How to transpose a matrix in prolog

后端 未结 8 1910
悲&欢浪女
悲&欢浪女 2020-12-06 18:40

How can I transpose a list like [[1,2,3][4,5,6][6,7,8]] to [[1,4,6],[2,7,8],[3,6,9]]?

To depict it: I\'d like to flip the matrix 90 degree

8条回答
  •  一向
    一向 (楼主)
    2020-12-06 19:20

    simpler approach:

    trans(M, [P|T]):- first(M, P, A), trans(A, T).
    trans(Empty, []):- empty(Empty).
    
    empty([[]|T]):- empty(T).
    empty([[]]).
    
    first([[P|A]|R], [P|Ps], [A|As]):- first(R, Ps, As).
    first([], [], []).
    

    efficient also

    [debug] 36 ?- time(trans([[1,2,3],[4,5,6],[7,8,9]],A)).
    % 21 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)
    A = [[1,4,7],[2,5,8],[3,6,9]] ;
    % 12 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)
    false.
    

提交回复
热议问题