我的矩阵大小为[n,n]
。
我需要找到总和 例如
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
sum = 3+4+7+8
我需要找到第一象限矩阵的元素总和
答案 0 :(得分:1)
使用library(clpfd)
,其中提供有用的sum/3
和transpose/2
:
:- use_module(library(clpfd)).
sum_first_quadrant(M, S) :-
first_quadrant(M, Q),
maplist(sum_, Q, Ss),
sum_(Ss, S).
sum_(L, S) :-
sum(L, #=, S).
first_quadrant(M, Q) :-
transpose(M, T),
reverse(T, RT),
dichotomize(RT, RD),
reverse(RD, D),
transpose(D, TD),
dichotomize(TD, Q).
dichotomize(M, D) :-
length(M, L),
X #= L//2,
dichotomize_(M, X, D).
dichotomize_(_, 0, []).
dichotomize_([H|T], X, [H|T2]) :-
X #> 0,
Y #= X - 1,
dichotomize_(T, Y, T2).
示例:
?- sum_first_quadrant([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], Z).
Z = 22 ;
false.
您可以使用library reif
中的dichotomize_
和if_/3
摆脱(=)/3
中无关的选择点:
dichotomize_(L, X, D) :-
X #>= 0,
if_(X = 0,
D = [],
( Y #= X - 1,
L = [H|T],
D = [H|T2],
dichotomize_(T, Y, T2)
)
).
答案 1 :(得分:0)
*> you may get more performance if you `REDEFINE` source-text as a `PIC X OCCURS length-of-text TIMES` - but I find this one more better to read and it shouldn't consume much more time...
MOVE 0 TO target-pointer
PERFORM VARYING source-pointer
FROM 1 BY 1
UNTIL source-pointer > length-of-text
IF source-text (source-pointer:1) = '#'
*> a very good optimizer would calculate the constant on the
*> right side, you may write it directly
IF source-pointer + 4 > length-of-text
ADD 1 TO target-pointer
MOVE source-text (source-pointer:)
TO target-text (target-pointer:)
EXIT PERFORM
END-IF
IF source-text (source-pointer:4) = '#RT#' OR '#LT#' OR ...
ADD 4 TO source-pointer
EXIT PERFORM CYCLE
END-IF
END-IF
ADD 1 TO target-pointer
MOVE source-text (source-pointer:1)
TO target-text (target-pointer:1)
END-PERFORM