Index of a specific element in a multidimensional list using Prolog

I'm trying to figure out if there is a way to find a specific index of an element in a multidimensional list, for example [[1,2,3],[4,5,6],[7,8,9]]


How do I find the index '5' - [2] [2] or get the value [3] [3]? Is this possible if the size of the list is unknown? Or is there a built-in predicate?


source to share

1 answer

You can use nth1 / 3 to achieve this goal:

index(Matrix, Row, Col, Value):-
  nth1(Row, Matrix, MatrixRow),
  nth1(Col, MatrixRow, Value).


Test cases:

?- index([[1,2,3],[4,5,6],[7,8,9]], 2, 2, X).
X = 5.

?- index([[1,2,3],[4,5,6],[7,8,9]], Row, Col, 5).
Row = Col, Col = 2 ;




All Articles