murloc
murloc

Reputation: 75

Shuffle an array in Arduino software

I have a problem with Shuffling this array with Arduino software:

int questionNumberArray[10]={0,1,2,3,4,5,6,7,8,9};

Does anyone know a build in function or a way to shuffle the values in the array without any repeating?

Upvotes: 2

Views: 4751

Answers (1)

Darth Hunterix
Darth Hunterix

Reputation: 1510

The simplest way would be this little for loop:

int questionNumberArray[] = {0,1,2,3,4,5,6,7,8,9};

const size_t n = sizeof(questionNumberArray) / sizeof(questionNumberArray[0]);

for (size_t i = 0; i < n - 1; i++)
{
    size_t j = random(0, n - i);

    int t = questionNumberArray[i];
    questionNumberArray[i] = questionNumberArray[j];
    questionNumberArray[j] = t;
}

Let's break it line by line, shall we?

int questionNumberArray[] = {0,1,2,3,4,5,6,7,8,9};

You don't need to put number of cells if you initialize an array like that. Just leave the brackets empty like I did.

const size_t n = sizeof(questionNumberArray) / sizeof(questionNumberArray[0]);

I decided to store number of cells in n constant. Operator sizeof gives you number of bytes taken by your array and number of bytes taken by one cell. You divide first number by the second and you have size of your array.

 for (size_t i = 0; i < n - 1; i++)

Please note, that range of the loop is n - 1. We don't want i to ever have value of last index.

size_t j = random(0, n - i);

We declare variable j that points to some random cell with index greater than i. That is why we never wanted i to have n - 1 value - because then j would be out of bound. We get random number with Arduino's random function: https://www.arduino.cc/en/Reference/Random

 int t = questionNumberArray[i];
 questionNumberArray[i] = questionNumberArray[j];
 questionNumberArray[j] = t;

Simple swap of two values. It's possible to do it without temporary t variable, but the code is less readable then.

In my case the result was as follows:

questionNumberArray[0] = 0
questionNumberArray[1] = 9
questionNumberArray[2] = 7
questionNumberArray[3] = 4
questionNumberArray[4] = 6
questionNumberArray[5] = 5
questionNumberArray[6] = 1
questionNumberArray[7] = 8
questionNumberArray[8] = 2
questionNumberArray[9] = 3

Upvotes: 3

Related Questions