Programming Geek
Rated 4.1/5 based on 446 reviews

Inserting Image in Database using JDBC

The following program reads an image character by character and inserts in database:

import java.sql.*;
import java.io.*;
public class BlobImages{
 public static void main(String[] args)    throws Exception 
 {
  try {
   Class.forName("com.ibm.db2.jcc.DB2Driver");
  } catch (Exception e) {
   System.out.println(e);
   System.exit(0); 
  }
  Connection con = DriverManager.getConnection("jdbc:db2://127.0.0.1:50000/SAMPLE","db2admin","db2admin");    
  Statement stmt=null;
  try {     
   stmt = con.createStatement();
   //to create table with blob field (One time only)
   stmt.executeUpdate("CREATE TABLE EmpPhoto (EmpId varchar (10) , EmpName varchar (50) , EmpPhoto BLOB (5M), filePath varchar(100))");
  } catch (Exception e) {
   System.out.println("Tables already created , skipping table creation process");
  }
  String empId="3222";
  String empName="John";
  String empPhotoFile="D:\\v\\Bhubaneswar@Infy\\about.png"; // photo file name
  int success=0;
  PreparedStatement pstmt = con.prepareStatement("INSERT INTO EmpPhoto VALUES(?,?,?,?)");
  pstmt.setString(1, empId);
  pstmt.setString(2, empName);
  pstmt.setBytes(3,readImage(empPhotoFile));   
  pstmt.setString(4,empPhotoFile);
  success =    pstmt.executeUpdate();
  if(success>=1)  System.out.println("New Employee detail added");
  
  

  ResultSet rs = stmt.executeQuery("Select * from EmpPhoto");  

  
  
  if (rs.next()) {  

   String filename = "vvv.png";  
   Blob blob = rs.getBlob("EmpPhoto");  
   InputStream is = blob.getBinaryStream();  
   FileOutputStream fos = new FileOutputStream("D:\\" + filename);  

   int b = 0;  
   while ((b = is.read()) != -1)  
   {  
    fos.write(b);   
   }  
  }   con.close(); 
 }
 //to read image from the physical file. 
 private static byte[] readImage(String filename) {

  byte[]  imageData = null;
  FileInputStream file = null;
  try {
   file = new FileInputStream(filename);
   int size = file.available();
   imageData = new byte[size];
   file.read(imageData);
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    if (file != null) file.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
  return imageData;
 }
}

Pascal Triangle


The Pascal triangle problem can be understood by the following visualization:



Each row of a pascal triangle can be viewed as the coefficients of the expansion of (x + y)n  .

The following program prints the pascal triangle separated by space with O(n*n) complexity .


import java.math.*;

public class Solution {

    public static void main(String[] args) {
      
        printPascal(Integer.parseInt(args[0]));
    }
    static void printPascal(int n)
{
  for (int line = 1; line <= n; line++)
  {
    BigInteger b=BigInteger.valueOf(1); 
    for (int i = 1; i <= line; i++)  
    {
      System.out.print(b+" ");  
      b = b.multiply(BigInteger.valueOf(line - i));
      b=b.divide(BigInteger.valueOf(i));    
          
    }
    System.out.println();
  }
}
}

Sum of Subset

The Sum of Subset problem can be give as: Suppose we are given n distinct numbers and we desire to find all combinations of these numbers whose sums are a given number ( m ).

For example, if n=4 i.e there are four numbers as: 1, 2, 3, 4, 5 and m=5 the all possible subsets are as : {1,4},{2,3},{5}

The following programs finds all subsets using backtracking:

JAVA implementation:


import java.util.Scanner;

/**
 *
 * @author VIK VIKKU VIKASHVVERMA VIKASH
 *
 * @Website: http://vikash-thiswillgoaway.blogspot.com
 * 
 */
public class SumOfSubsets {

    int[] w;
    int[] x;
    int sum;

    public void process() {
        getData();
    }

