Property

Friday, December 19, 2014

Given an array of red, green and blue balls arrange them in groups of all red together, greens together and blue together. Do in a single scan of the array.

You have an array containing only '0's, '1's and '2's. Club same items together in single scan.

let's try to understand problem:



algorithm:
i)  initialize i and j to 0 and  k to n-1 Where n is  number of balls
ii) while j <= k  do
            if pointer  j point to red ball than
                     swap a[i] and a[j];
and  perform i++; j++

           if pointer  j point to white ball than
just perform j++

           if pointer  j point to blue ball than
swap a[j] and a[k];
         and  perform  k--;

This problem is also known as Dutch National Flag Problem. Check out how Dutch flag looks like:

code:
#include <stdio.h>

//here red->0, white->1, blue->2
int arr[] = { 0,1,0,2,2,0,1,1,0 };      
int arr_size = sizeof(arr)/sizeof(arr[0]);

void swap(int *a, int *b);
void dutchflag( ); 

int main()
{
  int c; 
  dutchflag();  
  printf("\ndutch flag Order: ");
  for (c = 0; c < arr_size; c++)
    printf("%d ", arr[c]);
   
  return 0;
}
/* test function to to Sort the balls in dutch flag order*/
void dutchflag( )
{
 int i = 0,j=0 , k = arr_size - 1;
 
   while(j <= k)
   {
      switch(arr[j])
      {
         case 0:
            swap(&arr[i++], &arr[j++]);
           break;
         case 1:
          j++;
           break;
         case 2:
          swap(&arr[j], &arr[k--]);
           break;
      }
   }
}

/* Function to swap *a and *b */ 
void swap(int *a, int *b)
{
  int temp = *a;
  *a = *b;
  *b = temp;
}


output:-
dutch flag Order: 0 0 0 0 1 1 1 2 2

Time Complexity:  O(n)

Thursday, December 11, 2014

Game of master mind: you have four balls, and four different colors, as a solution. The user tries to guess the solution. If they guess the right color for the right spot, it counts as a 'hit'. If it's the right color, but the wrong spot, it counts as a pseudo-hit.

For example: if the solution is 'RGGB' and the user guesses 'YRGB' they have 2 hits and one pseudo hit. Write a program to, given a solution and a guess, calculate the number of hits and pseudo hits.

Solution 1:
Algorithm:
1.Take an temp array of length ascii chars(256), although we need array of length of 4 here
taking above array will give advantage so that we set/reset the 1 or 0 at particular character
position according to their ascii value.
2.scan solution & guess string & set value to 1 in temp array for each matching character of
solution & guess string also increment the hits counter.else increment temp array location of
corresponding character location.
3.in 2nd pass over temp array check for each location if that location value is not equal to 1 &
also temp[location]>0 if yes then increment pseudo-counter & decrement corresponding character
count in temp array.
code:
#include <stdio.h> 
int main() 
{
char solution[]={'A','B','C','D'};
char guess[]    ={'A','E','D','D'};
int  arr[256],i,hits=0,pseudoHits=0;

for ( i = 0; i < 4; i++)  // initialize all char in solution to set
  arr[solution[i]]=1;  
 //arr[i]=00..111100... till 256 
 for ( i = 0; i < 4; i++) 
 {
  if (guess[i]== solution[i])  // if match then increment hit 
    hits++; 
   else
     arr[guess[i]]++;      //no match increment guess array  index by 1
}
//now array will look like arr[i]=00..111210... till 256 
//because in this example E and D does not mach hence we increment them
//but D was present in sol hence it value was 1 and after increment it become 2 
//and E was initially 0 and after increment it become 1
//note:all index having value 2 means they are already present in solution 
//but guess does not match
//hence to find pseudoHits we have to search for index value equal to 2
 for ( i = 0; i < 4; i++) 
 {
  if (arr[solution[i]]> 1) 
  {
     pseudoHits++;
     arr[solution[i]]--; 
   }
 }
printf("number of hits is %d\n",hits);
printf("number of pseudo hits is %d",pseudoHits); 
return 0;
}


output:-
number of hits is 2
number of pseudo hits is 1
but can we do better than this ?

yes
instead of using char array of length 256 we can take help of bits to make set/reset the 1 or 0 to keep track of particular character.

