【问题标题】:Prolog - Tell if abs value of max is greater then abs value of min in list of integersProlog - 判断最大值的绝对值是否大于整数列表中最小值的绝对值
【发布时间】:2021-06-30 11:16:18
【问题描述】:

我的任务发生了一些变化。我还需要在 prolog 中实现 abs 和 max。我需要获取整数列表并判断最大值的绝对值是否大于最小值的绝对值。 - M

我的代码是这样的:

ismaxgreater([X],X).
ismaxgreater([X],X):-
    maxlist([X],X).
    %minlist([X],Y),
    %abs([Y],Z),
    %com(X,Z).

maxlist([X],X).
maxlist([X,Y |Rest],Max) :-
    maxlist([Y | Rest], MaxRest),
    max(X,MaxRest,Max).

minlist([X],X).
minlist([X,Y |Rest],Min) :-
    maxlist([Y | Rest], MinRest),
    max(X,MinRest,Min).

com(Max,Min) :- Max>Min,
    write('Max is Bigger Value');
    Max<Min,
    write('Min is Bigger Value').

max(X,Y,X) :- X>= Y.
max(X,Y,Y) :- X < Y.
min(X,Y,X) :- X =< Y.
min(X,Y,Y) :- X > Y.
abs(X,Y) :- X < 0 ->  Y is -X; Y = X.

但我只想像这样输入输入:

ismaxgreater([1,2,-5,9])

输出应该是这样的:

Max is greater true

【问题讨论】:

    标签: prolog max min implementation absolute-value


    【解决方案1】:

    在这个解决方案中,我们找到最大值和最小值,并将 Max 与 Min 的绝对值进行比较。

    max([X], X) :- !, true.
    max([X|List], M):- max(List, M), M >= X.
    max([X|List], X):- max(List, M), X > M.
    
    min([X], X) :- !, true.
    min([X|List], M):- min(List, M), M <= X.
    min([X|List], X):- min(List, M), X > M.
    
    ismaxgreater(X) :- max(X, Max), min(X, Min), Max > abs(Min);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-19
      • 1970-01-01
      • 1970-01-01
      • 2022-07-23
      • 2012-06-29
      • 1970-01-01
      相关资源
      最近更新 更多