mardi 19 septembre 2017

Printing an an array of integers in random order without repeating in C++

I'm attempting to implement the printRandom() function which should repeatedly select and remove a random entry from the array C and then prints out the selected value until all values in the array C have been printed. They can only be printed one time each.

I can only use cstdlib and iostream. This is my code for the function thus far:

void printRandom(int C[], int n, int seed) {
srand(seed);
int test[10] = { 21,-34,2,-42,89,24,11,4,13,-18 };

for (int i = 0; i < 10; i++)
{
    int r = rand() % 10;
    for (int j = 0; j < 10; j++) {
        if (r != C[j]) {
            C[i] = test[r];
            cout << C[i] << ' ';
        }
    }

}
}

This is the main function I am working with:

int main() {
  int A[10], B[10] ;

  A[0] =  21 ;
  A[1] = -34 ;
  A[2] =   2 ;
  A[3] = -42 ;
  A[4] =  89 ;
  A[5] =  24 ;
  A[6] =  11 ;
  A[7] =   4 ;
  A[8] =  13 ;
  A[9] = -18 ;

  for (int i=0 ; i < 10 ; i++) {
     B[i] = A[i] ;
  }
  printRandom(B,10,38173410) ;

  for (int i=0 ; i < 10 ; i++) {
    B[i] = A[i] ;
 }
  printRandom(B,10,83103131) ;

 for (int i=0 ; i < 10 ; i++) {
    B[i] = A[i] ;
 }
  printRandom(B,10,77192102) ;

return 0 ;
}

Right now I'm getting a large block of numbers

-34 -34 -34 -34 -34 -34 -34 -34 -34 -34 24 24 24 24 24 24 24 24 24 24 13 13 13 13 13 13 13 13 13 13 89 89 89 89 89 89 89 89 89 -18 -18 -18 -18 -18 -18 -18 -18 -18 -18 -18 -18 -18 -18 -18 -18 -18 -18 -18 -18 -18 -18 -18 -18 -18 -18 -18 -18 -18 -18 2 2 2 2 2 2 2 2 2 -42 -42 -42 -42 -42 -42 -42 -42 -42 -42 4 4 4 4 4 4 4 4 4 4 13 13 13 13 13 13 13 13 13 13 -18 -18 -18 -18 -18 -18 -18 -18 -18 -18 -34 -34 -34 -34 -34 -34 -34 -34 -34 -34 2 2 2 2 2 2 2 2 2 -42 -42 -42 -42 -42 -42 -42 -42 -42 -42 4 4 4 4 4 4 4 4 4 4 11 11 11 11 11 11 11 11 11 11 -34 -34 -34 -34 -34 -34 -34 -34 -34 -34 -42 -42 -42 -42 -42 -42 -42 -42 -42 -42 21 21 21 21 21 21 21 21 21 21 -42 -42 -42 -42 -42 -42 -42 -42 -42 -42 13 13 13 13 13 13 13 13 13 13 -34 -34 -34 -34 -34 -34 -34 -34 -34 -34 89 89 89 89 89 89 89 89 89 -42 -42 -42 -42 -42 -42 -42 -42 -42 -42 13 13 13 13 13 13 13 13 13 13 -42 -42 -42 -42 -42 -42 -42 -42 -42 -42 13 13 13 13 13 13 13 13 13 13 89 89 89 89 89 89 89 89 89 89 13 13 13 13 13 13 13 13 13 13

I took some time off of C++ and was wondering if you could help or at least point me in the right direction. Thank you!




Aucun commentaire:

Enregistrer un commentaire