Solution 2:
code:
#include <stdio.h> 
int main() 
{
char solution[]={'A','B','C','D'};
char guess[]    ={'A','E','D','D'};
int solution_mask = 0,i,hits=0,pseudoHits=0;
for ( i = 0; i < 4; ++i) 
 solution_mask =solution_mask | 1 << (solution[i] - 64);  
 
 for ( i = 0; i < 4; ++i) 
 {
  if (guess[i]== solution[i]) 
  {
   hits++;
   }
 else if ((solution_mask & (1 << (guess[i] - 64))) >= 1) 
 {
   pseudoHits++;
  }
 }
printf("number of hits is %d\n",hits);
printf("number of pseudo hits is %d",pseudoHits); 
return 0;
}


output:-
number of hits is 2
number of pseudo hits is 1

time complexity:-  O(n)
space complexity:-  O(1)

Step By Step Execution:
initialize solution_mask to 0
Step 1:-
for ( i = 0; i < 4; ++i)
 solution_mask =solution_mask | 1 << (solution[i] - 64);

for i=0
let's break the things first,
1<<(solution[i] - 64)
1<<(A-64)
1<<1
0000 0001
after 1<<1
0000 0010
now
solution_mask = solution_mask | 1 << (solution[i] - 64)
00000000 | 00000010 =00000010
decimal of 00000010 is 2.
Therefore new value of solution_mask is 2.

for i=1
1<<(solution[i] - 64)
1<<(B-64)
1<<2
0000 0001
after 1<<2
0000 0100
Value of solution_mask is 2 and binary of 2 is 00000010
solution_mask = solution_mask | 1 << (solution[i] - 64)
00000010 | 00000100 =00000110
decimal of 00000110 is 6.
Therefore new value of solution_mask is 2.

for i=2
1<<(solution[i] - 64)
1<<(C-64)
1<<3
0000 0001
after 1<<3
0000 1000
Value of solution_mask is 6 and binary of 6 is 00000110
solution_mask = solution_mask | 1 << (solution[i] - 64)
00001000 | 00000110 =00001110
decimal of 00001110 is 14.
Therefore new value of solution_mask is 14.

for i=3
1<<(solution[i] - 64)
1<<(D-64)
1<<4
0000 0001
after 1<<3
0001 0000
Value of solution_mask is 6 and binary of 6 is 00000110
solution_mask = solution_mask | 1 << (solution[i] - 64)
00010000 | =00001110 =00011110
decimal of 00011110 is 30.
Therefore new value of solution_mask is 30.

Step 2:-
 for ( i = 0; i < 4; ++i) 
 {
  if (guess[i]== solution[i]) 
  {
   hits++;
   }
 else if ((solution_mask & (1 << (guess[i] - 64))) >= 1) 
 {
   pseudoHits++;
  }
 }
for i=0
guess[i]== solution[i]
'A'=='A'is equal
therefore increment hit by 1

for i=1
guess[i] != solution[i]
hence control move to else part
now,let's break the things again
1<<(guess[i] - 64)
1<<(E-64)
1<<5
0000 0001
after 1<<5
0010 0000
now
solution_mask & (1 << (guess[i] - 64))
00011110 & 00100000  =00000000
decimal of 00000000 is 0.
((solution_mask & (1 << (guess[i] - 64))) >= 1)
0>=1 condition become false hence control goes to for loop

for i=2
guess[i] != solution[i]
hence control move to else part
now,let's break the things again
1<<(guess[i] - 64)
1<<(D-64)
1<<4
0000 0001
after 1<<5
0001 0000
now
solution_mask & (1 << (guess[i] - 64))
00011110 & 00010000  =00010000
decimal of 00000000 is 16.
((solution_mask & (1 << (guess[i] - 64))) >= 1)
16>=1 condition is true
hence pseudoHits will increment by 1

for i=3
guess[i]== solution[i]
'D'=='D'is equal
therefore increment hit by 1

Hence number of hits is 2 and pseudo hits is 1

done!!

A computer has three registers, A, B and R. It has only three instructions:


A->R : Load R with A

B->R : Load R with B

A-R->A : Subtract R from A and store the result in A

Using these instructions how can you do the follwoing?

B->A : Load A with B


solution:-

A->R       // R ==  A
A-R->A   // A ==  0
B->R       // R ==  B
A-R->A   // A == -B
A->R       // R == -B
A-R->A   // A ==  0
A-R->A   // A ==  B

