[英]Prolog: How can I know if each constant appers the same times of the others?
我需要知道一個常數是否與其他常數出現相同的時間。 例如:
?- eq([a, a, a, b, b, b, 1, 1, 1])。
真的。 // 這是真的,因為“a”出現了 3 次,“b”出現了 3 次,“1”出現了 3 次。
?- eq([a, b, c, b])。
錯誤的。 // 這是錯誤的,因為“a”和“c”出現了 1 次,而 b 出現了 2 次
你能幫助我嗎? ;-;
ps:我不能使用該語言的函數或庫
repeats_same_len(Lst) :-
% Check repeats (don't care what the common length is)
elem_repeats_same_len(Lst, _).
% Success if reached end of list
elem_repeats_same_len([], _).
elem_repeats_same_len([H|T], Len) :-
% Check length of this repeating element
elem_repeats_len([H|T], Rem, H, Len),
% Ensure that the rest of the list has same length of repeat
elem_repeats_same_len(Rem, Len).
% 2nd arg is remainder of list
elem_repeats_len([], [], _, 0).
elem_repeats_len([H], [], H, 1) :- !.
elem_repeats_len([H1, H2|T], [H2|T], H1, 1) :-
% 2nd elem is different
H1 \= H2, !.
elem_repeats_len([H, H|T], Rem, H, Len) :-
% Recursively search for same element
elem_repeats_len([H|T], Rem, H, Len0),
% Increment count of repeats for this element
Len is Len0 + 1.
結果 swi-prolog:
?- repeats_same_len([a,a,a,b,b,b,c,c,c]).
true.
?- repeats_same_len([a,b]).
true.
?- repeats_same_len([a,a,b]).
false.
?- repeats_same_len([a,a,b,b]).
true.
?- repeats_same_len([a,a,b,b,b]).
false.
?- repeats_same_len([a]).
true.
?- repeats_same_len([]).
true.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.