### random number

How to store 0 to 25 number randomly in 5x5 array.Can u teach me how to do it

Last edited on
How to get random numbers between 0 - 25 and store them in an array:
 ``1234`` ``````int myArray[10]; for (int i = 0; i < 10; ++i) myArray = rand() % 26;``````

How to get the numbers 0-25 shuffled randomly:
 ``123456`` ``````int myArray[26]; for (int i = 0; i < 26; ++i) myArray[i] = i; std::random_shuffle( myArray, myArray + 26 );``````

rand() comes from <cstdlib>
std::random_shuffle() comes from <algorithm>
Last edited on
How to get it for 5x5 array...
well you could just copy it over...

 ``1234`` ``````int fiveByfive[25][25]; for (int i = 0; i <5; ++i) for (int j = 0; j < 5; ++j) fiveByfive[i][j] = myArray[i * 5 + j ];``````

standard utilities are not really meant for multi-dimensional arrays because they are not the most efficient means of doing... anything.
Last edited on
closed account (D80DSL3A)
nvm. OP has abandoned the thread.
Last edited on
I advice against that as it's hackish. ;-P
closed account (D80DSL3A)
@Josue. Care to suggest a better method?
What do you find to be 'hackish' about it? Just curious.
Last edited on
You're writing random numbers into the array; there's no need to shuffle them. However, if you insist on shuffling them, here's what I believe to be the best way to achieve this:

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263`` ``````#include #include #include int main() { /*********************************** * Write into and print the array. * ***********************************/ const int size = 5, range = 25; int array[size][size]; srand(time(NULL)); for (int i = 0; i < size; ++i) { for (int j = 0; j < size; ++j) { array[i][j] = rand() % (range + 1); } } for (int i = 0; i < size; ++i) { for (int j = 0; j < size; ++j) { std::cout << std::setw(2) << array[i][j] << ' '; } std::cout << std::endl; } std::cout << std::endl; /******************************** * Shuffle and print the array. * ********************************/ for (int i = 0; i < size; ++i) { for (int j = 0; j < size; ++j) { int it = rand() % size, jt = rand() % size; int temp = array[it][jt]; array[it][jt] = array[i][j]; array[i][j] = temp; } } for (int i = 0; i < size; ++i) { for (int j = 0; j < size; ++j) { std::cout << std::setw(2) << array[i][j] << ' '; } std::cout << std::endl; } return 0; }``````
Topic archived. No new replies allowed.