Shuffle an array of ints

Hi guys :),

I have a problem with Shuffling this array:

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?

Well I myself would Google for:
shuffle algorithm

What I usually do is swap each entry with a random other entry:

int questionNumberArray[]={0,1,2,3,4,5,6,7,8,9};
const int questionCount = sizeof questionNumberArray / sizeof questionNumberArray[0];
for (int i=0; i < questionCount; i++) {
   int n = random(0, questionCount);  // Integer from 0 to questionCount-1
   int temp = questionNumberArray[n];
   questionNumberArray[n] =  questionNumberArray[i];
   questionNumberArray[i] = temp;
}

@John: I'd feel a little better if n were a long rather than an int.

Homework question.

How would you shuffle ianything?

@PaulMurrayCbr: This is the Google code mentioned earlier with a few minor modifications.

void setup() {
  int i;
  Serial.begin(9600);
  
  int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
  int n = sizeof(arr)/ sizeof(arr[0]);
  randomize (arr, n);
  for (i - 0; i < n; i++) {
    Serial.print(arr[i]);
    Serial.print("   ");
  } 
}

void loop() {
}

void swap (int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

void randomize ( int arr[], int n )
{
    // Use a different seed value so that we don't get same
    // result each time we run this program
    randomSeed(analogRead(A0));
 
    // Start from the last element and swap one by one. We don't
    // need to run for the first element that's why i > 0
    for (int i = n-1; i > 0; i--)
    {
        long j = random(0, n);
        swap(&arr[i], &arr[j]);
    }
}

If you mean how can you shuffle any type of data, all you need to do it alter the swap() function. You could even pre-write swap routines for the basic data types and call via a pointer to function if the data type is determined at run time.

PaulMurrayCbr:
Homework question.

How would you shuffle ianything?

gynintahi

econjack:
@John: I'd feel a little better if n were a long rather than an int.

Why? The value is constrained to be within 0 and the length of the array....

Regards,
Ray L.

A slightly faster algorithm which optimizes the swap, useful mainly (only) for large array's or on external devices. In memory the costs of random() far outweighs almost any optimization. Using a faster random makes more sense.

void shuffleArray(int * array, int size)
{
  int last = 0;
  int temp = array[last];
  for (int i=0; i<size; i++)
  {
    int index = random(size);
    array[last] = array[index];
    last = index;
  }
  array[last] = temp;
}