Prolog - 通过矩阵迭代

时间:2016-01-22 15:03:08

标签: matrix grid prolog

只是想警告你,我对Prolog很新,甚至不知道从哪里开始。

首先,我需要创建一个3x3的网格。然后我需要遍历它并打印出我正在使用的当前正方形。

所以网格看起来像:

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

我的讲师没有提供任何例子,我不知道还有什么地方可以转。

1 个答案:

答案 0 :(得分:1)

好吧,你的网格看起来像这样:

Grid = [[6,7,8],[5,4,3],[0,1,2]].

我喜欢这个用于访问矩阵的谓词:

matrix(Matrix, I, J, Value) :-
    nth0(I, Matrix, Row),
    nth0(J, Row, Value).

这为您提供矩阵,列索引,行索引和该位置的值之间的关系。将此视为关系非常重要,因为它可以为您做很多事情:

  1. 获取矩阵中给定坐标的值:

    ?- Grid = [[6,7,8],[5,4,3],[0,1,2]], matrix(Grid, 1, 1, Value).
    Grid = [[6, 7, 8], [5, 4, 3], [0, 1, 2]],
    Value = 4.
    
  2. 迭代矩阵:

    ?- Grid = [[6,7,8],[5,4,3],[0,1,2]], matrix(Grid, I, J, Value).
    Grid = [[6, 7, 8], [5, 4, 3], [0, 1, 2]],
    I = J, J = 0,
    Value = 6 ;
    Grid = [[6, 7, 8], [5, 4, 3], [0, 1, 2]],
    I = 0,
    J = 1,
    Value = 7 ;
    Grid = [[6, 7, 8], [5, 4, 3], [0, 1, 2]],
    I = 0,
    J = 2,
    Value = 8 ;
    Grid = [[6, 7, 8], [5, 4, 3], [0, 1, 2]],
    I = 1,
    J = 0,
    Value = 5 ;
    Grid = [[6, 7, 8], [5, 4, 3], [0, 1, 2]],
    I = J, J = 1,
    Value = 4 ;
    Grid = [[6, 7, 8], [5, 4, 3], [0, 1, 2]],
    I = 1,
    J = 2,
    Value = 3 ;
    Grid = [[6, 7, 8], [5, 4, 3], [0, 1, 2]],
    I = 2,
    J = Value, Value = 0 ;
    Grid = [[6, 7, 8], [5, 4, 3], [0, 1, 2]],
    I = 2,
    J = Value, Value = 1 ;
    Grid = [[6, 7, 8], [5, 4, 3], [0, 1, 2]],
    I = J, J = Value, Value = 2.
    
  3. 从矩阵中选择一行:

    ?- Grid = [[6,7,8],[5,4,3],[0,1,2]], 
       findall(Value, matrix(Grid, 1, _, Value), Row).
    Grid = [[6, 7, 8], [5, 4, 3], [0, 1, 2]],
    Row = [5, 4, 3].
    
  4. 从矩阵中选择一列:

    ?- Grid = [[6,7,8],[5,4,3],[0,1,2]], 
       findall(Value, matrix(Grid, _, 1, Value), Column).
    Grid = [[6, 7, 8], [5, 4, 3], [0, 1, 2]],
    Column = [7, 4, 1].
    
  5. 构造一个新矩阵(!):

    ?- matrix(M, 0, 0, 4), matrix(M, 1, 1, 2).
    M = [[4|_G673], [_G678, 2|_G682]|_G676].
    
  6. 实际上,这一个谓词可以完成所有操作,因为它只是建立了矩阵的结构,浮出了调用者可能感兴趣的值,并让Prolog的回溯完成其余的工作。 / p>

    这个列表表示不如C中的矩阵有效,但你不能让你失望:你正在使用Prolog!

    如果您真的对列表性能感到不满,那么您可以执行相同的操作,但更改结构以使用arg/3和术语而不是列表。整洁的是,你可以在改变后保持matrix/4的API一样!但是你可能会失去#5。

    因此,现在显示矩阵中的所有值非常简单:

    display_matrix(Matrix) :-
        matrix(Matrix, I, J, Value),
        write('I am on square ('),
        write(I), write(','), write(J),
        write(') and the value is '), write(Value), nl,
        fail.
    display_matrix(_).
    

    让我们尝试一下:

    ?- Grid = [[6,7,8],[5,4,3],[0,1,2]], 
       display_matrix(Grid).
    I am on square (0,0) and the value is 6
    I am on square (0,1) and the value is 7
    I am on square (0,2) and the value is 8
    I am on square (1,0) and the value is 5
    I am on square (1,1) and the value is 4
    I am on square (1,2) and the value is 3
    I am on square (2,0) and the value is 0
    I am on square (2,1) and the value is 1
    I am on square (2,2) and the value is 2
    Grid = [[6, 7, 8], [5, 4, 3], [0, 1, 2]].
    

    希望这有帮助!