More thoughts on shuffledness

Shuffling
Image by Hucklebarry from Pixabay

Thinking about what I said, it can’t be just about how far a card moves when shuffled but how much disordering occurs as well. If you shuffled the deck and discovered 7 cards in a sequence like 2,3,4,5,6 of hearts deep into the deck, they would have moved from near the top of the deck (an “ordered deck” is A-K in Hearts, Clubs, Diamonds and Spades) then it probably wasn’t a very good shuffle.

One way to measure “disorder” is to subtract each card’s ordinal value from it’s successor and sum up the absolute value of them . Ordinal value is the value 0-51 where 0 = Ace Hearts, 1 = 2 Hearts and so on. In an ordered deck the sum of all these subtractions will be 51. In a well shuffled deck I would guess it might be something like 1352 (52 x 26). Absolute value is the abs(x) function of x which is always positive if x is negative.  abs(-8) = 8. abs(8) = 8.

So now for shuffledness we have two values. Displacement and disorder. If both are calculated as a value between 0 and 1 then multiplying them together might work as a measure of shuffledness.

Here’s a very simple example of calculating the value for disorder. So far the calculations have never got a total much above 900, and not near 1352. I’ll run a few experiments and see the range of values.

// shuffledness.c : This measures how shuffled a deck of cards is
// cards are held as values 0-51 in a 52 int array.

#include <time.h>
#include <stdio.h>
#include <stdlib.h>

int deck[52];
time_t t;

// Order the cards 0-51. 0 = Acew Hards,13 = Ace Clubs,26 = Ace of Diamonds and 51 = King of Spades
void InitDeck() {
	for (int i = 0; i < 52; i++) {
		deck[i] = i;
	}
}

// Works on glovbal array deck and calculates a value for how displayed each card is
float CalcDisorder() {
	int total=0;
	for (int i = 1; i < 52; i++) {
		total += abs(deck[i] - deck[i - 1]);
	}
	printf("Total = %d\n", total);
	return total / (52.0f * 26.0f);
}

// Shuffle a deck by swapping two random cards a specified number of times
void ShuffleDeck(int numtries) {
	int firstIndex, secondIndex;
	for (int i = 0; i < numtries; i++) {
		do {
			firstIndex = rand() % 52;
			secondIndex = rand() % 52;
		}
		while (firstIndex == secondIndex);
		int value = deck[firstIndex];
		deck[firstIndex] = deck[secondIndex];
		deck[secondIndex] = value;
	}
}

int main() {
	/* Intializes random number generator */
	srand((unsigned)time(&t));
	InitDeck();
	ShuffleDeck(1000);
	printf("CalcDisorder() == %f\n", CalcDisorder());
	return 0;
}

That’s about 50 lines long. I’ll work on it and add the displacement calculation and try and get a maximum figure the the disorder calculation.

Leave a Reply

Your email address will not be published. Required fields are marked *