I worked all afternoon on a simple thing but cannot seem to get it right for some reason : how to turn a list into a matrix of given width.
Example : I got a list such a
You can divide the problem in two parts. The first building block would be to build a row of N elements. That is to take the input list and split it in two lists, one will have exactly N elements (the row) and the other is the remaining of the input list.
The second building block would be to build the matrix which is made of rows.
list_to_matrix([], _, []).
list_to_matrix(List, Size, [Row|Matrix]):-
list_to_matrix_row(List, Size, Row, Tail),
list_to_matrix(Tail, Size, Matrix).
list_to_matrix_row(Tail, 0, [], Tail).
list_to_matrix_row([Item|List], Size, [Item|Row], Tail):-
NSize is Size-1,
list_to_matrix_row(List, NSize, Row, Tail).
BTW, I thought I'd mention the code I finally wrote :
length_(Length, List) :- length(List, Length).
list2matrix(List, RowSize, Matrix) :-
length(List, L),
HowManyRows is L div RowSize,
length(Matrix, HowManyRows),
maplist(length_(RowSize), Matrix),
append(Matrix, List).
It's more high order oriented and funnier to read I guess :)
Look for a pattern in your desired outcome. That means pair numbers will be allocated as the second number in each pair and non pairs will be in first place each time. Create a bi dimensional array and assign non pair positions to sub index "a" and pairs to "b".
As you could see "i" is an index for an array, a multidimensional array. i[a][b]
You need to iterate through both arrays in order to accomplish this.
Hope it helps.