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
My solution with full names for a better understanding:
% emptyMatrix(Line, EmptyMatrix)
emptyMatrix([],[]).
emptyMatrix([_|T1],[[]|T2]):-emptyMatrix(T1,T2).
% only length of parameter 'Line' is interesting. It ignores its content.
% appendElement(Element, InputList, OutputList)
appendElement(E,[],[E]).
appendElement(E,[H|T],[H|L]):-appendElement(E,T,L).
% appendTransposed(NestedList, InputMatrix, OutputMatrix)
appendTransposed([],[],[]).
appendTransposed([X|T1],[],[[X]|T3]):-appendTransposed(T1,[],T3).
appendTransposed([X|T1],[R|T2],[C|T3]):-appendElement(X,R,C),appendTransposed(T1,T2,T3).
% transposeMatrix(InputMatrix, TransposedMatrix)
transposeMatrix([L|M],T):-emptyMatrix(L,A),transpose([L|M],T,A).
transpose([],T,T).
transpose([L|M],T,A):-appendTransposed(L,A,B),transpose(M,T,B).
A 'line' can be a col or a row.
The idea lies in appending the elements into the lists of an empty matrix. (e.g. all elements of the first row = the first elements of all cols => all elements of the first i-nth row = the i-nth elements of all cols)
It works on my machine as this session protocol shows to me:
5 ?- transposeMatrix([[1,2],[3,4]],T).
T = [[1, 3], [2, 4]] ;
false.
6 ?- transposeMatrix([[1],[2]],T).
T = [[1, 2]] ;
false.
7 ?- transposeMatrix([[1,2,3],[4,5,6]],T).
T = [[1, 4], [2, 5], [3, 6]] ;
false.
8 ?- transposeMatrix([[1]],T).
T = [[1]] ;
false.