Design a hash table to store phone #s. Your job is to write a hash function that has a parameter username, and generate a key. Username is unique, length 5 and can be A-Z, 0-9, space. Write a hash function that generate keys without collisions and use minimum memory.


let's try to understand problem:



code to generate hash function:
#include <stdio.h> 
#include <math.h> 
char arr[100];
int i,j=4,total=0;
double x;
/* this function will generate hashcode */
void hashcode()
{
 for(i=0;i<5;i++)
 {
  if(arr[i]==' ')  // to caovert space to 0
   x=0;
  
  if(arr[i]>='0'&& arr[i]<='9')  // to convert ascii of 0-9 to 1-10
   x=(arr[i]-47);

  if(arr[i]>='A'&& arr[i]<='Z') // to convert ascii of A-Z to 11-36
   x=(arr[i]-54);
  
  x=x*pow(37, j);     
  total=total+(int)x; 
  j--;      
 } 
}
int main() 
{
 printf("enter the usename of length 5\n");
 for(i=0;i<5;i++)
  scanf("%c",&arr[i]);
 hashcode();
 printf("\n%d",total);
 return 0;
}


output:-
enter the usename of length 5
Z10 A

67572482
----------------------------------------------
Z10 A=36*37^(4)+2*37^(3)+1*37^(2)+0*37^(1)+11*37^(0)
refer table givien below





Wednesday, December 10, 2014

Find the first occurrence of an integer in an array of sorted integers in O(logn).

Given a sorted array, where exists duplicated integers, find the first occurrence of the target integer?

code:
#include <stdio.h> 
int arr[100],mid,l,r,len,position,i,target;
int binarySearchFirstOccur();
int main()
{ 
 printf("Enter number of elements\n");
 scanf("%d",&len);
 printf("Enter %d integers\n", len);
 for ( i = 0 ; i < len ; i++ )
      scanf("%d",&arr[i]);
 
 printf("Enter value to find\n");
 scanf("%d",&target);
 position=binarySearchFirstOccur();
    if( position!= -1)
     printf(" Given integer is present at %d index in array",position);
    else
     printf(" Given integer is not present in array");
  return 0;
}

int binarySearchFirstOccur()
{
 int l=0,r=len-1;
 int mid=(l+r)/2;
 
 while(l+1!=r)  //l+1==r => arr[l]<target and arr[r]>=target and l<r     
 {      
  if(arr[mid]<target)  //target is in the right
     l=mid;
  else
   r=mid;  
  mid=(l+r)/2;
 }
 
 if(r<len||arr[r]==target)
 return r;  //r is the first occurrence index
 else 
 return -1;    //didnt find the integer
}

output:-
Enter number of elements
10
Enter 10 integers
1 2 3 4 5 6 7 8 8 9
Enter value to find
8
Given integer is present at 7 index in array

let me demonstrate this for you:
first initialize l,r and mid
l=0
r=9
mid=0+9/2=4

value:  1  2   3   4   5   6   7   8   8   9
index:  0  1   2   3   4   5   6   7   8   9
             l                  m                      r
arr[mid]<target
arr[4]<8
5<8
yes,therefore change value of l,
l=mid
l=4
r=9
mid=(4+9)/2=6

value: 1  2   3   4   5   6   7   8   8   9
index: 0  1   2   3   4   5   6   7   8   9
                                      m            r
arr[mid]<target
arr[6]<8
7<8
yes,therefore change value of l,
l=mid
l=6
r=9
mid=(6+9)/2=7


value: 1  2   3   4   5   6   7   8   8   9
index: 0  1   2   3   4   5   6   7   8   9
                                          m        r
arr[mid]<target

arr[7]<8
8<8
no,therefore change value of r,
r=mid
r=7
l=6
mid=(6+7)/2=6

now we are done with first occurrence
note in while loop condition is

while(l+1!=r)
not
 while(l<r)

because it will go to infinite loop because as you can see we are storing index in r. Therefore
l<r will always true.

Explain ((n & (n-1)) == 0)


variant of question:-
 find whether a no is power of two ?

It's figuring out if n is either 0 or an exact power of two.

how ?

It works because of binary Bits Magic.
but before explaining first i want to define them  
n ->  unsigned long 
(n-1) -> it is simple Subtraction 
& -> The bitwise AND operator (&) compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.
Bitwise AND Truth Table :


