Latest Updates ☛
  • Graphs: Introduction of graphs and types of graphs
  • SPOJ : Geeky solves geeky solution
  • Solution Code : Pass the time problem on SPOJ.
  • Find the minimum shortest path solution in c language ! !

Tuesday, August 13, 2013

Java program to shuffle the contents of array uniquely without repetition..

Java Code : Shuffling of Arrays uniquely

Shuffling of arrays elements can be done easily using the math.rand() function everyone thinks that...
But when you come to randomly shuffle the array's elements you will encounter problems like the arrays is not perfectly shuffled or it has repeated numbers in it.You can also come under the stituation that it takes more time than estimated due to its complexity.Here the provided java code not only suffles the the array elements uniquely but also reduces the time complexity of the method ..
In this code the swap is mainly used to swap the elements arbitarliy to the desired place and then it it reduces the array size thus coverning the other arrays elements and leaving that used elements at its place untill changes are made to access it.this algorithm is developed by one of the geeks so i tried to show you the way to apply into the java programming language .You can also shuffle any array of objects wgich is a plus point based on it.
/* Program to shuffle the contents of the array elements
 *
 * @author Code Author
 */
import java.util.*;
public class Array_shuffle {

    //method to shuffle the array uniquely
public static void shuffle(int a[])
   {
        int n = a.length;
        Random rand = new Random();  //using random function so as to randomly shuffle the contents of array
      
        for(int i=0;i<n;i++)
        {
            int change = i + rand.nextInt(n - i);
            swap(a,change,i); //calling swap method
            
        }
      
   }
    
//swap method swaps the chaged value with the positional value of i of the array
public static void swap(int[] a,int change,int i)
    {
    int temp = a[i];  //intially stored in temporary variable then swaping
    a[i] = a[change];
    a[change] = temp;
    }
    

//method to display the contents of the array --no need of explaination
public static void display(int[] a)
    {
        for(int na:a)
           System.out.print(na+" ");
    }
    

public static void main(String[] args) {
       Scanner console = new Scanner(System.in);
       int it=1;
       
       //create the array using specified number of the elements
       System.out.print("Enter the number of elements in the array : ");
       int n = console.nextInt();
       int[] a= new int[n];       //array created of size n
       
       
       //now adding the contents to the array
       System.out.println("\nFill the contents of the array : ");
        for(int j=0;j<a.length;j++ )
            a[j] = console.nextInt();
        
         //getting number of times to be shuffled
       System.out.println("Enter number of times array should be shuffled : ");
       int t =console.nextInt();
       
        
        //displaying the current array
        System.out.println("\nCurrent Array : ");
        display(a);
        
        while (t>0)
        {
            //calling the shuffle function to shuffle the array contents 
             shuffle(a);
        
            //Displaying the shuffled array
             System.out.printf("\nShuffled Array %dst Time : ",it);
             display(a);
             it++;
             t--;
        }

    }

}

The output for the shuffled arrays ca be seen here--
Enter the number of elements in the array : 10
Fill the contents of the array : 2 6 8 10 12 1 3 7 20 25
Enter number of times array should be shuffled : 5

Current Array : 2 6 8 10 12 1 3 7 20 25 

Shuffled Array 1st Time : 1 12 7 20 3 2 6 8 25 10 
Shuffled Array 2st Time : 7 25 1 2 3 12 6 20 8 10 
Shuffled Array 3st Time : 2 20 1 25 12 3 8 10 6 7 
Shuffled Array 4st Time : 1 10 7 2 25 3 12 6 8 20 
Shuffled Array 5st Time : 25 12 6 3 10 20 8 7 2 1 
Continue Reading...

Java Program to calculate sum of subsets using dynamic programming .. . .!!


Java Code : Sum of Subsets -Dynamic Programming

As explained earlier in the the program of sum of subsets given for C++ here the same fundamental or say basic working of the dynamic programming is use.
You can also check the C++ version of this program here
Dynamic programming works on the certain criteria
which  are explained into the comments as a wholesum.If any futher queries is to be asked regarding the working of the program or about the program's Dynamic approach users can just give their comments which are welcomed.


//Java Program to find subsets of desired sum using DP approach...
/**
 * @author Code Author
 */
import java.util.*;
public class Sum_of_subset {
    static Scanner console = new Scanner(System.in);
    
