Home > Blockchain >  Compare Each Cell in 3D Array for N-Puzzle problem
Compare Each Cell in 3D Array for N-Puzzle problem

Time:11-15

I'm trying to compare the lists below, the first two integers represent the location of 0 or space within the grid. I want to compare each cell within goal[2]/test[2] and calculate the cells that match. In this case, only 5 would match as location matters. Any advice on how to do this efficiently would be much appreciated :)

goal = [0, 2, [[3, 2, 0], [6, 1, 8], [4, 7, 5]]]
test = [0, 0, [[0, 7, 1], [4, 3, 2], [8, 6, 5]]]

CodePudding user response:

I would consider using the zip() method twice:

goal = [0, 2, [[3, 2, 0], [6, 1, 8], [4, 7, 5]]]
test = [0, 0, [[0, 7, 1], [4, 3, 2], [8, 6, 5]]]

for a,b in zip(goal[2],test[2]):
    for g,t in zip(a,b):
        print(g)
        print(t)
        print()

The code above only prints values on given places, but after slight modifications it should fit your requirements, however I'm not exactly sure what results do you want so I'll leave it to you.

CodePudding user response:

You can try the following:

# array data changed from the question to make
# the results more illustrative
goal = [0, 2, [[3, 2, 0], [6, 1, 8], [5, 7, 4]]]
test = [0, 0, [[0, 7, 1], [4, 1, 2], [5, 6, 6]]]

import numpy as np
g2 = np.array(goal[2])
t2 = np.array(test[2])
np.c_[np.nonzero(g2==t2)]

This gives:

array([[1, 1],
       [2, 0]])

It means that there are two matching elements: one in row 1, column 1, and the other in row 2, column 0.

  • Related