Shuffle function

Jan 22, 2019 at 4:16pm
Can someone explain how this shuffling works. So I know it shuffles 100 times. But how does it work? Does it pick 2 random numbers from the Pack and swap them?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void Shuffle()
{
	unsigned seed = time(0);
	srand(seed);

	for (int Shuffle = 0; Shuffle < 100; Shuffle++) 
	{
		int RNum1 = rand() % 52;
		int RNum2 = rand() % 52;

		Temp = Pack[RNum1];
		Pack[RNum1] = Pack[RNum2];
		Pack[RNum2] = Temp;
	}
}
Jan 22, 2019 at 4:20pm
closed account (E0p9LyTq)
Yes.

A rather inadequate shuffle algorithm IMO, crudely duplicating what std::random_shuffle does.

C++ has better random functions and algorithms available.
Last edited on Jan 22, 2019 at 4:24pm
Jan 22, 2019 at 4:26pm
unsigned seed = time(0); - Gets unix time in seconds
srand(seed); - seeds/enables the rand() function by seeding with the value of the time we had gotten.

for (int Shuffle = 0; Shuffle < 100; Shuffle++)
^ Iterates for 100 times starting with 0 and ending with 99.

1
2
int RNum1 = rand() % 52;
int RNum2 = rand() % 52;

^ Produces two different random numbers in the range [0, 51] inclusive and stores them in RNum1 and RNum2

Temp = Pack[RNum1];
Temporary variable storing the value at RNum1'th index of Pack the array.
I.e, if RNum1 was 10, then it would get the 10th element from Pack and store in Temp the variable.

Pack[RNum1] = Pack[RNum2];
Changes the value at the RNum1'th index to the RNum2'th index of Pack the array.

Pack[RNum2] = Temp;
Assigned the RNum2'th index of Pack the value we had stored in Temp.
Jan 23, 2019 at 5:12pm
This shuffle algorithm swaps two random cards in the deck and does 100 times.

- Lines 8 & 9 pick two random card locations.
- Lines 11-13 swap the cards at those two positions.
- The loop at line 6 causes lines 8-13 to execute 100 times.
Jan 24, 2019 at 12:22am
Really should just use the Fisher-Yates algorithm.

The one above has a significant chance of leaving particular elements untouched.

In psuedocode.
1
2
  for (int i = 0; i < v.size() - 1; ++i)
    swap(v[i], v[random_integer_in_halfopen_interval(i, size())]);

Last edited on Jan 24, 2019 at 12:23am
Topic archived. No new replies allowed.