     //getting the number of elelments  thus defining array size globally so it can be used to define arraysize
       final static int n=console.nextInt();
       static int sum;
       
       // declaring and initializing array of size n
       // set : consistes of the set of numbers
       // receive : consistes of the subset included into the array to form desired sum
       static int[] set = new int[n];
       static int[] receive = new int[n];
       

    //Function to calculate sum of subset
    //w=intial weight or sum
    //total = total of the arrays elements
    public static void SOS(int i,int w,int total)
    {
     if(Acceptable(i,w,total))
     {
         //checking whether the weights are now equal to sum of subset or not
         if(w==sum)
         {
            //printting the subsets 
             System.out.println("Subset : ");
         
            for(int p=0;p<=i;p++)
            {
              if(receive[p]==1)
                 System.out.print(set[p]+" ");
            }
             System.out.println();
             return;   
         }
        receive[i+1]=1; //get the value here
      
        //calling recursively again by adding w i.e weight to the set[i+1] 
         //and simultaneously reducing that much from the total value 
         //to main the equilibrium betwweeen the datas 
         SOS(i+1,w+set[i+1],total-set[i+1]);
      
         //similary continuing for the all the elements
         receive[i+1]=0;
         SOS(i+1,w,total-set[i+1]);
         
     }
      
     
    }
    
    //method to check whether the given element is acceptable 
    //or not to be included into the array set whose sum should 
    //be equal to the given sum of subset
    //if it is return true else return false as not possible
    public static boolean Acceptable(int i,int w,int total)
    {
      if((w+total>=sum)&&(w==sum||w+set[i+1]<=sum)) 
          return true;
      return false;
    }
    
    static void print(int[] set)
    {
        for(int a:set)
            System.out.print(a + " ");
    }

public static void main(String[] args) {
     int total=0;
     System.out.println("Number of Elements : "+n);

    // Adding contents to the array
     System.out.print("Enter the contents of the array in any order : ");                
     for(int i =0;i<set.length;i++)
     {
         set[i] = console.nextInt();
         total +=set[i];
     }
     //sorting the array if not in ascending order for proper application of dynamic programming
     Arrays.sort(set);  
      
     //displaying the sorted array
     System.out.println("\nYour array is : ");
     print(set);
     
     System.out.println("Total is : "+total);
     
     //getting the sum to be calculated
     System.out.println("Enter the sum to be calculated i.e Sum of Subset : ");
     sum = console.nextInt();
     
     //calling the Sum of subset method
     SOS(-1,0,total);
     
    }

}
The output of the program is given as-----
10
Number of Elements : 10
Enter the contents of the array in any order : 19 1 3 12 5 6 10 15 18 9

Your array is : 1 3 5 6 9 10 12 15 18 19
Total is : 98
Enter the sum to be calculated i.e Sum of Subset : 20
Subset  : 1 3 6 10 
Subset  : 1 9 10 
Subset  : 1 19 
Subset  : 3 5 12 
Subset  : 5 6 9 
Subset  : 5 15 
Continue Reading...

C++ Program to calculate the sum of subsets using dynamic programming.. ! !

C++ : Sum Of Subset using Dynamic Programming

In this problem code we use the concept of dynamic programming to capture the subset of a given number set whose sum to be equal to the provided input,here it takes the combination of the numbers from the set of numbers whose sum is  provided and simultaneously checking the condition  that is it promising to include the number into the includeable array in order to receive desired value of sum if condition is true then it includes inti include able array else move forward and checks for next ,similarly it checks for various combination eliminating which are already used.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//C++ program to calculate sum of subset
//by Code Author


#include<stdio.h>
#include<conio.h>

//declaring arrays for weight i.e which contains number set
int w[10],include[10];
int n,sum;

//function prototyping
int promising(int i,int weight,int total);
void sofsubset(int i,int weight,int total);

main()
{
int i,total=0; //initialization of total

//providing total number of numbers in the set
printf("Enter the no. of numbers : ");
scanf("%d",&n);

//printing numbers in increasing order
//caution:numbers must be given in ascending order
printf("Enter the numbers in Increasing order : ");
for(i=0;i<n;i++)
{
scanf("%d",&w[i]);
//here total is automatically calculated inorder to supply to the sum of the subset
total = total + w[i];
}


printf("Enter the required sum for which subset should be given out : ");
scanf("%d",&sum);
sofsubset(-1,0,total);
getch();
}

