Prolog 检查列表是否像 1,2,3,4,2,1 [英] Prolog check if the list is like 1,2,3,4,2,1

查看:66
本文介绍了Prolog 检查列表是否像 1,2,3,4,2,1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个程序来检查列表是否增加然后减少,就像下面的例子一样:

[1,2,3,4,5,6,4,3,2,1]

并且它必须至少增加或减少一步.

基本上:

  • 必须有一个升序序列,然后是一个降序序列.
  • 每个转换中的步骤必须至少为一个(不能并排使用相同的数字).
  • 这一步可以不止一个.

我想过在列表中找到最大的数字,然后将列表分成两个列表,然后检查它们是否都已排序.如何更轻松地完成?

解决方案

如果使用的所有数字都是整数,请考虑使用

<预>:- use_module(图书馆(clpfd)).

基于chain/2,我们可以这样定义up_down_zs/3:

<预>up_down_zs(Up, [P|Down], Zs) :-向上 = [_,_|_],向下 = [_|_],追加(向上、向下、Zs),追加(_,[P],向上),(向上,#<),链([P|Down], #>).

首先,有些情况我们预计会失败:

<预>?- 会员(Zs,[[1,1],[1,2,2,1],[1,2,3,4],[1,2,3,4,5,5,6,4,3,2,1]]),up_down_zs(_, _, Zs).错误的.

现在,让我们运行一些可满足的查询!

<预>?- up_down_zs(Up, Down, [1,2,3,4,5,6,4,3,2,1]).( 上 = [1,2,3,4,5,6], 下 = [6,4,3,2,1];错误的).?- up_down_zs(Up, Down, [1,2,3,1]).( 上 = [1,2,3], 下 = [3,1];错误的).?- up_down_zs(Up, Down, [1,2,1]).( 上 = [1,2], 下 = [2,1];错误的).

I need to create a program to check if a list increases then decreases, just like in the example below:

[1,2,3,4,5,6,4,3,2,1]

and it must be at least a one step increase or decrease.

Basically:

  • there must be a single ascending sequence followed by a single descending sequence.
  • the step in each transition must be at least one (no identical numbers side by side).
  • the step can be more than one.

I thought about finding the biggest number in the list and then splitting the list into two lists, then checking if they are both sorted. How can it be done easier?

解决方案

If all numbers used are integers, consider using !

:- use_module(library(clpfd)).

Based on chain/2, we can define up_down_zs/3 like this:

up_down_zs(Up, [P|Down], Zs) :-
   Up = [_,_|_],
   Down = [_|_],
   append(Up, Down, Zs),
   append(_, [P], Up),
   chain(Up, #<),
   chain([P|Down], #>).

First, some cases we all expect to fail:

?- member(Zs, [[1,1],[1,2,2,1],[1,2,3,4],[1,2,3,4,5,5,6,4,3,2,1]]),
   up_down_zs(_, _, Zs).
false.

Now, let's run some satisfiable queries!

?- up_down_zs(Up, Down, [1,2,3,4,5,6,4,3,2,1]).
(  Up = [1,2,3,4,5,6], Down = [6,4,3,2,1] 
;  false
).

?- up_down_zs(Up, Down, [1,2,3,1]).
(  Up = [1,2,3], Down = [3,1]
;  false
).

?- up_down_zs(Up, Down, [1,2,1]).
(  Up = [1,2], Down = [2,1]
;  false
).

这篇关于Prolog 检查列表是否像 1,2,3,4,2,1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