vendredi 22 décembre 2017

Swapping of randomly chosen elements gone wrong

I'm trying to write an algorithm in C++ that produces a sequence of five consecutive distinct numbers from 1 to 25 by initializing an array of 25 elements to their corresponding index value and then iteratively generate two random numbers, one of which in the range 1-5 and the other in the range 6-25, and then swap the two elements corresponding to these two random values. It's basically a random-sorting algorithm of the numbers 1-25, and I only care about the ones that end up on the first five positions. However, when I output the result in Xcode, I get a weird number on the last line, like:

16
12
11
6
-272632008

The code I have is this:

 #include <iostream>

 using namespace std;

  int main(int argc, const char * argv[]) {
  int numbers[26];
  int randomnum1, randomnum2;

  for(int i=0;i<=25;i++) {
    numbers[i] = i;
  }

  srand(time(NULL));

  int temp;


  for(int i=1;i<=25;i++) {
    randomnum1 = 1 + rand() % 5;
    randomnum2 = 6 + rand() % 25;
    temp = numbers[randomnum1];
    numbers[randomnum1] = numbers[randomnum2];
    numbers[randomnum2] = temp;
  }

  for(int i=1;i<=5;i++) {
      cout<<numbers[i]<<"\n";
  }
    return 0;
  }

Any advice on how to solve this problem would be appreciated.




Aucun commentaire:

Enregistrer un commentaire