【问题标题】:Inserting elements into indexes that are the powers of 2 [Prolog]将元素插入到 2 的幂的索引中 [Prolog]
【发布时间】:2022-11-17 20:57:13
【问题描述】:

我必须将一个元素插入到 2 的幂位置的列表中

例如在列表中

L = [1, 2, 3, 4, 5, 6, 7, 8] 

我应该在 first 元素之后插入一个元素 E = 0,然后是 third,然后是 7th,等等,所以结果列表将是

R = [1, 0, 2, 3, 0, 4, 5, 6, 7, 0, 8]

我尝试使用预定义谓词 nth1/4 将元素添加到列表中的位置 P,然后通过将其乘以 2 来增加位置 P

%empty list
ins_aux(_, [], _, _, []).
%if the position is even, add the element and then multiply P by 2 
%and add a value K which is incremented at every step to get the next position 
ins_aux(E, L, P, K, Res) :- 0 is mod(P, 2), !, 
                         nth1(P, Res, E, L), 
                         P1 is (P*2)+K,
                         K1 is K+1,
                         ins_aux(E, Res, P1, K1, Res).
%if the position is odd, add the element to the list 
ins_aux(E, L, P, K, Res) :- nth1(P, Res, E, L),
                         P1 is P+1,
                         ins_aux(E, Res, P1, K, Res).

我的问题是这总是输出false.我显然做错了什么只是我不知道是什么

【问题讨论】:

    标签: list prolog


    【解决方案1】:

    为什么在ins_aux中使用nth1?这使得事情......不必要的二次方:)

    您可以这样做:

    ins_aux([],_,_,[])。
    ins_aux([E|Es],X,I,[E|Rs0]) :-
       ( I / (I-1) == 0
       -> Rs0 = Rs1 % I 不是二的幂
       ; Rs0 = [X|Rs1] % I 是二的幂
       ),
       I1 是 I + 1,
       ins_aux(Es,X,I1,Rs1)。

    使用 Scryer Prolog 的示例查询:

    ?- ins_aux([1,2,3,4,5,6,7,8],0,2,Rs)。
       Rs = [1,0,2,3,0,4,5,6,7,0,8]。
    
    ?- ins_aux([a,b,c,d,e,f,g,h],0,2,Rs)。
       Rs = [a,0,b,c,0,d,e,f,g,0,h]。

    【讨论】:

    • 哇!非常感谢您提供解决方案,但是呃...我不知道这个 / 运算符...它像 pow() 吗?
    • 这些削减真的有必要吗?一个干净的 if-then-else 不是更可取的,毕竟 (=:=)/2 确保实例化错误,表达式和 I 被充分实例化。
    • 说到效率,请注意第二种情况比第一种情况更频繁......
    • 加一:1 是 2 的幂。不是吗?
    猜你喜欢
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    • 2014-10-01
    • 2014-02-26
    • 2022-01-25
    • 2011-11-14
    • 1970-01-01
    相关资源
    最近更新 更多