计算序言中数字的连续出现 [英] count successive occurrences of number in Prolog

查看:96
本文介绍了计算序言中数字的连续出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我试图在Prolog中制作一个程序,给定一个列表,它按如下方式对列表中每个连续元素的出现进行计数:

Hello I am trying to make a program in Prolog that given a list it counts the occurrences of each successive element in the list as follows:

count(1,[1,1,1,2,2,2,3,1,1],0,X)

结果将是X=[ [1,3],[2,3],[3,1][1,2] ] 也就是每个子列表都是[element,occurrences]

the result would be X=[ [1,3],[2,3],[3,1][1,2] ] aka each sublist is [element,occurrences]

就我而言,我认为基本情况存在问题,但我无法解决.你能帮我吗?

In my case i believe there is something wrong with the base case but I cannot solve it. Can you help me?

%append an element to a list
append([ ],Y,Y).
append([X|Xs],Ys,[X|Zs]):-append(Xs,Ys,Zs).

%c is the counter beginning with 0 
count(_,[],_,[]).
count(X,[X],C,[L]):-count(X,[],C,[L|[X,C]]).

%increase counter
count(X,[X|Tail],C,L):-Z is C+1,count(X,Tail,Z,L).
count(X,[Head|Tail],C,[L]):-append(L,[X,C],NL),count(Head,Tail,1,NL).

推荐答案

这里是基于


:- use_module(library(clpfd)).

基于 if_/3 示例查询:

  • 编码/解码#1

  • encode/decode #1


?- list_rle([a,a,b,c,c,c,d,e,e],Ys).
Ys = [2*a,1*b,3*c,1*d,2*e].

?- list_rle(Xs,[2*a,1*b,3*c,1*d,2*e]).
  Xs = [a,a,b,c,c,c,d,e,e]
; false.

  • 编码/解码#2

  • encode/decode #2

    
    ?- dif(A,B),dif(B,C),dif(C,D),dif(D,E), list_rle([A,A,B,C,C,C,D,E,E],Ys).
    Ys = [2*A,1*B,3*C,1*D,2*E], dif(A,B), dif(B,C), dif(C,D), dif(D,E).
    
    ?- list_rle(Xs,[2*A,1*B,3*C,1*D,2*E]).
      Xs = [A,A,B,C,C,C,D,E,E], dif(A,B), dif(B,C), dif(C,D), dif(D,E)
    ; false.
    

  • 有些普遍的事情?

  • How about something a little more general?

    
    ?- list_rle([A,B,C,D],Xs).
      Xs = [4*A            ],     A=B ,     B=C ,     C=D
    ; Xs = [3*A,        1*D],     A=B ,     B=C , dif(C,D)
    ; Xs = [2*A,    2*C    ],     A=B , dif(B,C),     C=D
    ; Xs = [2*A,    1*C,1*D],     A=B , dif(B,C), dif(C,D)
    ; Xs = [1*A,3*B        ], dif(A,B),     B=C ,     C=D
    ; Xs = [1*A,2*B,    1*D], dif(A,B),     B=C , dif(C,D)
    ; Xs = [1*A,1*B,2*C    ], dif(A,B), dif(B,C),     C=D   
    ; Xs = [1*A,1*B,1*C,1*D], dif(A,B), dif(B,C), dif(C,D).
    

  • 这篇关于计算序言中数字的连续出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