    private void getData() {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the number of elements:");
        int n = sc.nextInt();
        w = new int[n + 1];
        x = new int[n + 1];
        int total = 0;
        System.out.println("Enter " + n + " Elements :");
        for (int i = 1; i < n + 1; i++) {
            w[i] = sc.nextInt();
            total += w[i];
        }
        System.out.println("Enter the sum to be obtained: ");
        sum = sc.nextInt();
        if (total < sum) {
            System.out.println("Not possible to obtain the subset!!!");
            System.exit(1);
        }
        subset(0, 1, total);
    }

    private void subset(int s, int k, int r) {
        int i = 0;
        x[k] = 1;
        if (s + w[k] == sum) {
            System.out.println();
            for (i = 1; i <= k; i++) {
                System.out.print("\t" + x[i]);
            }
        } else if ((s + w[k] + w[k + 1]) <= sum) {
            subset(s + w[k], k + 1, r - w[k]);
        }
        if ((s + r - w[k]) >= sum && (s + w[k + 1]) <= sum) {
            x[k] = 0;
            subset(s, k + 1, r - w[k]);
        }
    }

    public static void main(String[] args) {
        new SumOfSubsets().process();
    }
}

       
   
C Implementation:

#include < stdio.h >

void sumOfSub(int,int,int);
static int m=0;
int*w;
int*x;
void main()
{ int i=0,sum=0,n=0;
 printf("Enter size of array: ");
 scanf("%d",&n);
 w=(int*)malloc(sizeof(int)*n+1);
 x=(int*)malloc(sizeof(int)*n+1);
 printf("Enter %d elements: ",n);
 for(i=1;i < =n;i++)
 {
  scanf("%d",&w[i]);
  sum+=w[i];
  x[i]=0;
 }
 printf("Enter the sum to be obtained: ");
 scanf("%d",&m);
 if(sum < m)
 {
 printf("Not possible to obtain any subset !!! ");
 exit(1);
 }
 printf("Possible Subsets are( 0 indicates exclusion and 1 indicates inclusion) : ");
 sumOfSub(0,1,sum);
}

void sumOfSub(int s,int k,int r)
{ int i=0;
 x[k]=1;
 if(s+w[k]==m)
 { printf("\n");
  for(i=1;i < =k;i++)
  printf("\t%d",x[i]);
 }
 else if((s+w[k]+w[k+1]) < =m)
 {
  sumOfSub(s+w[k],k+1,r-w[k]);
 }
 if((s+r-w[k]) > =m && (s+w[k+1]) < =m)
 {
  x[k]=0;
  sumOfSub(s,k+1,r-w[k]);
 }
}
     

All Permutations


All Permutations of a Set of Elements

Let us have a set of n elements; the objective is to find all the possible permutations of this set. For example if we have a set of four elements viz. {a, b, c} then we need to print all the permutation of a, b and c as give below:

1)      { a, b, c}
2)      { a, c , b}
3)      { b, a, c}
4)      { b, c, a}
5)      { c, a, b}
6)      { c, b, a}

Clearly for a set of n elements there exists n! different permutations.  One way to generate permutations is to iterate through n nested loops but that will be hardcoded approach as n may vary from time to time.  So one flexible approach is to generate the permutation recursively.  Let us have a set of three elements {a, b, c,} now to generate permutation follow these steps:

1) Fix a and generate permutation of { b, c }
2) Fix b and generate permutation of { a, c }
3) Fix c and generate permutation of { a, b }


The pseudo code for the recursive algorithm to generate all permutation is as below:


permute(a,k,n)
{
 if(k==n) then print a[1..n]     // output permutation
 else
  for i=k to n do
  {
   t=a[k];a[k]=a[i]; a[i]=t;
   permute(a,k+1,n); // all permutation of a[k+1..n]
   t=a[k];a[k]=a[i]; a[i]=t;
  }
}

The calling function takes inputs and calls permute function passing three arguments a list of elements, start index and end index.

