Make matrix from list

不打扰是莪最后的温柔 提交于 2019-12-24 00:36: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!



来源:https://stackoverflow.com/questions/44267022/make-matrix-from-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!