Microsoft Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: In-Person
Hi,
The right way to do it : Space complexity : O(1), Time Complexity : O(n)
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#define CARD_COUNT 52
void swap(int *card_arr, int index1, int index2)
{
if(index1 != index2)
{
card_arr[index1] = card_arr[index1] + card_arr[index2];
card_arr[index2] = card_arr[index1] - card_arr[index2];
card_arr[index1] = card_arr[index1] - card_arr[index2];
}
}
int main(void)
{
int i;
int card_arr[CARD_COUNT] = {0};
for(i = 0; i < CARD_COUNT; i++)
card_arr[i] = i+1;
for(i = 0; i < CARD_COUNT; i++)
{
int index = rand() % (CARD_COUNT - i) + i;
swap( card_arr, i, index);
}
getch();
}
for i = 0 to 51
generate a random number in the range (i+1 to 51): @next_idx
swap the elements at the indices i and next_idx
Yes, that's correct. I just showed an algorithm that I implemented long ago for one of my programs where there was a limitation not to have any element in its proper position in the final shuffled set. If we still want to have such elements, we can simply change the range from (i+1) to (i), and this will allow selecting the proper element for the given position.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
main()
{
int card[52];
int n;
int i,c;
srand(time(NULL)); // initialize the seed randomly
printf("How many card you want to open from the deck after shuffle");
scanf("%d",&n);
for (i=0; i<52; i++)
{
card[i] = i; // fill the array in order
}
//--- Shuffle elements by randomly exchanging each with one other.
for (i=0; i<(52-1); i++)
{
int r = i + (rand() % (52-i)); // Random remaining position.
printf("rand()%(52-i):%d\n",r);
int temp = card[i];
card[i] = card[r];
card[r] = temp;
}
//--- Print first n cards as ints.
for (c=0; c<n; c++)
{
printf("%d ",card[c]);
}
getch();
}
Yup. This is one way to do it:
- smffap June 16, 2012