如何在 prolog 中转置矩阵
如何将 [[1,2,3][4,5,6][6,7,8]]
之类的列表转置为 [[1,4,6], [2,7,8],[3,6,9]]
?
描述它:我想将矩阵向左翻转 90 度。我怎样才能做到这一点?
How can I transpose a list like [[1,2,3][4,5,6][6,7,8]]
to [[1,4,6],[2,7,8],[3,6,9]]
?
To depict it: I'd like to flip the matrix 90 degree to the left. How can I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
不确定你的例子是否正确,但我明白了。
如果使用 SWI-PROLOG,您可以使用 CLPFD 模块,如下所示:
< code>:- use_module(library(clpfd)).
允许您使用
transpose/2
谓词,如下所示:否则(如果没有 SWI-PROLOG),您可以简单地使用此实现(恰好是 SWI 的 clpfd 中的旧版本):
有关使用内置的foldl和maplist的更新版本,请参阅clpfd.pl。
Not sure your example is correct, but I get the idea.
If using SWI-PROLOG, you can use the CLPFD module, like so:
:- use_module(library(clpfd)).
Allowing you to use the
transpose/2
predicate, like this:Otherwise (if no SWI-PROLOG), you could simply use this implementation (which happened to be an old one in SWI's clpfd):
For an updated version which uses foldl and maplist built-ins, see clpfd.pl.
这是我能想到的最小的解决方案。
代码
测试
打印:
解释
它的工作方式是
transpose
将递归调用transpose_1st_col
来提取并转置矩阵的第一列。例如:将打印
and
重复此操作,直到输入矩阵为空,此时所有列都已转置。然后将转置的列连接到转置的矩阵中。
This is the smallest solution I could come up with.
Code
Test
Prints:
Explanation
The way it works is that
transpose
will recursively calltranspose_1st_col
which extracts and transposes the first column of the matrix. For example:will print
and
This is repeated until the input matrix is empty, at which point all columns have been transposed. The transposed columns are then joined into the transposed matrix.
这是较大答案的片段:
Here's a fragment of a larger answer:
另一种简单的方法:
Another simple approach:
更简单的方法:
也高效
simpler approach:
efficient also
迭代方法:
An iterative approach:
我的解决方案带有全名,以便更好地理解:
“行”可以是列或行。
这个想法在于将元素附加到空矩阵的列表中。
(例如第一行的所有元素 = 所有列的第一个元素
=>第 i-n 行的所有元素 = 所有列的第 i-n 个元素)
它在我的机器上工作,正如此会话协议向我显示的那样:
My solution with full names for a better understanding:
A 'line' can be a col or a row.
The idea lies in appending the elements into the lists of an empty matrix.
(e.g. all elements of the first row = the first elements of all cols
=> all elements of the first i-nth row = the i-nth elements of all cols)
It works on my machine as this session protocol shows to me:
另一种方法:
Another approach: