我已经做了一些搜索并尝试了很多附加内容,我在stackoverflow的一些问题中看到过,但我无法解决我的问题......
这几乎就是那个问题,但我还有一个列表:
Replacing elements in list of lists PROLOG
我的矩阵:
[
[[-1], [-1], [-1], [4], [-1], [-1], [-1]],
[[-1], [0], [1], [0], [2], [-1]],
[[3], [4], [3], [1], [1], [2], [3]],
[[1], [5], [4], [2], [4], [3]],
[[2], [3], [4], [0], [4], [4], [1]],
[[2], [3], [1], [3], [0], [4]],
[[0], [1], [0], [3], [2], [1], [0]],
[[-1], [2], [2], [5], [0], [-1]],
[[-1], [-1], [-1], [4], [-1], [-1], [-1]]
]
我需要一种方法来替换一个包含带有新列表的数字的列表,并返回带有替换值的all矩阵。 方法replace接收行号和列(位置)编号以及位置的新值。
有没有人知道如何才能做到这一点?
修改
内部列表包含1-5个元素。输入为:Matrix,Row,Cell,NewValue。主要目标是在行的单元格中返回带有newValue的新Matrix。
示例:
我想将行nº1和单元格nº4设置为值:[1,2,3]。
因此输出矩阵将是:
[
[[-1], [-1], [-1], [1,2,3], [-1], [-1], [-1]],
[[-1], [0], [1], [0], [2], [-1]],
[[3], [4], [3], [1], [1], [2], [3]],
[[1], [5], [4], [2], [4], [3]],
[[2], [3], [4], [0], [4], [4], [1]],
[[2], [3], [1], [3], [0], [4]],
[[0], [1], [0], [3], [2], [1], [0]],
[[-1], [2], [2], [5], [0], [-1]],
[[-1], [-1], [-1], [4], [-1], [-1], [-1]]
]
因此该方法用列表[1,2,3]替换列表[4]。
答案 0 :(得分:2)
SWI-Prolog有builtin可以提供帮助:
test :- I=[ [[-1], [-1], [-1], [4], [-1], [-1], [-1]],
[[-1], [0], [1], [0], [2], [-1]],
[[3], [4], [3], [1], [1], [2], [3]],
[[1], [5], [4], [2], [4], [3]],
[[2], [3], [4], [0], [4], [4], [1]],
[[2], [3], [1], [3], [0], [4]],
[[0], [1], [0], [3], [2], [1], [0]],
[[-1], [2], [2], [5], [0], [-1]],
[[-1], [-1], [-1], [4], [-1], [-1], [-1]]
],
replace_row_col(I,1,4,[1,2,3],Upd),
maplist(writeln,Upd).
replace_nth(N,I,V,O) :-
nth1(N,I,_,T),
nth1(N,O,V,T).
replace_row_col(M,Row,Col,Cell,N) :-
nth1(Row,M,Old),
replace_nth(Col,Old,Cell,Upd),
replace_nth(Row,M,Upd,N).
产量
?- test.
[[-1],[-1],[-1],[1,2,3],[-1],[-1],[-1]]
[[-1],[0],[1],[0],[2],[-1]]
[[3],[4],[3],[1],[1],[2],[3]]
[[1],[5],[4],[2],[4],[3]]
[[2],[3],[4],[0],[4],[4],[1]]
[[2],[3],[1],[3],[0],[4]]
[[0],[1],[0],[3],[2],[1],[0]]
[[-1],[2],[2],[5],[0],[-1]]
[[-1],[-1],[-1],[4],[-1],[-1],[-1]]