//function to calculate sum of subset for given sum value
void sofsubset(int i,int weight,int total)
{
int j;
if(promising(i,weight,total)) //calling the checking method
{
if(weight==sum)
{
printf(" The subsets are : ");
for(j=0;j<=i;j++)
{
if(include[j]==1)
printf(" %d ",w[j]);
}
printf("\n");
return;
}
include[i+1]=1;
sofsubset(i+1,weight+w[i+1],total-w[i+1]);
include[i+1]=0;
sofsubset(i+1,weight,total-w[i+1]);

}

}

//function to check the promising condition of the sum of the subset and return accordingly
int promising(int i,int weight,int total)
{

if((weight+total>=sum)&&(weight==sum||weight+w[i+1]<=sum))
return 1;
return 0;
}




The output for the given code is ------


Enter the no. of numbers : 8
Enter the numbers in Increasing order : 2 5 8 9 12 15 17 20
Enter the required sum for which subset should be given out : 17
The subsets are : 2 15
The subsets are : 5 12
The subsets are : 8 9
The subsets are : 17

Continue Reading...

Java Solution for Next Pallindrome number finder !!

Next Pallindrome Number Finder


This question i received while solving a problem on SPOJ so i made a solution to this question and wanted to give this idea to other fellows the question was like that----

"A positive integer is called a palindrome if its representation in the decimal system is the same when read from left to right and from right to left. For a given positive integer K of not more than 10000000 digits, write the value of the smallest palindrome larger than
                                                      K to output.Number  are always displayed without leading zeros."


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//Java program to print next pallindrome number of given number K where 0<=k<=100000000 

/**
* @author Code Author
*/
import java.util.*;
class Pallindrome {

//method to find if number ids pallindrome or not and return either true or false
static boolean next_pallin(int k)
{
boolean flag = true;

//converting the number into string type
String str =String.valueOf(k);

//getting the length of the string
int c = str.length();

//dividing the string length
int m = c/2;
int i=0;

while(m>0)
{
//checking char at first and last from middle
if(str.charAt(i)!=str.charAt(c-i-1))
flag=false;

i++;
m--;
}

//returning the status os string i.e number k
return flag;
}


public static void main(String[] args) {
Scanner console =new Scanner(System.in);

//getting number of test cases
int t = console.nextInt();
int k;

while(t>0)
{
k =console.nextInt(); //input for the k

/* Here we apply do-while loop but not while loop bcoz.
* we have to check the next number is pallindrome or not
* but not the given number inorder to do so we always
* start with k+1 value so intial increment is must else if apply
* while loop it will print the same number for k and
* if we apply for k+1 it will always bypass a number */

do k++;
while(!next_pallin(k));

//printing next pallindrome number
System.out.println(k);
t--;
}
}

}


Here the first line contains the test conditions for which wwe have to find the palindromes and the next line should be as given accordingly

The OUTPUT of the code is here -----


Enter number of test cases : 5
Enter your number : 0
The next pallindrome number is : 1

Enter your number : 123
The next pallindrome number is : 131

Enter your number : 3123
The next pallindrome number is : 3223

Enter your number : 947485
The next pallindrome number is : 947749

Enter your number : 16928683
The next pallindrome number is :16933961

Continue Reading...

Saturday, August 10, 2013

C program to generate Prime Numbers between two given numbers ! !


Prime number Generator in C language

The C version of the prime number generator as givern earlier for java version this uses same working concepts as java....
A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. A natural number greater than 1 that is not a prime number is called a composite number. For example, 5 is prime because only 1 and 5 evenly divide it, whereas 6 is composite because it has the divisors 2 and 3 in addition to 1 and 6. Thefundamental theorem of arithmetic establishes the central role of primes in number theory: any integer greater than 1 can be expressed as a product of primes that is unique up toordering. The uniqueness in this theorem requires excluding 1 as a prime because one can include arbitrarily many copies of 1 in any factorization, e.g., 3, 1 × 3, 1 × 1 × 3, etc. are all valid factorizations of 3.
Source:Wikipedia : Prime_number
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//Program to generate prime number
//*** By CodeAuthor

#include<stdio.h>

