How can I make a random 4×4 array<array<int,4>,4>? Each element of this 2D array should be unique number from the interval from 0 to 15, inclusive.
Example:
6 7 5 4
10 11 12 15
1 3 2 8
9 14 0 13
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Not a bad question. This would be my pick:How to generate subsequent array values, mix them and initialize 2D arrays with them?
I extended my answer to include another (simple) solution to the problem using
std::vectoronly, andstd::vector + std::array(as asked by the O.P.).In the for loop, we only do 4 iterations but have a total of 4×4 elements. Because each of the 4 matrix rows is 4 elements wide, we have to find a way how we take the correct 4 elements for each matrix row from our shuffeld 16-element 1D vector v:
v.begin()+i*N ... v.begin()+(i+1)*N. Ifiis 0 (first iteration), we copy the four elements fromv[0 * N] ... v[0+1 * N], this meansv[0] .. v[4].This is a sequence where the last element v[4] is not included in the copy. This is also somehow an idiomatic pattern in C/C++ which is comparable to:
for(i=START; i < END; i++) ....The END element is therefore beyond the range, not included.
In the second iteration (i = 1), we have
v[1 * N] ... v[1+1 * N], which isv[4] ... v[8]. You see the pattern?Why is the shuffled order always the same? The C library uses a random number implementation that starts from the same seed number generating always the same sequence (which might be important for debugging). In order to get different shuffling, you’d have to re-initialize the random number generator at the program start once.
For this, you need the C-library time-header (for
time()) and most probably stdlib-header (forsrand()):I deliberately tried to provide very simple solutions only. Therefore, no generators or C++11 lambdas seemed appropriate for this purpose.
Regards
rbo