Picking a random order of 10 numbers

I have been banging my head against a wall trying to randomise the contents of an array without any number repeating.

randnumbe[10] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

I want to fill these 10 array variable positions with a random number between 1 and 10, and each number (1-10) is only used once.

Any ideas? Mine so far have failed miserably

Put the numbers 1 to 10 in the array then repeatedly swap two random pairs of them as many times as you want

1 Like

Thanks Bobs.... instant fix.
Legend

Glad to have been of service

@UKHeliBob offers a good solution for scrambling ten items.

It is clear what you are doing, and easy to see why it works.

When/if you get to scrambling a larger number of items, it's time to take a page from the book you didn't write and use the Fisher-Yates shuffle algorithm.

It is harder to see what's happening. I can figure it out one day, but the next I cannot write it down on a blank piece of paper, which means I haven't been able to understand it very well. Or my brain is mush. Both I guess.

What Fisher-Yayes has going for it is that it will only need N random numbers to shuffle N items. The simple shuffle would need many more than N to get a good shuffle when N is large-ish. Dunno where large in that context is and would depend also on how much time you had to get the job done.

# define N 52

int array[N];

void shuffle()
{
  int i, j, tmp;

  for (i = N - 1; i > 0; i--) {
    j = random(i + 1);
    tmp = array[j];
    array[j] = array[i];
    array[i] = tmp;
  }
}

I even manage to forget all about it, but the matter comes up not infrequently around here, see this recent thread for your amusement:

a7

here is an example using the Fisher Yates shuffle

click to see the code
int array[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
size_t arraySize = sizeof array / sizeof * array;

void printArray() {
  for (size_t i = 0; i < arraySize; ++i) {
    Serial.print(array[i]);
    Serial.write(' ');
  }
  Serial.println();
}

void fisherYatesShuffle() {
  // Start from the last element and swap it with a randomly selected element before it
  for (int i = arraySize - 1; i > 0; --i) {
    // Generate a random index between 0 and i (inclusive)
    int randomIndex = random(0, i + 1);
    // Swap array[i] with the randomly selected element
    int temp = array[i];
    array[i] = array[randomIndex];
    array[randomIndex] = temp;
  }
}


void setup() {
  Serial.begin(115200);

  // create a bit of randomness
  randomSeed(analogRead(A0));

  Serial.println(F("Before shuffling"));
  printArray();

  // shuffle the array
  fisherYatesShuffle();

  Serial.println(F("After shuffling"));
  printArray();

}

void loop() {}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.