Monday, October 22, 2012

Search Pattern in Java

Program to find a specific pattern from a given text or file is stated as below.



import java.io.*;

class srchPattern
{
  public static void main(String args[])
  {
    if(args.length == 0 || args.length == 1)
    {
      System.out.println("Insufficient arguments...");
      return;
    }

    File f = new File(args[1]);

    try
    {
      BufferedReader i = new BufferedReader(new FileReader(args[1]));

      String line;
      int ct = 0;

      if(f.exists() && f.isFile())
      {
        while((line = i.readLine()) != null)
        {
          if((line.indexOf(args[0])) != -1)
          {
            ct++;
          }
          System.out.println(line + " ");
        }

        if(ct == 0)
        {
          System.out.println("Pattern not Found");
        }
        else
        {
          System.out.println("Pattern found in the file...");
          System.out.println("Number of Occurances of the word " + args[0] + " in te file " + args[1] + " is " + ct);
        }
      }
    }
    catch(Exception e){}
  }
}

Word,character count in Java

Program  to count the number of occurrences of a word in a file is given as below:


import java.io.*;

class wordcnt
{
  public static void main(String args[])
  {
    int i = 0,cnt = 0;
    try
    {
      FileInputStream fin = new FileInputStream("d:/java/wordcnt.java");
      String word;
      char ch , charr[];
      charr = new char[100];
      String w = new String("word");
      while(( ch = (char)fin.read()) != -1)
      {
        if( ch != ' ' && ch != '\n')
        {
           charr[i] = ch ;
           i++;
        }
        else
        {
           word = new String(charr,0,i);
           if(word.equals(w))
              cnt++;   
           if( ch == '\n')
              System.out.println( word );
           else
              System.out.print( word + " ");
           i = 0;
        }
     };
     fin.close();
    }
    catch(Exception ie)
    {
    }
    System.out.println("\n\nWord Count : " + cnt);
  }
}

Copy file in Java

Program to copy a file content in java is as follows:

 import java.io.*;

class FileCopy
{
  public static void main(String args[]) throws IOException
  {
    FileInputStream fin = new FileInputStream("d:/java/stk.java");
    FileOutputStream fout = new FileOutputStream("d:/java/txtfile.txt");
    int b;

    while(true)
    {
      b = fin.read();
      if(b == -1)
      {
        break;
      }
      System.out.print((char)b);
      fout.write(b);
    }

    fin.close();
    fout.close();
  }
}

Polynomial operations in Java

Program for Ploynomial expression in java is as follows:


import java.lang.*;
import java.io.*;
class term
{
  int coeff,exp;
}
class poly
{
    term pl[] = new term[10];
    int n;
    poly()throws Exception
    {
        poly p[]=new poly[10];
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the no. of terms: ");
        n=Integer.parseInt(br.readLine());
    }
    public void getPoly()throws Exception
    {
        poly p[]=new poly[10];
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the base & exponent:");
        for(int i=0;i<n;i++)
        {
            p[i].coeff=Integer.parseInt(br.readLine());
            p[i].exp=Integer.parseInt(br.readLine());
        }
    }   
    public void putPoly()
    {
        poly p[]=new poly[10];
        System.out.println("Polynomial is : ");
        for(int i=0;i<n;i++)
        {
            System.out.println(" "+p[i].coeff+"x^"+p[i].exp);
        }
    }
    public void evalPoly()throws exception
    {
        poly p[]=new poly[10];
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int x,ans=0;
        System.out.println("Enter the value for x:");
         x=Integer.parseInt(br.readLine());   
        for(int i=0;i<n;i++)
        {
            ans=ans+p[i].coeff*pow(x,p[i].exp);
        }
        System.out.println("Ans : "+ans);
    }
    public static void main(String args[])throws Exception
    {
        poly p1=new poly();
        poly p2=new poly();
        p1.getPoly();
        p2.getPoly();
        p1.putPoly();
        p2.putPoly();
        p1.evalPoly();
       
    }   
}

Matrix in Java

Program for matrix in java is as follows:


import java.io.*;

class matrix
{
  int mat[][],r,c;

