1

使用 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)
    ).

我想出现/频率计数应该对两者或类似的工作相同。我不知道从哪里开始或如何继续,感谢任何帮助。

4

1 回答 1

1

让我知道您对此解决方案的看法。我假设子序列也必须是一个数字,因为我们正在寻找它在数字中的出现。

这个想法如下:

给定一个数字和另一个数字(子序列),从数字中减去子序列,看看最低有效位是否为零(最低有效位的数量由子序列的大小决定)。如果它们是零,那么我们有 subsequence ,否则我们没有。继续使用 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),!.
于 2012-11-29T13:44:46.690 回答