我的数组应该等于这个,但事实并非如此! [英]My array should equal this, but it doesn't!

Given an array of integers a which contains n integers, and a single integer x; remove the fewest amount of elements from a to make the sum of a equal to x. If no combinations of a can form x, return a falsy value.

给定一个整数数组,其中包含n个整数和一个整数x;从a中移除最少量的元素以使a等于x的总和。如果没有a的组合可以形成x,则返回一个假值。

As pointed out in a comment this is the maximum set with a sum of x, excuse my lesser math brain. I forgot a lot of terms since college.

正如评论中指出的那样,这是x的总和的最大值,请原谅我较小的数学大脑。自大学以来我忘记了很多条款。


Examples (Truthy):

f([1,2,3,4,5,6,7,8,9,10], 10) = [1,2,3,4]

f([1,2,3,4,5,6,7,8,9,10],10)= [1,2,3,4]

f([2,2,2,2,2,2,2,2,2], 10) = [2,2,2,2,2]

f([2,2,2,2,2,2,2,2,2],10)= [2,2,2,2,2]

f([2,2,2,2,-2,-2,-2,-4,-2], -8) = [2,2,-2,-2,-2,-4,-2]

f([2,2,2,2,-2,-2,-2,-4,-2], - 8)= [2,2,-2,-2,-2,-4,-2 ]

f([-2,-4,-2], -6) = [-4,-2] OR [-2,-4]

f([ - 2,-4,-2],-6)= [-4,-2] OR [-2,-4]

f([2,2,2,4,2,-2,-2,-2,-4,-2], 0) = [2,2,2,4,2,-2,-2,-2,-4,-2] (Unchanged)

f([2,2,2,4,2,-2,-2,-2,-4,-2],0)= [2,2,2,4,2,-2,-2, - 2,-4,-2](不变)

f([], 0) = [] (Unchanged Zero-sum Case)

f([],0)= [](零和案例不变)


Examples (Falsy, any consistent non-array value):

示例(Falsy,任何一致的非数组值):

Impossible to Make Case: f([-2,4,6,-8], 3) = falsy (E.G. -1)

不可能做出案例:f([ - 2,4,6,-8],3)= falsy(E.G. -1)

Zero Sum Case: f([], non-zero number) = falsy (E.G. -1)

零和案例:f([],非零数字)= falsy(E.G。-1)

注意:任何像[-1]这样的值都不能对falsy有效,因为它是一个潜在的truthy输出。

  • Note: any value like [-1] cannot be valid for falsy, as it is a potential truthy output.

Rules:

输入可以采用数组形式,也可以作为参数列表,最后一个或第一个是x。

输出可以是任何分隔的整数列表。例如。 1 \ n2 \ n3 \ n或[1,2,3]。

任何值都可以用作虚假指示符,而不是整数数组。

您的代码必须最大化结束数组的大小,顺序无关紧要。例如。对于f([3,2,3],5),[2,3]和[3,2]都同样有效。例如。对于f([1,1,2],2),只能返回[1,1],因为[2]更短。

a的总和和x的值都将小于2 ^ 32-1且大于-2 ^ 32-1。

这是代码高尔夫,最低字节数的胜利。

如果有多个相同大小的子阵列是有效的,则输出所有子阵列是不可接受的。您必须选择一个并输出一个。

  • Input may be taken in array form, or as a list of arguments, the last or first being x.
  • Output may be any delimited list of integers. E.G. 1\n2\n3\n or [1,2,3].
  • Any value can be used as a falsy indicator, other than an array of integers.
  • Your code must maximize the size of the end array, order does not matter.

    例如。对于f([3,2,3],5),[2,3]和[3,2]都同样有效。

    例如。对于f([1,1,2],2),只能返回[1,1],因为[2]更短。

    • E.G. For f([3,2,3],5) both [2,3] and [3,2] are equally valid.
    • E.G. For f([1,1,2],2) you can only return [1,1] as [2] is shorter.
  • Both the sum of a and the value of x will be less than 2^32-1 and greater than -2^32-1.
  • This is code-golf, lowest byte-count wins.
  • If there are multiple subarrays of the same size that are valid, it is not acceptable to output all of them. You must choose a single one and output that one.

