### Changing Duplicate Random Numbers

We were assigned to write a program using a Matrix, that displays a table of random numbers from 1-48. In each row (horizontal) there could be NO matching numbers. We are not to use a lot of if statements. Could anyone share ideas of how to go about doing this?

My code:

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475`` `````` /* Project Tickets by Jacob Wright 2-26-13 */ #include #include #include //___________________________________ void changedisp (matrix change); //Changes numbers of same value if they're in the same row and displays //___________________________________ int main() { cout << "\n\n\n\n"; randomize(); matrix rand(25, 6); for (int c=0; c<=5; c++) { for (int r=0; r<=24; r++) rand[r][c]=random(48)+1; } changedisp(rand); cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"; return(0); } //_________________________________ void changedisp (matrix change) //Changes numbers of same value if they're in the same row and displays { for (int C=0; C<=24; C++) //Start of my search for duplicate numbers { for (int Y=0; Y<=5; Y++) //nested for statement to allow me to search each row for duplicates { cout.width(14); cout << " [1]"; for (int x=2; x<=6; x++) { cout.width(8); cout << " [" << x << "]"; } cout << endl << endl; cout << " [1]"; for (int ze=0; ze<=5; ze++) { cout.width(10); cout << change[0][ze]; } cout << endl; for (int X=2; X<=25; X++) { if (X<=9) cout << " "; cout << "[" << X << "]"; for (int zes=0; zes<=5; zes++) { cout.width(10); cout << change[X-1][zes]; } cout << endl; } } ``````
Why not check for duplicates when you are adding them to the array.
Are you familiar with set's http://www.cplusplus.com/reference/set/set/

Rewrite the inner loop of the following

 ``12345`` ``````for (int c=0; c<=5; c++) { for (int r=0; r<=24; r++) rand[r][c]=random(48)+1; }``````

as
 ``123456789101112131415161718192021`` ``````set s; for (int c=0; c<=0; c++) { // clear set at start of each row s.clear(); int r=0; while( r <= 24 ) { int rVal = random(48)+1; // Do we already have this value if( s.find( rVal ) != s.end() ) continue; // If we get here a new value s.insert(rVal); rand[r][c] = rVal; r++; }``````

 We were assigned to write a program using a Matrix, that displays a table of random numbers from 1-48.

A fairly common way is to generate a list of values covering the range needed, and shuffle the list.
Topic archived. No new replies allowed.