now, why it work ?

because all number n which is power of 2 follow some pattern

look at this:

2  = 10
4  = 100
8  = 1000
16= 10000
32= 100000
64= 1000000

and all number (n-1) also follow some pattern

1=   01
3  = 011
7  = 0111
15= 01111
32= 011111
64= 0111111


all number n which is power of 2 has msb( leftmost bit ) 1 followed by all 0's              and all (n-1) number  has msb( leftmost bit ) 0 followed by all 1's

when we perform logical & operation between n and (n-1) answer will always 0.

example:

For n=2

  n           2 =  1 0
n-1     &  1 =  0 1
           ------------------
                      0 0
           ------------------

For n=4

  n           4 =  1 0 0
n-1     &  3 =  0 1 1
           ------------------
                      0 0 0
           ------------------

For n=8

  n           8 =  1 0 0 0
n-1     &  7 =  0 1 1 1
           ------------------
                      0 0 0 0
           ------------------

And so on...

But what about 0 ?

let n=0
n-1= (0-1)= (-1)
binary representation of 0=0000
and (-1) represent in 2's complement form 
Therefore binary representation of (-1)=1111

For n=0
  n               0 =  0 0 0 0
n-1      &  (-1) =  1 1 1 1
          -----------------------
                          0 0 0 0
          -----------------------

What if i only want to find whether number is power of two or not ?

(n != 0) && ((n & (n - 1)) == 0);

code:
#include <stdio.h> 
int main()
{
 int n,x;
 printf("enter value of n:");
 scanf("%d",&n);
 x= n & (n-1);
    if( x==0)
     printf("n is either 0 or an exact power of two.");
    else
     printf("n is neither 0 nor an exact power of two.");
  return 0;
}

output:-
enter value of n:16
n is either 0 or an exact power of two.

To find whether number is power of two or not?

code:
#include <stdio.h> 
int main()
{
 int n,x;
 printf("enter value of n:");
 scanf("%d",&n);
 x= n & (n-1);
    if( x==0)
     printf("number is power of 2");
    else
     printf("number is not power of 2");
  return 0;
}

output:-
enter value of n:16
number is power of 2




3 Ants and Triangle Puzzle


Three ants are sitting at the three corners of an equilateral triangle. Each ant starts randomly picks a direction and starts to move along the edge of the triangle. What is the probability that none of the ants collide? Now find the same for n vertex polygon with n ants.

solution :

Every Ant can move in 2 possible directions , Backward  ( B )  and Forward ( F ).
for 3 ants we have 2^(3) combination of moves,so the whole sample space consists of 8 choices.

F F B
F F F
F B B
F B F
B F B
B F F
B B B
B B F

here out 8 only 2 , namely BBB and FFF are no collision choices. 
so probability of not colliding is 2 /8 = 1/4=0.25

think in this way:

how can you avoid collision ?

The ants can only avoid a collision if they all decide to move in the same direction (either clockwise or anti-clockwise). If the ants do not pick the same direction, there will definitely be a collision.

1) all move in clockwise direction



2) move in anti-clockwise direction






Therefore  we have only 2 ways to avoid collision irrespective of shape and no of ant. 


how to find probability for n vertex polygon with n ants ?


As we know Every Ant can move in 2 possible directions , backward and forward .Therefore we have 2^(n) combination of moves.but only two will avoid collision (when all move in either clockwise or ant-clockwise direction )
hence probability of not colliding is 2/ 2^(n)
and probability of colliding is 1-2/ 2^(n)
example:pentagon 
pentagon has five vertices so n is 5
probability of not colliding = 2/ 2^(n)=2/2^(5)=2/32=1/16
probability of colliding = 1-2/ 2^(n)=1-2/2^(5)=1-2/32=1-1/16=15/16

Here another way to watch same problem...

As we know Each ant has the option to either move clockwise or anti-clockwise. There is a one in two chance that an ant decides to pick a particular direction. Using simple probability calculations, we can determine the probability of no collision.

P(No collision) = P(All ants go in a clockwise direction) + P( All ants go in an anti-clockwise direction)
P(No collision)= 0.5 * 0.5 * 0.5 + 0.5 * 0.5 * 0.5 = 0.25

let's generalize this for  n vertex polygon with n ants

