使用Prolog语言,我需要找出一个数字中子序列的出现次数。
我试图在一个大文本文件中计算一个单词的出现次数,但它也没有用。虽然我有代码。
word_freq(W, Freq) :-
word_count(W, 0, Total, 0, Match),
Total > 0 -> Freq is Match / Total.
word_count(W, TotSoFar, Tot, MatchSoFar, Match) :-
( read_word(SoFar,W),
N \= end_of_file
-> T1 is TotSoFar + 1,
( N == W
-> M1 is MatchSoFar+1
; M1 is MatchSoFar
),
word_count(W, T1, Tot, M1, Match)
; TotSoFar = Tot,
MatchSoFar = Match
).
read_word(SoFar, W) :-
get_code(C),
( C == -1
-> ( SoFar == [] -> W = end_of_file ; reverse(SoFar, W) )
; code_type(C, alnum)
-> read_word([C|SoFar], W)
; reverse(SoFar, W)
).
我认为两者或类似的事件/频率计数应该相同。我不知道从哪里开始或如何继续,感谢任何帮助。
答案 0 :(得分:1)
让我知道您对此解决方案的看法。我假设子序列也必须是一个数字,因为我们正在寻找它的出现次数。
这个想法如下:
给定一个数字和另一个数字(子序列),从数字中减去子序列,并查看最低有效数字是否为零(最低有效数字的数量由子序列的大小确定)。如果它们是零,那么我们有后续,否则我们没有。继续使用NumberNew = Number div 10获得的其余数字执行此操作,直到达到Number小于Subsequence的情况。如果您在理解代码时遇到任何问题,我将编辑帖子并使用评论进行更新。
subsequence_size(Subsequence,1) :- Subsequence < 10,!.
subsequence_size(Subsequence,Size) :- SubNew is Subsequence div 10,subsequence_size(SubNew,N),Size is N+1.
is_subsequence(_,0).
is_subsequence(Number,SubSize) :- Rem is Number mod 10,
Rem=0,
NumberNew is Number div 10,
SubSizeNew is SubSize - 1,
is_subsequence(NumberNew,SubSizeNew).
occurence_of_subsequence_in_number(Subsequence,Number,Occurences) :- subsequence_size(Subsequence,SubSize),
count(Subsequence,SubSize,Number,0,Occurences).
count(0,_,0,Occurences,1) :- Occurences=0,!.
count(0,_,0,Occurences,Occurences) :- not(Occurences=0),!.
count(Subsequence,_,Number,Occurences,Occurences) :- Subsequence > Number,!.
count(Subsequence,SubSize,Number,Occurences,FinalOccurences) :- NumberToTest is Number-Subsequence,
(is_subsequence(NumberToTest,SubSize)),
OccurencesNew is Occurences+1,
NumberNew is Number div 10,
count(Subsequence,SubSize,NumberNew,OccurencesNew,FinalOccurences),!.
count(Subsequence,SubSize,Number,Occurences,FinalOccurences) :- NumberToTest is Number-Subsequence,
not(is_subsequence(NumberToTest,SubSize)),
NumberNew is Number div 10,
count(Subsequence,SubSize,NumberNew,Occurences,FinalOccurences),!.