简体   繁体   中英

Fill a 2D array with non-repeating random numbers

I am currently trying to fill up a 2D array with 16 values from 1-16. I want to fill up the array with non-repeating random values.

For example, if I have an array int array[4][4] how would I go through a loop filling the array while checking to make sure that another identical random value isn't placed into another location in the array?

int array[4][4];
int* p = &array[0][0];
std::iota(p, p+16, 1);

std::random_device r;
std::default_random_engine g(r());
std::shuffle(p, p+16, g);

Use int randomValue = rand() % 16 + 1; and store it in another helper 2D array for check purpose. you should be done.

Create a 1-d array, say arr of size 16, populate it with values from 1 to 16 . Use shuffle on arr . Traverse through the array to fill the 2-D array, say arr2 .

for(int i = 0; i < 16; i++){
   arr2[i/4][i%4] = arr[i];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM