Assign element to matrix only when there is space?

Asked

Viewed 228 times

0

I have some vectors that should be assigned in a 20x20 matrix, but no vectors can override each other and not be printed in different lines, they should be assigned vertically or horizontally. For example, I have vectors :

int a[8] ={1,2,3,4,5,6,7,8};

int b[7] ={7459015};

int c[6] ={5,4,3,7,9,1};

And a matrix 20x20 I want to insert the vectors a and b horizontally and the c vertical, but this in a random order, whenever you run the program it will assign a, b and c in different places. However, these numbers cannot be overwritten, that is, they must all be in the matrix in full and in addition they must be vertical or horizontal, without changing column if it is vertical, and without changing line if it is horizontal.

I tried to generate a random seed of row and column for this, and I used a matrix defined with all elements valid -1, so far so good, but how do I verify if my vector fits in that position generated by rand? This without overwriting another number other than -1 ?

I won’t post the code because it’s very simple, just a rand for row and column and go assigning the vector to matrix, I did not do any treatment to know if there is space for the vector in the matrix, for not knowing even.

In short, it is like generating a position of the random matrix and seeing if it has space in the orientation (vertical or horizontal) to receive my vector. Not about writing any number that isn’t -1.

1 answer

2


You have to check if the space is available before you write the values. You also need to check that the random position does not leave the existing space.

Suppose you wanted to enter 5 values horizontally from (1, 1);

bool disponivel;
do {
    disponivel = true;
    startx = 1; // ou escolha aleatoria
    starty = 1; // ou escolha aleatoria
    for (int k = 0; k < 5; k++) {
        if (a[starty][startx + k] != -1) { disponivel = false; break; )
    }
} while (!disponivel);
// aqui já podes atribuir valores no array

Browser other questions tagged

You are not signed in. Login or sign up in order to post.