重新排列列表元素 - Prolog [英] Rearrange list element - Prolog

查看:43
本文介绍了重新排列列表元素 - Prolog的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据子列表的长度从短到长重新排列列表.

I want to rearrange a list according to their length of sublists from short to long.

期望输出为:

rearrange([[a,b],[c],[a,b,c],[d,d,d],[d,s],[s],[d,s,s,a]],X).
X=[[c],[s],[a,b],[d,s],[a,b,c],[d,d,d],[d,s,s,a]].

我的想法是先计算每个长度,然后重新排列.到目前为止,我所做的是使用 [length-number] 模式收集长度等于第一个子列表的子列表的数量.

My idea is that to calculate each length first and then do rearrangement. What I have done so far is to collect the number of sublist whose length is equal to the first sublist using the pattern [length-number].

count([],[0-0]).
count([A|B],[L-N]):-
    length(A,L),
    same_length(B,L,M),
    N is M+1.

same_length([],_,0).
same_length([A|B],L,N) :-
    (   length(A,L)->
        same_length(B,L,M),
        N=M+1
    ;   same_length(B,L,N)
    ).  

count(LIST,X) 输出如下:

The count(LIST,X) output is as followed:

21 ?- count_slot([[2],[3],[4],[2,3,4]],X).
X = [1-3]. 

但是预期的输出是[1-3,3-1],我不知道如何处理剩下的子列表(一一删除??)并按照[1-3,3-1].

But the expected output is [1-3,3-1], I don't know how to deal with the rest sublist(remove one by one??) and rearrange them according to the pattern [1-3,3-1].

有人可以帮忙吗?提前致谢.

Can somebody help? Thanks in advanced.

推荐答案

在这种情况下,keysort/2 通常会派上用场.例如:

In such cases, keysort/2 often comes in handy. For example:

lists_ascending(Lists0, Lists) :-
    maplist(list_with_length, Lists0, LLs0),
    keysort(LLs0, LLs),
    pairs_values(LLs, Lists).

list_with_length(List, L-List) :- length(List, L).

示例查询及其结果:

?- lists_ascending([[a,b],[c],[a,b,c],[d,d,d],[d,s],[s],[d,s,s,a]], Ls).
Ls = [[c], [s], [a, b], [d, s], [a, b, c], [d, d, d], [d, s, s, a]]

EDIT:以下谓词,使用上面的代码,按照你在下面评论中概述的方式进行排序,即按照相同长度的子列表的出现次数:

EDIT: The following predicate, which uses the code above, sorts in the way you outline in the comment below, which is by the number of appearances of sublists of the same length:

lists_ascending_appearences(Lists0, Lists) :-
    maplist(list_with_length, Lists0, LLs0),
    keysort(LLs0, LLs1),
    group_pairs_by_key(LLs1, LLs2),
    pairs_values(LLs2, Lists1),
    lists_ascending(Lists1, Lists2),
    append(Lists2, Lists).

示例查询及其结果:

?- lists_ascending_appearences([[a,b],[c],[a,b,c],[d,d,d],[d,s],[s],[d,s,s,a]], Ls).
Ls = [[d, s, s, a], [c], [s], [a, b], [d, s], [a, b, c], [d, d, d]].

这篇关于重新排列列表元素 - Prolog的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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