  matrix()
  {
     mat = new int[10][10];
  }
  public void getMat() throws Exception
  {
   // mat = new int[10][10];
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("\nEnter the Dim of the matrix : ");    
    r = Integer.parseInt(br.readLine());
    c = Integer.parseInt(br.readLine());

    System.out.println("\nEnter the matrix elements : ");    
    for(int i = 0 ; i < r ; i++)
    {
      for(int j = 0 ; j < c ; j++)
      {
        mat[i][j] = Integer.parseInt(br.readLine());
      }
    }
  }

  public void addMat(matrix m1,matrix m2)
  {
     r = m1.r;
     c = m1.c;

     for(int i = 0 ; i < r ; i++)
    {
       for(int j = 0 ; j < c ; j++)
       {
          mat[i][j] = m1.mat[i][j] + m2.mat[i][j];
       }
    }
  }

  public void putMat()
  {
    System.out.println("\nMatrix is : \n");
    for(int i = 0 ; i < r ; i++)
    {
      for(int j = 0 ; j < c ; j++)
      {
        System.out.print(" " + mat[i][j]);
      }
      System.out.println("");
    }
  }

  public static void main(String args[]) throws Exception
  {
    matrix m1 = new matrix();
    matrix m2 = new matrix();
    matrix m3 = new matrix();

    m1.getMat();
    m2.getMat();

    m1.putMat();
    m2.putMat();

    m3.addMat(m1,m2);
    m3.putMat();
  } 
}

Linear Search in Java

Below is simple program in java which shows the linear search.


import java.io.*;

class LinearSearch
{
  int ar[];
  int ele,n;

  public void setData() throws Exception
  {
     ar = new int[10];
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter the size for array : ");    
    n = Integer.parseInt(br.readLine());

    System.out.println("Enter the data for array : ");    
    for(int i = 0 ; i < n ; i++)
    {
      ar[i] = Integer.parseInt(br.readLine());
    }
    
    System.out.println("Enter the data to be searched : ");
    ele = Integer.parseInt(br.readLine());
  }

  public void putData()
  {
    System.out.println("The array is : ");
    for(int i = 0 ; i < n ; i++)
    {
      System.out.println(" " + ar[i]);
    }
  }

  public void LinSrch()
  {
    int i;
   
    for(i = 0 ; i < n ; i++)
    {
      if(ar[i] == ele)
      {
        break;
      }
    }
    if(i == ar.length)
    {
      System.out.println("\nElement not found");
    }
    else
    {
      System.out.println("\nElement found at " + i);
    }
  }

  public static void main(String args[]) throws Exception
  {
    LinearSearch ln = new LinearSearch();
    ln.setData();
    ln.putData();
    ln.LinSrch();
  }

}

Vector Demo in Java

Program for vector in java.

Below is the program.

import java.util.*;

class vectorDemo
{
    public static void main(String args[])
    {
        Vector v = new Vector(3,2);

        System.out.println("Intial Size : " + v.size());
        System.out.println("Intial Capacity : " + v.capacity());

        v.addElement(new Integer(1));
        v.addElement(new Integer(2));
        v.addElement(new Integer(3));
        v.addElement(new Integer(4));

        System.out.println("Capacity after 4 additions : " + v.capacity());
        v.addElement(new Double(4.55));
        System.out.println("Capacity after adding double element : " + v.capacity());       
    }
}

Array Keys and Array Values

Below is Simple Example which shows how the array keys or array values can be obtained from a array.


<?php

     $personinfo=array(array("name"=>"john","address"=>"pune","age"=>30),
          array("name"=>"Sathya","address"=>"Nashik","age"=>39),
          array("name"=>"madhav","address"=>"pune","age"=>22));

      $arr1=array_keys($personinfo);

      $arr2=array_values($personinfo);

       echo "OUTPUT AS ONLY KEYS FOR GIVEN ARRAY";
       echo "<br><br>";
       print_r($arr1);

      echo "<br><br>";   
      echo "OUTPUT AS ONLY VALUES FOR GIVEN ARRAY";
      echo "<br><br>";
      print_r($arr2);

?>

PHP Function to create slug from string

Here is simple Function to create slug from string.



