Prolog-将清单分为两半,将前半部分颠倒 [英] Prolog - Split a list in two halves, reversing the first half
本文介绍了Prolog-将清单分为两半,将前半部分颠倒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我被要求将一个字母列表分成两个列表,两个列表大小相等(我猜是原尺寸的原始列表),或者一个比另一个大一个元素(奇数列表),然后颠倒第一个当我在它的时候.
I am asked to take a list of letters into two lists that are either equal in size (even sized original list I guess) or one is larger than the other by one element (odd sized list), and reverse the first one while I'm at it.
查询和输出示例:
?- dividelist2([a,b,c,d,e,f], L1,L2).
L1 = [c,b,a]
L2 = [d,e,f]
?- dividelist2([a,b,c,d,e], L1,L2).
L1 = [c,b,a]
L2 = [d,e]
% OR
L1 = [b,a]
L2 = [c,d,e]
我已经达到了这个解决方案,但是我感觉到它有问题.如果我缺少什么,请让我知道...我如何获得最后的输出? (我的意思是有两个输出选项)
I've reached this solution, but I have a feeling something is wrong with it. Please let me know if I'm missing something... How do I get the last output? (two options for output, I mean)
dividelist2(L, X, B) :-
( append(A, B, L),
length(A, O),
length(B, N),
( (O-1) =:= N
; (O+1) =:= N
; O =:= N
),
!
), reverse(A, X).
reverse(List, Rev) :-
reverse(List, Rev, []).
reverse([], L, L).
reverse([H|T], L, SoFar) :-
reverse(T, L, [H|SoFar]).
提前谢谢!
推荐答案
您在正确的轨道上:
splitflip(In, Out1, Out2) :-
length(In, L), % length of the list
FL is L//2, % integer division, so half the length, Out1 will be 1 shorter than Out2 if L is odd
( \+ (FL*2 =:= L), % is odd
FLP is FL + 1 % odd case, choicepoint left
; FLP = FL % odd and even case, no choicepoint left
), % the one place we need a choicepoint for the odd length case of an odd input, note order prunes choicepoint for even case
length(FirstHalf, FLP), % generate an list of vars to the right length
append(FirstHalf, Out2, In), % unify with the first half and generate second half of correct length
reverse(FirstHalf, Out1). % do the reverse
只需稍微重新排序一下,然后使用整数除法即可.
Just need to reorder things a bit and use integer division.
这篇关于Prolog-将清单分为两半,将前半部分颠倒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文