## Microsoft Interview Question

Senior Software Development Engineers- 2of 2 votes
Write a program to shuffle a deck of card?

**Country:**United States

```
#include<iostream>
#include<vector>
#include<cstdlib>
#include<ctime>
using namespace std;
const int deckSize = 52;
void fisherYatesShuffler( vector<int>& cards )
{
srand(time(0));
for( int i=cards.size()-1; i>=0; --i)
{
int randomIndex = rand() % (i+1);
swap( cards[i], cards[randomIndex] );
}
}
int main()
{
vector<int> cards( deckSize );
for( int i=0; i<cards.size(); ++i)
{
cards[i] = i+1;
}
fisherYatesShuffler( cards );
return 0;
}
```

Here is my solution

```
import java.util.Random;
public class ShuffleDeckOfCards {
private static void shuffle(int[] input) {
int inputLength = input.length;
// class to generate random numbers
Random r = new Random();
for (int i = inputLength - 1; i > 0; i--) {
// Generate random index
int index = r.nextInt(i);
// swap i with randomly generated index
int temp = input[index];
input[index] = input[i];
input[i] = temp;
}
}
public static void main(String[] args) {
int[] cards = new int[52];
for (int i = 0; i < 52; i++) {
cards[i] = i + 1;
}
shuffle(cards);
}
}
// Time complexity: O(N)
```

My solution in Java:

```
import java.util.Random;
public class ShuffleDeckOfCards {
private static void shuffle(int[] input) {
int inputLength = input.length;
// class to generate random numbers
Random r = new Random();
for (int i = inputLength - 1; i > 0; i--) {
// Generate random index
int index = r.nextInt(i);
// swap i with randomly generated index
int temp = input[index];
input[index] = input[i];
input[i] = temp;
}
}
public static void main(String[] args) {
int[] cards = new int[52];
for (int i = 0; i < 52; i++) {
cards[i] = i + 1;
}
shuffle(cards);
}
}
// Time complexity: O(N)
```

- Makarand October 30, 2017