2

I am writing a program that involves placing one number into each cell of a 7x7 grid. There are 56 numbers, chosen from at random, and there must be no repetition.

The end result should be a 7x7 grid in which each cell contains an integer from 1 to 56, with no two cells containing the same number. What is the most efficient way of doing this?

extra words: I tried creating a for x{for y{}} that would go through the grid cell by cell and add a random number 1-56. It would then check a 56-slot array to see if that number was already in use, and correspondingly either re-roll or accept the number, then flag the array to mark the number as in use. For some reason, I couldn't get it to work, and it seemed like a bad solution. I scrapped it, and instead had a second for x{for y{}} run each time and check the entire grid cell by cell for the rolled number before approving or rejecting it. This also didn't quite work and seemed unwieldly, so I scrapped it as well.

4 Answers4

1
  1. Create an array of length 56, filled with numbers 1 to 56

  2. Use Fisher-Yates shuffle to create an unbiased, randomised array

  3. Fill 7x7 matrix (row or column order) sequentially from array.

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
1

You can generate an array of 1:56, then shuffle, then pick out the first 49 elements.

$arr = range(1,56);
shuffle($arr);
$vals = array_slice($arr, 0, 49); //49 because grid is 7x7

// put $vals in grid.
mathematical.coffee
  • 55,977
  • 11
  • 154
  • 194
0
  • Create an array of 56 elements containing the numbers 1 to 56.
  • Generate a random number between 1 and the length of the array
  • Choose the number at that index and remove it from the array
  • lather, rinse, repeat
mowwwalker
  • 16,634
  • 25
  • 104
  • 157
0

Create an array with all the numbers needed, and shuffle it.

$fullGrid = range($min, $max);
shuffle($fullGrid);

Now all you need to do is visually display the $fullGrid array.

More on the php shuffle function.

Frankie
  • 24,627
  • 10
  • 79
  • 121