Make matrix from list

2019-07-18 14:59发布

问题:

Good morning. I need your help. I want to make a list of list (matrix with size SQRT(N)*SQRT(N)) from a list with Size N

I am tried but It does not work for me :(

gen(L,T,Matrix)

which T is the size of Matrix You are free to add more param if you want

for example

gen([1,2,3,4,5,6,7,8,9],3,Matrix)
Matrix = [[1,2,3],[4,5,6],[7,8,9]]

回答1:

This is actually a fairly straightforward problem. The trick is to remember that append/3 has many instantiation patterns, and can be used not just to glue lists together but also to break them apart:

?- append(X, Y, [1,2,3,4]).
X = [],
Y = [1, 2, 3, 4] ;
X = [1],
Y = [2, 3, 4] ;
X = [1, 2],
Y = [3, 4] ;
X = [1, 2, 3],
Y = [4] ;
X = [1, 2, 3, 4],
Y = [] ;
false.

You can use length/2 to control the size of the list you make as well:

?- append(X, Y, [1,2,3,4]), length(X, 3).
X = [1, 2, 3],
Y = [4] ;
false.

This is almost everything you need right here. The rest is just wrapping this in a recursive call. You need a base case:

gen([], _, []).

This essentially says, my dimension doesn't matter if I'm out of flat-representation or matrix representation.

Now the recursive case:

gen(List, T, [Start|Rest]) :-
    append(Start, Remainder, List),
    length(Start, T),
    gen(Remainder, T, Rest).

This is a very basic recursive predicate. The append/3 followed by length/2 steps are the same as above; they establish a length T prefix of List as the next chunk of the result. Then we recursively apply ourselves to the remaining List to generate the Rest of the result.

As a cool side benefit, this predicate works both ways:

?- gen(X, 3, [[1, 2, 3], [4, 5, 6], [7, 8, 9]]).
X = [1, 2, 3, 4, 5, 6, 7, 8, 9] ;
false.

How nice is that!



标签: prolog