Prolog - 矩阵中行的总和

发布于 2024-10-06 05:33:08 字数 679 浏览 4 评论 0原文

一个 nxn 矩阵可以表示为 n 个列表的列表,每个列表有 n 个元素, 矩阵实际上可以 1 2 3 4 5 6 7 8 9 写为 [[1, 2, 3], [4, 5, 6], [7, 8, 9]]。

我需要编写一个 Prolog 程序来添加每个 ROW 中的所有值。 我是 Prolog 新手,请帮忙。 提前致谢!

以下是我所做的,但似乎不起作用......

sum(X):-
    result(X,0,0,Y),!.

result([H|T],I,J,Length):-
    rowTotal([H|T],J,Sum),
    write('Sum of Row: '),
    write(Sum),nl,
    (not(I = Length)) ->
    (NewI is I + 1,
    result([H|T],NewI,0,Length);!).

rowTotal([H|T],J,Sum):-
    rowValue(H,J,Value),
    rowTotal(T,NewSum),
    Sum is Value + NewSum.

rowTotal([],0).

rowValue([H|T],J,Value):-
    (J < 3) ->
    Value = H,
    NewJ is J+1,
    rowValue([H|T],NewJ,Value).

An n x n matrix can be represented as a list of n lists, each with n elements,
the matrix could actually
1 2 3
4 5 6
7 8 9
written as [[1, 2, 3], [4, 5, 6], [7, 8, 9]].

I need to write a Prolog program to add all the values in each ROW.
I am new in Prolog, please help.
Thanks in advanced!

Below is what I had done, but it seems like not working....

sum(X):-
    result(X,0,0,Y),!.

result([H|T],I,J,Length):-
    rowTotal([H|T],J,Sum),
    write('Sum of Row: '),
    write(Sum),nl,
    (not(I = Length)) ->
    (NewI is I + 1,
    result([H|T],NewI,0,Length);!).

rowTotal([H|T],J,Sum):-
    rowValue(H,J,Value),
    rowTotal(T,NewSum),
    Sum is Value + NewSum.

rowTotal([],0).

rowValue([H|T],J,Value):-
    (J < 3) ->
    Value = H,
    NewJ is J+1,
    rowValue([H|T],NewJ,Value).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

只是偏爱你 2024-10-13 05:33:08

您不需要计数器 IJ。只需边走边解压列表即可。下面是 rowTotal 的解决方案:

rowTotal([], 0).
rowTotal([H|T], Sum) :-
    rowTotal(T, SubTotal),
    Sum is H + SubTotal.

以下尾递归解决方案有点难以理解,但效率更高:

rowSum(L, Sum) :-
    rowResult(L, 0, Sum).

rowResult([], Acc, Acc).
rowResult([H|T], Acc, Sum) :-
    S is H + Acc,
    rowResult(T, S, Sum).

应用相同的技术来实现 sumresult

You don't need counters I and J. Simply unpack the lists as you go. Here's a solution for rowTotal:

rowTotal([], 0).
rowTotal([H|T], Sum) :-
    rowTotal(T, SubTotal),
    Sum is H + SubTotal.

The following tail-recursive solution is a little trickier to get your head around, but is more efficient:

rowSum(L, Sum) :-
    rowResult(L, 0, Sum).

rowResult([], Acc, Acc).
rowResult([H|T], Acc, Sum) :-
    S is H + Acc,
    rowResult(T, S, Sum).

Apply the same technique to implement sum and result.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文