P(No collision) = P(All ants go in a clockwise direction) + P( All ants go in an anti-clockwise direction)
P(No collision)=(0.5)^n + (0.5)^n
P(No collision)=2*(0.5)^n
P(No collision)=1-2*(0.5)^n

example:pentagon 
pentagon has five vertices so n is 5
probability of not colliding = 2*(0.5)^5=0.0625
probability of colliding = 1-2*(0.5)^5=0.9375

i know both are same and after simplifying them final formula is 1/2^(n-1) &1-1/2^(n-1) for No collision & collision resp.

Monday, December 8, 2014

Whats the difference between statically and dynamically typed languages? what is Strong Typing and Weak Typing?



Static vs. dynamic typing



Here are some claimed benefits.
Static typing
1. Reduced CPU usage since types don’t need to be checked at run-time
2. Reduced memory usage since types don’t need to be stored at run-time
3. Other type-directed optimizations
4. Discovery of errors as early as possible, for all my code
5. statically typed language, every variable name is bound both
       a) to a type (at compile time, by means of a data declaration)
       b)  to an object.

Dynamic typing
1. Easier to run and test since there are practically no compile-time or link-time errors
2. Programs are not limited by the expressiveness of the type system of the language
— e.g. heterogeneous data structures w/o explicit tagging.
3. Allows for implicit open recursion, late binding, dynamic scope, and duck typing
4. Programs are simpler since I don’t have to worry about types. Things are often coerced implicitly       making my programs more concise, and I don’t have to use really abstract things like type                   variables and higher-order types. In other words, they have been abstracted away by being pushed       down to a place I don’t have to think about.
5. In a dynamically typed language, every variable name is (unless it is null) bound only to an object.

write a program to find whether the m/c is big endian or little endian

Big endian and little endian are two formats to store multibyte data types into computer's memory. These two formats are also called network byte order and host byte order respectively.

let's try to understand problem:



code:
#include <stdio.h> 
int main ()
{
  unsigned int x = 0x76543210;
  char *c = (char*) &x;
  printf ("value of *c is: 0x%x\n", *c);
  if (*c == 0x10)
    printf ("your Machine architecture is little endian. \n");
  else
     printf ("your Machine architecture is Big Endian. \n");
  return 0;
}

output:-
value of *c is: 0x10
your Machine architecture is little endian.

Sunday, December 7, 2014

Given n stairs, how many number of ways can you climb if u use either 1 or 2 at a time?

variant of question:-
A person can take m steps at a time to reach a particular floor( say in a building). How many different ways can a person reach the nth floor?

let's try to understand problem:




but we have to make some modification in Fibonacci sequence to get correct answer.
why?
In Fibonacci first element is 0 & second is 1
i.e for step no 0  we have 0 ways & for step no 1 we have 1 way
for step no 2=no of ways(0)+ no of ways(1)=0+1=1
but  answer is 2 which is no of ways(2)+ no of ways(1)=1+1=2
look at table

Here our first element is 1 not 0
therefore to find no of ways for step no n ,we have to find  no of ways for step no n+1

code:
#include <stdio.h> 
int Fibonacci(int);
main()
{
   int n;
   printf("total no of steps:");
   scanf("%d",&n);
   printf("no of ways to climb is %d\n", Fibonacci(n+1));
   return 0;
}
 
int Fibonacci(int n)
{
   if ( n == 0 )
      return 0;
   else if ( n == 1 )
      return 1;
   else
      return ( Fibonacci(n-1) + Fibonacci(n-2) );
} 
output:-
total no of steps:4
no of ways to climb is 5

but what if person can take m steps at a time ?
if person take up-to 2 steps at time(i.e either 1-step or 2-step) then to get no of steps we add
(n-1) +(last result)=(new result)

if person take up-to 3 steps at time(i.e either 3-step or 2-step or 1-step) then to get no of steps we add
(n-2)+(n-1) +(last result)=(new result)
similarly, 
if person take up-to m steps at time then to get no of steps we add
(n-(m-1))+(n-(m-1)-1) ..............+(last result)=(new result)

Generalize code:
#include <stdio.h> 
int n, m;
int Fibonacci(int n);
int main ()
{
 printf("total no of steps:");
 scanf("%d",&n);
 printf("max no of steps can climb:");
 scanf("%d",&m);
 printf("no of ways to climb is %d\n", Fibonacci(n+1));
   return 0;
}
int Fibonacci(int n)
{ int total=0,i;
  if ( n == 0 )
      return 0;
  if ( n == 1 )
      return 1;
    for ( i = 1; i<=m && i<=n; i++) //for m steps
        total += Fibonacci(n-i);
    return total;
}

output:-
total no of steps:4
max no of steps can climb:3
no of ways to climb is 7


Friday, December 5, 2014

Shuffle card algorithm

One common programming question is how to randomly shuffle an array of numbers in-place.

variant of question:-
How would you write code to shuffle a deck of cards?
                                                   OR
write a program to generate a random permutation of array elements.


let's try to understand problem:



algorithm:

1. Start iterating the array from the last element.
2. If you are at ith element from the end, generate a random number say j,in range[0,i].
3. Swap A[i] and A[j].
4. Decrease j by 1
5. Continue till you reach the element at index 1 i.e A[1].

Generalize code:

#include <stdio.h> 
#include <stdlib.h> 
#include <time.h>
     int a[] = {1, 2, 3, 4, 5, 6, 7, 8},temp,i, n = 8;
// A function to generate a random permutation of a[]
void randomize ( )
{

// srand()--> gives the random function a new seed, a starting point 
//(usually random numbers are calculated by taking the previous number 
//(or the seed) and then do many operations on that number to generate the next).
 
//time(0)--> gives the time in seconds since the Unix epoch, 
//which is a pretty good "unpredictable" seed 
//(you're guaranteed your seed will be the same only once, 
//unless you start your program multiple times within the same second).
    srand ( time(NULL) );
 
    //We don't need to run for the first element that's why n-1 pass
    
    for ( i = n-1; i > 0; i--) //for Shuffle card algorithm i=51
    {
        // Pick a random index from 0 to i
        int j = rand() % (i+1);
 
        // Swap a[i] with the element at random index
            temp = a[i];
            a[i] = a[j];
            a[j] = temp;
    }
}
 
int main()
{
 // shuffle the array
    randomize ();
  // print results.
     for ( i = 0; i < n; i++)
        printf("%d ", a[i]);
    return 0;
}


output:-
8 1 5 4 6 2 3 7

time complexity:-  O(n)
time complexity to traverse array is o(n) and assume rand() generates random number in O(1) time.

code for  shuffle deck of cards: 
we have to make change in input and array size of above generalize algorithm.input array consist of 52 cards
          int a[] ={  1,2,3,4,5,6,7,8,9,10,11,12,13,
                      14,15,16,17,18,18,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
                   };
change value of n
int n=52  // array size 
final code for  shuffle deck of cards:  :
#include <stdio.h> 
#include <stdlib.h> 
#include <time.h>
// Clubs->1 to 13
//Diamonds->14 to 26
//Hearts->27 to 39
//Spades->40 to 52
 int a[] ={ 1,2,3,4,5,6,7,8,9,10,11,12,13,
            14,15,16,17,18,18,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
          };
 int temp,i, n = 52;
// A function to generate a random permutation of a[]
void randomize ( )
{
 
// srand()--> gives the random function a new seed, a starting point 
//(usually random numbers are calculated by taking the previous number 
//(or the seed) and then do many operations on that number to generate the next).
  
//time(0)--> gives the time in seconds since the Unix epoch, 
//which is a pretty good "unpredictable" seed 
//(you're guaranteed your seed will be the same only once, 
//unless you start your program multiple times within the same second).
    srand ( time(NULL) );
  
    //We don't need to run for the first element that's why n-1 pass
     
    for ( i = n-1; i > 0; i--) //for Shuffle card algorithm i=51
    {
        // Pick a random index from 0 to i
        int j = rand() % (i+1);
  
        // Swap a[i] with the element at random index
            temp = a[i];
            a[i] = a[j];
            a[j] = temp;
    }
}
  
int main()
{
 // shuffle the array
    randomize ();
  // print results.
     for ( i = 0; i < n; i++)
        printf("%d ", a[i]);
    return 0;
}
output:-
29 8 47 10 49 28 24 43 14 13 48 32 2 12 
36 31 30 18 50 1 25 41 40 45 39 38 6 35
23 17 9 46 20 11 51 52 4 34 42 15 22 7 
37 33 18 3 5 16 27 26 21 44



All Rights Reserved. 2014 Copyright SIMPLITONA

Powered By Blogger | Published By Gooyaabi Templates Designed By : BloggerMotion

Top