正如标题所述,我有四个单独的列表。我想要做的是:
/* Pseudo-code (not in prolog).. */
if(size(List1) % 2 == 1) {
/* Take the head of List1, and move it to List2 */
}
if(size(List2) % 2 == 1) {
/* Take the head of List2, and move it to List3 */
}
if(size(List4) % 2 == 1) {
/* Take the head of List4 and move it to List2 */
}
if(size(List3) % 2 == 1) {
/* Take the head of List3 and move it to List4 */
}
所以,如果我有以下格式:list(contents, list_name)
以及以下事实:
list([1,2,3,4], List1).
list([5,6,7], List2).
list([8,9,10], List3).
list([11,12,13,14], List4).
% validList(ListNo,ListTransfer).
% If ListNo has an odd number of items, we can move any item to the list, ListTransfer).
validList(List1,List2).
validList(List2,List3).
validList(List2,List4).
validList(List4,List3).
我写这篇文章是为了检查它,但我不确定我是否走在正确的道路上:
checkList(ListFrom,ListTo):-
1 is mod(size(ListFrom), 2), % Check to see if size of list is odd
ListFrom = [Head|Tail], % it is, so we grab the head of the list
append(Head, ListTo, ListTo).% we then append it to the correct list
我对序言非常陌生,并且仍在努力理解它。是否有更简洁的方法来根据某些约束对列表项的这种移动进行编码?
最佳答案
TL;DR:您在OP中给出的两个伪代码不匹配!
以下内容基于两个假设:
要达到一个固定点。毕竟,您在评论中写道:
Basically, I know for a fact that at the end (after moving items around if there are an odd amount of items), that each list will have an even amount of items.
第一个伪代码就是您的目标。
/* Pseudo-code (not in prolog).. */ if(size(List1) % 2 == 1) { /* Take the head of List1, and move it to List2 */ } if(size(List2) % 2 == 1) { /* Take the head of List2, and move it to List3 */ } if(size(List4) % 2 == 1) { /* Take the head of List4 and move it to List2 */ if(size(List3) % 2 == 1) { /* Take the head of List3 and move it to List4 */ }
坏消息:上面的“代码”可能无法达到固定点(满足第一个约束)!
作为反例,请考虑以下循环 ( 2->3->4->2
):
L1 = [], L2 = [2], L3 = [], L4 = []
:取出L2的头部,并将其移动到L3L1 = [], L2 = [], L3 = [2], L4 = []
:将L3的头部移动到L4L1 = [], L2 = [], L3 = [], L4 = [2]
:将L4的头部移动到L2L1 = [], L2 = [2], L3 = [], L4 = []
: 返回步骤1
关于list - 从列表中删除第一个元素,并将该元素 append 到 Prolog 中的另一个列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33884613/