function getSlug($title)
             {
                        $slug = preg_replace("/[^a-zA-Z0-9 ]/", "", $title);
                           $slug = str_replace(" ", "-", $slug);
                        $slug=strtolower($slug);
                        return($slug); 
  }

PHP Function to generate random unique string.

Here is a Simple Function to generate random unique string.



            function GenerateNumber($min, $max)
{
                        // Create the meta-password
                        $sMetaPassword = "";
                        global $CONFIG;
                        $ahPasswordGenerator = array(
                        "C" => array('characters' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'minimum' => $min, 'maximum' => $max),
//"S" => array('characters' => "!@()-_=+?*^&", 'minimum' => 2, 'maximum' => 2
"N" => array('characters' => '1234567890', 'minimum' => $min, 'maximum' => $max)
);
                        foreach ($ahPasswordGenerator as $cToken => $ahPasswordSeed)
$sMetaPassword .= str_repeat($cToken, rand($ahPasswordSeed['minimum'], $ahPasswordSeed['maximum']));
                                    $sMetaPassword = str_shuffle($sMetaPassword);
                        // Create the real password
                        $arBuffer = array();
                        for ($i = 0; $i < strlen($sMetaPassword); $i ++)
$arBuffer[] = $ahPasswordGenerator[(string)$sMetaPassword[$i]]['characters'][rand(0, strlen($ahPasswordGenerator[$sMetaPassword[$i]]['characters']) - 1)];
                        return implode("", $arBuffer);

PHP Function to check whether the given number is decimal or not.

Below is a simple Function to check whether the given number is decimal or not.



function check_decimal($dec_val, $decimals = 2)
{
                        $pattern = "/^[-]*[0-9][0-9]*\.[0-9]{".$decimals."}$/";
                        if (preg_match($pattern,  $dec_val))
                                    return true;
                        else
                                    return false;
}

PHP Function to check whether a given date is valid or not.

Here is a Simple Function to check whether a given date is valid or not.



           function is_valid_date($value, $separator='-')
{
              if(strlen($value) <= 10)
                        {
                        // check date
                        $arr=explode($separator,$value);
                        $day=$arr[2];
                        $month=$arr[1];
                        $year=$arr[0];
                        if(@checkdate($month, $day, $year))
                                    return true;
              }
             return false;
}

PHP Function to calculate days difference between given 2 dates.

Here is a simple  Function to calculate days difference between given 2 dates.



function daysDifference($endDate, $beginDate)
{

              //explode the date by "-" and storing to array
             $date_parts1=explode("-", $beginDate);
             $date_parts2=explode("-", $endDate);
             //gregoriantojd() Converts a Gregorian date to Julian Day Count
            $start_date=gregoriantojd($date_parts1[1], $date_parts1[2], $date_parts1[0]);
             $end_date=gregoriantojd($date_parts2[1], $date_parts2[2], $date_parts2[0]);
             return $end_date - $start_date;
}

PHP Function to convert date from mm/dd/yyyy to yyyy-mm-dd

Here is a simple Function to convert date from  mm/dd/yyyy to yyyy-mm-dd.



function convert_date($date)
{
                        if($date=='')
                        return '';
                     else
                        $dateArray=explode('/',$date);

                        return "$dateArray[2]-$dateArray[0]-$dateArray[1]";
}

PHP Function to validate an email address

Here is a simple Function to validate an email address in php.



function check_email($mail_address)
{
                        if($mail_address == '')
                        {
                                    return false;
                        }
                        else
                        {
if (preg_match("/^[0-9a-z]+(([\.\-_])[0-9a-z]+)*@[0-9a-z]+(([\.\-])[0-9a-z-]+)*\.[a-z]{2, 4}$/i",  strtolower($mail_address)))
                                    return true;
                        else
                                    return false;
                        }
}

PHP Function to get extension of a file.

Here is a simple function which returns the extension of the file.



           function getExtension($str)
{
                        $i = strrpos($str,".");
                        if (!$i) { return ""; }
                        $l = strlen($str) - $i;
                        $ext = substr($str,$i+1,$l);
                        return $ext;

MS SQL : How to identify fragmentation in your indexes?

Almost all of us know what fragmentation in SQL indexes are and how it can affect the performance. For those who are new Index fragmentation...