Generate 2D array with adjacent elements not being x+1

Viewed 93

I need to develop an algorithm which would accept two numbers m and n - dimensions of 2D array - as input and generate 2D array filled with numbers [1..m*n] with the following condition:

All (4) elements adjacent to a given element cannot be equal to currentElement + 1

Adjacent elements are located to the two/three/four sides (depending on position) of a given element

0 1 0
1 2 1
0 1 0

(E.g four 1s are adjacent to 2)

Example:

Input: m = 3, n = 3 (does not essentially have to be square matrix)

(Sample) output:

[
[7, 2, 5],
[1, 6, 9],
[3, 8, 4]
]

Note that there apparently may exist more than one possible output. In that case, numbers in the array have to be generated randomly (though still meeting the conditions), not following any preset sequence (e.g not [ [1, 3, 5], [4, 6, 2], [7, 9, 8] ] because it clearly uses a non-randomly generated sequence of numbers, odds first, then evens, etc)

Basically, for the same input, on two different occasions, two different arrays should be generated.

P.S: that was a coding interview question and I wonder how I could solve it, so, any help is highly appreciated.

0 Answers
Related