Rearrange list element - Prolog -
Rearrange list element - Prolog -
i want rearrange list according length of sublists short long.
the expect output is:
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]].
my thought calculate each length first , rearrangement. have done far collect number of sublist length equal first sublist using pattern [length-number].
count([],[0-0]). count([a|b],[l-n]):- length(a,l), same_length(b,l,m), n 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) ).
the count(list,x) output followed:
21 ?- count_slot([[2],[3],[4],[2,3,4]],x). x = [1-3].
but expected output [1-3,3-1], don't know how deal rest sublist(remove 1 one??) , rearrange them according pattern [1-3,3-1].
can help? in advanced.
in such cases, keysort/2
comes in handy. 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).
example query , result:
?- 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: next predicate, uses code above, sorts in way outline in comment below, number of appearances of sublists of 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).
example query , result:
?- 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
Comments
Post a Comment