将列表变成矩阵 [英] Turn a list into a matrix
问题描述
我整个下午都在做一件简单的事情,但由于某种原因似乎无法做到:如何将列表转换为给定宽度的矩阵.
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 as
[1, 3, 5, 7, 6, 8, 9, 0]
并想创建一个矩阵,例如
and want to create a matrix such as
[[1, 3],
[5, 7],
[6, 8],
[9, 0]]
通过谓词
list2matrix/3 : list2matrix(List, Size_of_Rows, Matrix).
在这个例子中使用如下:
In this example used like :
list2matrix([1, 3, 5, 7, 6, 8, 9, 0], 2, Matrix).
如果列表的长度不是行大小的倍数,则谓词应该失败.
The predicate should fail if the length of the list is not a multiple of the size of the rows.
我决定不发布我的作品,因为我认为我做错了,无法帮助我纠正它;(
I decided not to post my work since I think I got it so wrong that it would not help me to get correction on it ;(
如果您能提出有关如何处理此类问题的任何线索,请提前致谢.
Thanks by advance if you can propose any leads about how to deal with such a problem.
推荐答案
您可以将问题分为两部分.第一个构建块是构建一行 N 个元素.即把输入列表分成两个列表,一个正好有N个元素(行),另一个是输入列表的剩余部分.
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).
这篇关于将列表变成矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!