Let me know if this has been posted, I couldn't find it.

如果已发布,请告诉我,我找不到它。

Posts I found like thisRelated but closed, ...

帖子我发现这样:相关但关闭,......

13 个解决方案

#1


5  

Python 2108 104 bytes

lambda a,n:[x for l in range(len(a)+1)for x in combinations(a,l)if sum(x)==n][-1]
from itertools import*

Try it online!

在线尝试!

-4 bytes, thanks to Jonathan Allan

-4个字节,感谢Jonathan Allan


Python 2108 106 bytes

def f(a,n):
 q=[a]
 while q:
  x=q.pop(0);q+=[x[:i]+x[i+1:]for i in range(len(x))]
  if sum(x)==n:return x

Try it online!

在线尝试!

-2 bytes, thanks to Janathan Frech

2个字节,感谢Janathan Frech

#2


4  

Brachylog, 8 bytes

h⊇.+~t?∧

Try it online!

在线尝试!

Monthly Brachylog answer. Returns false. if it is not possible.

每月Brachylog回答。返回false。如果不可能的话。

Explanation

h⊇.           The output is a subset of the head of the input
  .+~t?       The sum of the elements of the output must equal the tail of the input
       ∧      (Avoid implicit unification between the output and the input)

#3


4  

05AB1E, 9 bytes

æʒOQ}0ªéθ

Try it online!

在线尝试!

#4


4  

Japt -h, 11 bytes

à f_x ¥VÃñl

Try it online!

在线尝试!

#5


3  

Pyth, 8 bytes

  • 8-byter (Try it!) – Outputs only one possible solution. For unsolvable inputs, it doesn't print anything to STDOUT, which is an empty string, which is technically speaking falsey in Pyth, but writes to STDERR. Thanks to FryAmTheEggman for suggesting this (ignoring STDERR and focusing on the STDOUT output only), thus saving 1 byte.

    8-byter(试一试!) - 仅输出一种可能的解决方案。对于不可解析的输入,它不会向STDOUT打印任何内容,这是一个空字符串,在技术上讲在Pyth中是假的,但写入STDERR。感谢FryAmTheEggman建议这一点(忽略STDERR并仅关注STDOUT输出),从而节省1个字节。

    efqz`sTy    
    
  • 9-byter (Try it!) – Outputs only one possible solution, wrapped in a singleton list as allowed by default (e.g. ([1...10], 10) -> [[1,2,3,4]]; ([], 0) -> [[]]). For unsolvable inputs, it returns [], which is falsey in Pyth.

    9-byter(试一试!) - 输出一个可能的解决方案,默认情况下包含在单个列表中(例如([1 ... 10],10) - > [[1,2,3,4]] ;([],0) - > [[]])。对于无法解析的输入,它返回[],这在Pyth中是假的。

    >1fqz`sTy
    
  • 10-byter (Try it!) – For a clearer output, without using the singleton-list rule and using 0 rather than [] as a falsy value.

    10-byter(试一试!) - 为了更清晰的输出,不使用单例列表规则并使用0而不是[]作为假值。

    e+0fqz`sTy
    

Explanation

First, the code computes the powerset of the input list (all possible ordered sub-collections thereof). Then, it only keeps those collections whose sum is equal to the input number. It should be noted that the collections are generated from the shortest to the longest, so we focus on the last one. To obtain it:

首先,代码计算输入列表的powerset(其所有可能的有序子集合)。然后,它只保留那些总和等于输入数的集合。应该注意的是,集合是从最短到最长生成的,所以我们关注最后一个。获得它:

8-byter只使用内置的end,它会抛出一个错误,但是根据我们的站点规则可以忽略STDERR,STDOUT的输出是一个空字符串,这是假的。

9-byter采用最后一个元素,但使用等效的Python代码lst [-1:]代替lst [-1],以避免因无法解析的输入而抛出错误。

10-byter将0添加到已过滤的子集合列表中,然后获取该集合的结尾(最后一个元素)。如果输入不可解,则自然会使用0代替。

  • The 8-byter simply uses the end built-in, which throws an error, but STDERR can be ignored as per our site rules, the output to STDOUT being an empty string, which is falsy.
  • The 9-byter takes the last element, but using the equivalent Python code lst[-1:] in place of lst[-1] to avoid errors from being thrown for unsolvable inputs.
  • The 10-byter prepends a 0 to the list of filtered sub-collections, then takes the end of that collection (last element). If the inputs aren't solvable, then 0 is naturally used instead.

#6


2  

Pyth, 14 bytes

A.Q|>1fqsTHyG0

Try it online!

在线尝试!

#7


2  

This started out cool and small, but edge cases got me. Whatever happens, I'm proud of the work I put into this.

这开始很酷,很小,但边缘案件得到了我。无论发生什么,我都为自己的工作感到自豪。

Python 3169 161 154 bytes

from itertools import*
def f(a,x):
	if sum(a)==x:return a
	try:return[c for i in range(len(a))for c in combinations(a,i)if sum(c)==x][-1]
	except:return 0

Try it online!

在线尝试!

#8


1  

Jelly, 7 bytes

ŒPS⁼¥ƇṪ

Try it online!

在线尝试!

Output clarified over TIO.

通过TIO澄清产出。

#9


1  

R, 100 bytes

function(a,x){for(i in sum(a|1):0)if(x%in%(y<-colSums(K<-combn(a,i))))return(K[,y==x,drop=F][,1])
F}

Try it online!

在线尝试!

Returns FALSE for impossible criteria.

对于不可能的标准,返回FALSE。

#10


1  

Clean, 89 bytes

import StdEnv,Data.List,Data.Func
$n=find((==)n o sum)o sortBy(on(>)length)o subsequences

Try it online!

在线尝试!

Defines the function $ :: Int -> [Int] -> (Maybe [Int]) returning Nothing if there is no appropriate combination of elements, and (Just [elements...]) otherwise.

定义函数$ :: Int - > [Int] - >(Maybe [Int])如果没有适当的元素组合则返回Nothing,否则返回(Just [elements ...])。

#11


1  

Attache, 28 bytes

${(y&`=@Sum\Radiations@x)@0}

