序言:生成给定模式的列表的所有可能性 [英] Prolog: Generating Every Possibility of a List Given a Pattern

查看:84
本文介绍了序言:生成给定模式的列表的所有可能性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您在Prolog中有一个列表,例如:[3,4,2,2,1,4].如何生成从列表的第一个元素开始的所有可能模式的列表列表,然后转到i + 2th元素或i + 3rd元素,依此类推.

Let's say you have a list in Prolog such as: [3,4,2,2,1,4]. How would one go about generating a list of lists of all possible patterns that start at the first element of the list, then either go to the i + 2th element, or the i + 3rd element, and so on from there.

示例: 说我有[3,4,2,2,1,4,8]. 我希望能够生成一个列表列表,例如: [[3,2,1,8],[3,2,4],[3,2,8]]

Example: Say I have [3,4,2,2,1,4,8]. I want to be able to generate a list of lists such as: [[3,2,1,8], [3,2,4], [3,2,8]]

即每个其他元素或每个i + 3元素的所有可能性,或任何其他组合,例如i + 2,i + 3,i + 2,i + 2等.

I.e. all possibilities of either every other element or every i+3 element, or any other combination, such as i+2,i+3,i+2,i+2, etc.

我已经实现了自己的Powerset版本,但似乎无法弄清楚从哪里开始.

I've implemented my own version of a powerset, but I can't seem to figure out where to start.

推荐答案

gen([], []).
gen([A], [A]).
gen([A, _ | T], [A | Xs]) :- gen(T, Xs).
gen([A, _, _ | T], [A | Xs]) :- gen(T, Xs).

产生

?- gen([3,4,2,2,1,4,8], X).
X = [3, 2, 1, 8] ;
X = [3, 2, 1] ;
X = [3, 2, 4] ;
X = [3, 2, 4] ;
X = [3, 2, 8] ;
false.

您可以使用findall/3获取所有结果

You can use findall/3 to get all results

?- findall(X, gen([3,4,2,2,1,4,8], X), Z).
Z = [[3, 2, 1, 8], [3, 2, 1], [3, 2, 4], [3, 2, 4], [3, 2, 8]].

这篇关于序言:生成给定模式的列表的所有可能性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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