So the question is to develop a [5][5] table, each containing unique numbers from 1-100 (no duplicates)
so here's what I came up with:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int outerLoop;
int innerLoop;
int board[5][5]; /* Array Name And Size*/
/* seeds the random number generator*/
srand(time(NULL));
int number;
number = rand() % 101;
/* Start a loop to generate a random integer between 1 and 100 and
assign it into the array. The loop runs 25 times*/
for ( outerLoop = 0 ; outerLoop <= 25 ; outerLoop++ ) /* loop 25 times*/
{
for ( innerLoop = 0 ; innerLoop <= 4 ; innerLoop++ ) /* <=4 due to 5
columns*/
{
board[outerLoop][innerLoop] = rand() % 100 + 1;
}
printf( "%d \n", board[outerLoop][innerLoop] );
}
So I pretty much got stuck here.I'm not really sure about this:
board[outerLoop][innerLoop] = rand() % 100 + 1;
I simply made it up :/ Any idea guys?
What you want is a shuffle algorithm
Shuffle array in C
To get your 25 element array of unique #s from 1 to 100; just create a 100 element array with the numbers 1..100, shuffle the 1st 25 from the pool of 100, and use the 1st 25.
Just create array of boolean of size 100 :
bool numberUsed[100]
. Then in cycle:Note that you need to use WHILE cycle with this approach, not FOR cycle.
Here is some pseudo code to solve it:
index = (int)rand() * numbersAvailable;
and the take the numbernumbersAvailable.get(index);
and then donumbersAvailable.remove(index);
In Java creating a list is easy. If you like to stick to C you have to emulate this via arrays. (I can write down the solution, but this looks like a homework, so I leave something for you).
Note: In contrast to a trial-and-reject solution, this solution has the advantage of a fixed amount of time needed to construct the result.
C stores arrays in row-major order, i.e, the elements of row 0 comes first , followed by the elements of row 1, and so forth.
We can take advantage of this by viewing
int board[5][5]
asint board[5*5]
.Since
int board[5][5];
allocates a continuous amount of memory you can initialise it with justOr use a double loop like you did, but then you only need to loop 5 times in the other loop, or use
sizeof
to set the iteration count automatically:Please keep in mind that
sizeof
will only work on arrays in this way when the length of the array is known at compile time like it is in your example.Think of it like a deck of 100 cards.