void prime(int m,int n) //function to generate prime numbers
{ 
  if(m>n)
         return;

   int j=2;
   int flag=1;
   while(j<m)
        {
             if(m%j==0)
             flag = 0;
            j++;
        }
   if(flag)
      printf("%d ",m);  //printing numbers
   prime(m+1,n);       //recalling self
}


int main()
{
int m,j,n,t;
printf("Enter test cases : ");
scanf("%d ",&t);

        
while (t > 0)
{
       printf("\nEnter starting and ending  numbers : ");
       scanf("%d",&m);   //starting no.
       scanf("%d",&n);   //ending no.
             
       if(m==1 || m==0)
               m=2;
       printf("\nThe nubers are : ");       
       prime(m,n);   //calling function
            
       printf("\n");
       t--;
            
}
        
getch();
        
}
 

The output of the program is -----



Enter test cases : 3

Enter starting and ending  numbers :0 10
The numbers are : 2 3 5 7

Enter starting and ending  numbers : 1 20
The numbers are : 2 3 5 7 11 13 17 19

Enter starting and ending  numbers : 50 70
The numbers are : 53 59 61 67
Continue Reading...

Java program to generate Prime numbers between given two numbers ! ! !

Prime number Generator :

It can also be considered as a solution to the SPOJ classic problem it has some code exceptions which can also be by pass using try and catch method of java exception handling*********









 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
 * @author CodeAuthor
 * 
 */

import java.util.*;
class PRIME1 {
 
static void prime(int m,int n)
{ 
    if(m>n)
        return ;
    int j=2;
    boolean flag=true;
    while(j<m)
        {
            if(m%j==0)
                flag = false;
            j++;
        }
    if(flag)
      System.out.print(m + " "); //printing the numbers
     prime(m+1,n);  //recalling self 
}
   
public static void main(String[] args) {
        Scanner c = new Scanner(System.in);
        int m,g,n;
        System.out.println("Enter number of test cases : ");
        int t=c.nextInt(); //getting the test cases
       
           while (t > 0)
        {
           System.out.println("Enter the starting and ending point between which prime numbers to be shown : ");
             m=c.nextInt(); //get starting number
             n = c.nextInt(); //get ending number
             
             System.out.print("The prime numbers between "+ m +" and " + n + " are :" );
             //check for if m==1 or m==0
             if(m==0 || m==1)
                 m=2;
             prime(m,n); //call the prime function

        System.out.println();
        t--;
            
        }
       }
}
The output for the program is --- - - - - -







Enter number of test cases : 
3
Enter the starting and ending point between which prime numbers to be shown : 
0 10
The prime numbers between 0 and 10 are :2 3 5 7 

Enter the starting and ending point between which prime numbers to be shown : 
1 30
The prime numbers between 1 and 30 are :2 3 5 7 11 13 17 19 23 29 

Enter the starting and ending point between which prime numbers to be shown : 
37 100
The prime numbers between 37 and 100 are :37 41 43 47 53 59 61 67 71 73 79 83 89 97 
Continue Reading...

Friday, August 9, 2013

C++ program to perform MergeSort using Divide and conquer technique..



Merge Sort using C++

  This program makes the use of recursion in order to sort the elements of the array. The technique used here is of the famous algorithm divide and conquer. Its complexity is O(n log n).







 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include<stdio.h>
#include<conio.h>

//function prototyping
void mergesort(int *a,int *temp,int l,int u);
void merge(int *a,int *temp,int l,int u);

//main method to perform operations
main()
{
      int n;      
      printf("Enter the value of n-array size");
      scanf("%d",&n);
     
      //declaring arrays
      int a[n];
      int temp[n];

      
      //adding contents to array
      for(int i=0;i<n;i++)
     {
               scanf("%d   ",&a[i]);
               temp[i]=0; //intializing temp
     }
      
      puts("Array before sorting : ");
      for(int i=0;i<n;i++)
      printf("%d   ",a[i]);
      
      //calling function
      mergesort(a,temp,0,n-1);
      
      //Displaying sorted array
      puts("\nArray after sorting");
      for(int i=0;i<n;i++)
      printf("%d   ",a[i]);
      getch();
}

//functon to mergesort elements of array
void mergesort(int *a,int *temp,int l,int u)
{
       int m; 
       if(l<u)
       {
             m=(l+u)/2;
             mergesort(a,temp,l,m);
             mergesort(a,temp,m+1,u);
             merge(a,temp,l,u);
       }
}