Try it online!

在线尝试!

Alternatives

34 bytesf[x,y]:=({y=Sum@_}\Radiations@x)@0

34个字节:f [x,y]:=({y = Sum @_} \ Radiations @ x)@ 0

30 bytesFirst@${y&`=@Sum\Radiations@x}

30个字节:首先@ $ {y&`= @ Sum \ Radiations @ x}

29 bytes{(_&`=@Sum\_2)@0}#/Radiations

29个字节:{(_&`= @ Sum \ _2)@ 0}#/辐射

29 bytes${({y=Sum@_}\Radiations@x)@0}

29个字节:$ {({y = Sum @_} \ Radiations @ x)@ 0}

29 bytes`@&0@${y&`=@Sum\Radiations@x}

29个字节:`@&0 @ $ {y&`= @ Sum \ Radiations @ x}

29 bytes{_}@@${y&`=@Sum\Radiations@x}

29个字节:{_} @@ $ {y&`= @ Sum \ Radiations @ x}

Explanation

${(y&`=@Sum\Radiations@x)@0}
${                         }    function receiving two arguments, x and y
            Radiations@x        calculate the radiations of x
                                (simulates removing all possible subslices of x)
           \                    keep those radiations
        Sum                     ...whose sum...
     `=@                        ...equals...
   y&                           ...y
  (                     )@0     select the first one (always the longest)

#12


1  

JavaScript (ES6), 108 bytes

Takes input as (array)(n). Returns either an array or false.

输入为(数组)(n)。返回数组或false。

a=>n=>a.reduce((a,x)=>[...a,...a.map(y=>1/r[(y=[...y]).push(x)]||eval(y.join`+`)-n?y:r=y)],[[]],r=!n&&[])&&r

Try it online!

在线尝试!

#13


1  

Perl 6, 38 bytes

{;*.combinations.grep(*.sum==$_).tail}

Try it online!

在线尝试!

Curried function.

 

本文转载自

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值