在prolog中转置矩阵

时间:2015-12-07 22:01:35

标签: prolog

我在下面编写了以下代码,以便在prolog中转置矩阵

listFirst([],[]).
listFirst([H1|T1],[H2|Z]):-
    H1 = [H2|_],
    listFirst(T1,Z).

listFollowers([],[]).
listFollowers([H1|T1],[T2|Z]):-
    H1 = [H2|T2],
    listFollowers(T1,Z).

decompose(A,L1,L2):-
    listFollowers(A,L2),listFirst(A,L1).

transpose([],[]).
transpose([H|T],[L1|R]):-   
    decompose([H|T],L1,L2),
    transpose(L2,R).

测试用例

transpose([[1,2],[3,4],[5,6]], R).
R = [[1,3,5],[2,4,6]] ;

我遇到了transpose谓词的问题,不确定如何实现它。其他谓词似乎没问题。

3 个答案:

答案 0 :(得分:2)

取自SWI-Prolog中的<form action='submit.php' method='get' name='xword' id='xword1'> <?php $array=array( array("h","e","l","l","o","0","0","0"), array("e","0","0","0","0","0","0","0"), array("l","0","0","0","0","0","0","0"), array("l","0","0","0","0","0","0","0"), array("o","0","0","0","0","0","0","0"), array("0","0","0","0","0","0","0","0"), array("0","0","0","0","0","0","0","0"), array("0","0","0","0","0","0","0","0"), ); $X = 0; while ($X < "8") { $Y = 0; while ($Y < "8") { if ($array[$X][$Y] == "0") { echo "<input type='text' id='text' name='" . $X . "[$Y]' class='blank'>"; } else { echo "<input type='text' id='text' name='" . $X . "[$Y]' class='text'>"; } $Y++; } echo "<br />"; $X++; } ?> <input type='submit' value='Submit'> (有关详细信息,请参阅source code):

library(clpfd)

示例查询:

transpose([], []).
transpose([L|Ls], Ts) :- foldl(transpose_, L, Ts, [L|Ls], _).

transpose_(_, Fs, Lists0, Lists) :-
        maplist(list_first_rest, Lists0, Fs, Lists).

list_first_rest([L|Ls], L, Ls).

答案 1 :(得分:2)

我的旧代码 - 相当高效的强硬

transpose_col_row([], []).
transpose_col_row([U], B) :- gen(U, B).
transpose_col_row([H|T], R) :- transpose_col_row(T, TC), splash(H, TC, R).

gen([H|T], [[H]|RT]) :- gen(T,RT).
gen([], []).

splash([], [], []).
splash([H|T], [R|K], [[H|R]|U]) :-
    splash(T,K,U).

答案 2 :(得分:1)

这可能会有所帮助。 如果您更改基本案例以便将列表列表添加到完整列表中,它将起作用。即使它可能不是最有效的方法,因为它只能获得4个列表。这意味着一个四行矩阵。

transpose([[X],[Y],[Z],[B]],[[X,Y,Z,B]]).
transpose([H|T],[L1|R]):-    
    decompose([H|T],L1,L2),
    transpose(L2,R).