Home > Software design >  Choosing random numbers in a 2D arrays
Choosing random numbers in a 2D arrays

Time:10-24

I want to pick 2 numbers randomly in a 2D array[4][2]. My 2D array stock (x, y) and I want to randomly choose between two coordinates.

I tried the following algorithm, but it doesn't work:

#define _CRT_SECURE_NO_WARNINGS
#define DEBUG
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

int nb_aleatoire(int min, int max)
{
    return min   (int)(rand() / (RAND_MAX   0.001) *(max - min   1));
}

int main(void)
{
    int lab[4][2] = {
        { 1, 4 },
        { 2, 4 },
        { 3, 8 }
    };

    int alea;
    int x;
    int y;
    int i, j;

    /*On initialise le générateur de nombres aléatoires. */
    srand((unsigned int) time(NULL));
    rand();

    for (i = 0; i < 1; i  )
    {
        printf("(%d, %d)\n", rand(lab[i][i   1]), rand(lab[i][i   1]));
    }

    system("pause");
    return EXIT_SUCCESS;
}

CodePudding user response:

For starters:

int lab[4][2] = {
    { 1, 4 },
    { 2, 4 },
    { 3, 8 },
};

Your 4 element array only has 3 members.

Howe about this instead:

int lab[4][2] = {
    { 1, 4 },
    { 2, 4 },
    { 3, 8 },
    { 4, 9 }
};

As for this line:

printf("(%d, %d)\n", rand(lab[i][i   1]), rand(lab[i][i   1]));

I'm not sure how it compiles since rand doesn't take any parameters. (Are you really compiling as C?). rand returns a value between 0 and RAND_MAX, which is typically 32767. To clamp the range of rand, use a modulo % operator.

int c1 = rand() % 4;
int c2 = rand() % 4;
int r1 = rand() % 2;
int r2 = rand() % 2;
printf("(%d, %d)\n", lab[c1][r1], lab[c2][r2]);

CodePudding user response:

rand doesn't take any arguments.

This could be done by:

size_t max_x = std::size(lab);
size_t max_y = std::size(lab[0]);

size_t random_x = rand() % max_x;
size_t random_y = rand() % max_y;

auto random_value = lab[random_x][random_y];

std::size was introduced in C 17, so for older versions, the array size must be calculated like this:

size_t max_x = sizeof(lab) / sizeof(lab[0]);
size_t max_y = sizeof(lab[0]) / sizeof(lab[0][0]);
  •  Tags:  
  • c
  • Related