I am practicing some exercises and have been going in circles trying to figure it out. The first part is to create a 5x5 matrix with NumPy giving it random values, and I’ve already solved it.
Now I need to see if the matrix, either horizontally or vertically, has consecutive numbers (for example: The matrix of the attached image does not have consecutive numbers). Here is there are 4 consecutive numbers in the first column: [[50 92 78 84 36] [51 33 94 73 32] [52 94 35 47 9] [53 5 60 55 67] [83 51 56 99 18]]` Here are 4 consecutive numbers in the last row [[50 92 78 84 36] [41 33 94 73 32] [72 94 35 47 9] [55 5 60 55 67] [84 85 86 87 18]]"
The last step is to continue randomizing the array until you find those consecutive numbers.
CodePudding user response:
All things you need to do is to check whether a position in a mtrix minus its previous position (both horizontally and vertically) equals to 1 or -1.
You can use np.diff method, this calculates the difference of a matrix along a given axis, for example:
M = np.random.randint(1, 100, size=(5,5))
print(M)
print(np.diff(M)) # Horizontally
print(np.diff(M.T)) # Vertically
[[ 4 69 99 11 61]
[81 36 12 27 3]
[92 86 68 40 49]
[11 58 49 6 32]
[74 52 87 95 1]]
[[ 65 30 -88 50]
[-45 -24 15 -24]
[ -6 -18 -28 9]
[ 47 -9 -43 26]
[-22 35 8 -94]]
[[ 77 11 -81 63]
[-33 50 -28 -6]
[-87 56 -19 38]
[ 16 13 -34 89]
[-58 46 -17 -31]]
Then you can use np.any
together with np.abs
to find whether these difference matrices contain 1 or -1:
def has_consecutive_number(M):
return np.any(np.abs(np.diff(M)) == 1) or np.any(np.abs(np.diff(M.T)) == 1)
Testing:
M = np.random.randint(1, 100, size=(5,5))
print(M)
print(has_consecutive_number(M))
[[73 72 23 16 43]
[ 4 43 14 42 98]
[76 89 82 13 18]
[43 93 73 17 29]
[85 49 77 42 78]]
True
[[ 8 96 2 91 2]
[37 55 37 74 94]
[51 97 6 94 15]
[74 95 52 46 82]
[ 3 95 42 72 23]]
False