Inside permute it is checked whether start index and end index are same (if there is only one element) or not. If both are same then print the permutation else iterate through for loop and call permute function recursively.

The following program implements this pseudo code in C :


#include<stdio.h>
void permute(int* a,int k,int n);

void main()
{
 int i,n;
 int*a;
 scanf("%d",&n);
 a=(int*)calloc(n,sizeof(int));

        for(i=0;i<n;i++)
 scanf("%d",&a[i]);
 permute(a,0,n-1);
}

void permute(int* a,int k,int n)
{ int i,t;
 if(k==n)
 {
  for(i=0;i<=n;i++)
  printf("%d\t",a[i]);
  printf("\n");
 }else
 {
  for(i=k;i<=n;i++)
  { 
   t=a[k];
   a[k]=a[i];
   a[i]=t;
   permute(a,k+1,n);
   t=a[k];
   a[k]=a[i];
   a[i]=t;
  }
 }
}


The output of the following program is as shown below:





Let us observe the output one by one:

The first line of input 3 is the number of elements to be entered y the user.
The second line of input consists of three input numbers 1, 2 and 3.
The remaining 6 lines are all permutations of the input elements i. e. all permutations of 1, 2 and 3.
Main function call permute function passing a, 0 and 2 as parameters.

First Call

Inside permute if condition is false hence else is executed. In else since i=0 and k=0 so no swapping. Here we have k=0, i=0 and  a[0]=1,a[1]=2 and a[2]=3. Now call again permute passing a, k+1(=1) and n(=2) as parameters.

Second Call

The value of  k and n differs so again else is executed. Inside else value of k and I is same so no swapping occurs hence i=1,k=1 and a[0]=1, a[1]=2 and a[2]=3. Call again permute function passing a, k+1(=2) and n(=2) as parameters.

Third Call

The value of k and n are same i.e. 2 hence if is executed and inside if content of list a is printed i. e. 1 2 3.

 Now control is transferred back to calling function i. e. to Second Call

[Third Call ends here]

Inside second Call again swap occurs. But i=1 and k=1 so actually no swapping. Again i is incremented by 1 hence value of i=2 and k=1 so swapping occurs i. e.  now a becomes a[0]=1, a[1]3 and a[2]=2 and now call permute passing a, k+1(=2) and n(=2) as parameters.

Fourth Call

The value of k and n are same i.e. 2 hence if is executed and inside if content of list a is printed i. e. 1 3 2.

 Now control is transferred back to calling function i. e. to Second Call

[Fourth Call ends here]

Inside second call swapping occurs as value of i=2 and k=1 so a[0]=1,a[1]=2 and a[2]=3. i is incremented by 1 and for condition becomes false hence control is transferred back to calling function i.e. First Call.

[Second call ends here]

Inside First Call Value of i and k are 0 hence again no swapping. Now i is incremented by 1 and it becomes 1. Now swapping occurs as i=1 and k=0. Hence revised list a is as a[0]=2, a[1]=1 and a[2]=3. And now call again permute  function passing a, k+1(=1) and n(=2) as parameters.
 Hence now again Second Call, Third Call and Fourth Call is repeated and following gets printed i.e. 2 1 3 and 2 3 1 and values of list a are a[0]=2, a[1]=1 and a[2]=3.

Again inside First Call swapping occurs as i=1 and k=0 and list a becomes a[0]=1, a[1]=2 and a[2]=3. 
Now i is incremented by 1 i. e. i becomes 2 now and k is 0  hence swapping occurs i. e. a[0]=[3] and a[1]=2 and a[2]=2 and  permute function is called passing a, k+1(=1) and n(=2) as parameters. Hence now again Second call Third Call and Fourth Call is repeated and following gets printed i. e. 3 2 1 and 3 1 2.

Again inside First call values are swapped and values of list a are a[0]=1, a[1]=2 and a[2]=3
[First Call ends here]

Hence values of list a remains intact after the completion of all recursive calls and all permutations are printed.