Using this program, I’m trying to set a 6×15 array to 0, then place a random number x amount of times in a random slot of the array. However, it doesn’t go as planned…
Note that MAX_ROWS is 6, MAX_COLS is 15, and OCEAN is 0
#include <stdio.h>
#include <time.h>
#include "util.h"
int rand_number(int param);
main()
{
int map[MAX_ROWS][MAX_COLS]; //initializes an array, map, with the dimensions 6 and 15.
//sets all values in the array to 0
int a,b;
for (a = 0; a < MAX_ROWS; a++)
{
for (b = 0; b < MAX_COLS; b++)
{map[a][b]=OCEAN;}
}
int shipnum = 6;
This SHOULD place the random numbers. (shipnum is just a value I use to limit the number of ships I place):
while(shipnum > 0)
{
map[rand_number(MAX_ROWS)][rand_number(MAX_COLS)] = 3;
shipnum -= 1;
map[rand_number(MAX_ROWS)][rand_number(MAX_COLS)] = 2;
shipnum -= 2;
map[rand_number(MAX_ROWS)][rand_number(MAX_COLS)] = 1;
shipnum -= 3;
}
However, when I run
/*This will print the array*/
for (a = 0; a < MAX_ROWS; a++)
{
for (b = 0; b < MAX_COLS; b++)
{printf("%d ", map[a][b]);}
printf("\n");
}
}
I am given
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
When I actually want to get something like
0 0 0 0 0 0 0 0 0 0 0 0 0 0 2
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 2 0 0 0 0 0 3 0 0
0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
This is the function I use to generate a random number.
/*This will generate a random number*/
int rand_number(int param)
{
srand((unsigned int)time(NULL));
int x = param;
int rn = rand() % x;
return rn;
}
You are reseeding your random generator on every call which will make it not random. Remove this line:
Your code also allows writing a ship where there already was a ship. If you don’t want to allow this, you should check that the cell is empty before placing a ship in that cell.