找到第一个包含从 1 到 K 的所有数字的子列表 [英] Find first sublist that has all numbers from 1 to K

查看:29
本文介绍了找到第一个包含从 1 到 K 的所有数字的子列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到第一个包含从 1 到 K 的所有数字的子列表,并返回它及其长度.

I need to find the first sublist having all numbers from 1 to K and return it and its length.

抱歉编辑不当

所以我检查 1 到 K 是否在子列表中,如果不是,然后我从

So I check if 1 to K is in sublist if not then I delete the element (Hd) from

NumList ,将其附加到我们的 result(SubList) 并递归调用函数

NumList ,append it to our result(SubList) and recursively call the function

以尾部作为我们要检查的新列表.

with the tail as our new List to check.

findFirstSubListHavingAllColors( NumList, [Hd|Tl] ,SubList, X):-
   (   oneToKinSub(SubList,NumList)
   ->  length(SubList,X)
   ;   delete(NumList,Hd,NumList1),
       append(SubList,[Hd],SubList1),
       findFirstSubListHavingAllColors(NumList1,Tl,SubList1,_)
   ).

oneToKinSub(_,[]).
oneToKinSub(SubString,[Hd|Tl]) :-
   member(Hd,SubString),
   oneToKinSub(SubString,Tl).

<小时>

例如如果


For instance if

NumList =[1,2,3]

NumList =[1,2,3]

[Hd|Tl] =[1,3,1,3,1,3,3,2,2,1]

[Hd|Tl] =[1,3,1,3,1,3,3,2,2,1]

预期结果应该是 SubList=[1,3,1,3,1,3,3,2] 和 X=8

the expected result should be SubList=[1,3,1,3,1,3,3,2] and X= 8

推荐答案

您可以使用 append/3subtract/3 获取包含所有项目的第一个子列表:

You may use append/3 and subtract/3 to obtain the first sublist that contains all items:

findFirstSubListHavingAllColors( NumList, List ,SubList, Len):-
  once((
   append(SubList, _, List),        % get SubList
   subtract(NumList, SubList, []),  % test whether NumList is contained in SubList
   length(SubList, Len)
  )).

once/1 这里是为了避免在回溯时得到其他(错误的)解决方案.

once/1 here is to avoid getting other (wrong) solutions on backtracking.

这篇关于找到第一个包含从 1 到 K 的所有数字的子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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