从列表制作矩阵 [英] Make matrix from list

查看:41
本文介绍了从列表制作矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

早上好.我需要你的帮助.我想从一个大小为 N 的列表中创建一个列表(大小为 SQRT(N)*SQRT(N) 的矩阵)

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)

其中 T 是矩阵的大小如果需要,您可以随意添加更多参数

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

例如

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

推荐答案

这实际上是一个相当简单的问题.诀窍是要记住 append/3 有许多实例化模式,不仅可以用来将列表粘合在一起,还可以用来将它们分开:

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.

您也可以使用 length/2 来控制您制作的列表的大小:

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.

现在递归的情况:

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

这是一个非常基本的递归谓词.append/3 后跟 length/2 步骤与上面相同;他们建立一个长度为 List 的 T 前缀作为结果的下一个块.然后我们递归地将自己应用于剩余的 List 以生成剩余的结果.

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.

多好啊!

这篇关于从列表制作矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