//function to merge array elements
void merge(int *a,int *temp,int l,int u)
{
         int m=(l+u)/2;
         int i=l,j=m+1;
         int c;
         for(c=l;i<=m&&j<=u;c++)
         {
                if(a[i]==a[j])
                {
                    temp[c++]=a[i];
                    temp[c]=a[i];
                    i++;
                    j++;
                }
                else
                {
                    if(a[i]<a[j])
                    {
                        temp[c]=a[i];
                        i++;
                    }
                    else
                    {
                        temp[c]=a[j];
                        j++;
                    }
                }
         }
         for(;i<=m;)
         temp[c++]=a[i++];
         for(;j<=u;)
         temp[c++]=a[j++];
         for(i=l;i<=u;i++)
         a[i]=temp[i];
}                                    

The output of the program is--------------------


Enter the value of n-array size 10
18 45 3 11 8 0 32 1 67 2

Array before sorting :
18   45   3   11   8   0   32   1   67   2

Array after sorting
0   1   2   3   8   11   18   32   45   67
Continue Reading...

Java Program for MergeSort using Divide and Conquer Method

Java Code : Merge Sort


Merge Sort is an important program in terms of reducing the time execution for sorting of the array elements in a simple way.
Merge Sort has a complexity of O(nlogn) as shown in here.
The time complexity can be reduced to O(n) if used with binary trees so stay updated for program code of MergeSort using binary trees...




  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
/**
 * @author
 * Code Author
 */
import java.util.*;
public class D_C_MergeSort {
   static Scanner console = new Scanner(System.in); 
   
   
   //method for sorting array elements using merge sort
   public static void mergesort(int[] a,int[] t,int l,int u)
   {
       int m ;
        if (l<u)
        {
            m = (l+u)/2;      //middle term
            mergesort(a,t,l,m); //using rcursive method 
            mergesort(a,t,m+1,u);
            merge(a,t,l,u);
        }
   }
   
   //method for merging array elements 
   public static void merge(int[] a,int[] t,int l , int u)
   {
    int m =(l+u)/2;
    int i=l,j=m+1;
    int k;
    
    for(k=l;i<=m && j<=u;k++)
    {
        if(a[i]==a[j])
        {
         t[k++]=a[i];
         t[k]=a[i];
         i++;
         j++;
        }
        else if(a[i]<a[j])
        {
            t[k]=a[i];
            i++;
        }
        else
        {
            t[k]=a[j];
            j++;
        }
    }
    
    //filling the sorted elemts
    for(;i<=m;)
         t[k++]=a[i++];
    for(;j<=u;)
        t[k++]=a[j++];
    
    //copying content to original array
    for(i =l;i<=u;i++)
        a[i]=t[i];
    
    
   }
    
   public static void main(String args[])
   {    
       
       
       //giving the aaray size to store the elements
       System.out.print("Enter the size of the array : ");
       int n = console.nextInt();
       
       //creating integer datatype array of size n
       int[] array = new int[n];
       int[] temp = new int[n]; //temporary array to store data
       
       //Filling the array
       System.out.print("Enter the contents to the array : ");
       for(int i = 0;i<=n-1;i++)
       {
         array[i]=console.nextInt();  
       }
       
       //displaying array content before sorting
       System.out.print("\n Unsorted array : ");
       for(int a:array)
         System.out.print(a + " ");
       System.out.println();
       
       //calling method mergesort to stort elements of the array
       mergesort(array,temp,0,n-1);
       
       //Displaying sorted array
       System.out.print("Sorted array is : ");
       for(int b:array)
       System.out.print(b +" ");
       System.out.println();
       
       
   }
}

 The sample output for the program is give as------------

run:
Enter the size of the array : 20
Enter the contents to the array : 8 1 4 7 22 11 8  4 5 65 23 86 21 3 7 0 2 91 217 9

 Unsorted array : 8 1 4 7 22 11 8 4 5 65 23 86 21 3 7 0 2 91 217 9 
Sorted array is : 0 1 2 3 4 4 5 7 7 8 8 9 11 21 22 23 65 86 91 217 


Continue Reading...
Privacy Policy | Disclaimer | Terms of Service

Copyright © 2013, Code Author. Powered by Blogger.