Search code examples
prologlogicdeclarative

Index of specific element in a multi-dimensional list using Prolog


I'm trying to find out if there is any way to find specific element index in a multi dimensional list, for example [[1,2,3],[4,5,6],[7,8,9]]?

How to find index of '5' - [2][2] or get value [3][3] ? Is this possible without when size of the list is unknown? Or is there any built-in predicate?


Solution

  • You can use nth1/3 to achieve it:

    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 ;