生成合计为目标值的组合


14

挑战

假设您有一个数字列表和一个目标值。查找所有数字组合的集合,这些组合的总和等于目标值,并将它们作为列表索引返回。

输入输出

输入将采用数字列表(不一定是唯一的)和目标求和数字。输出将是一组非空列表,每个列表包含对应于原始输入列表中值位置的整数值。

例子

Input: values = [1, 2, 1, 5], target = 8
Output: [ [0,1,3], [1,2,3] ]

Input: values = [4.8, 9.5, 2.7, 11.12, 10], target = 14.8
Output: [ [0,4] ]

Input: values = [7, 8, 9, -10, 20, 27], target = 17
Output: [ [1,2], [0,3,4], [3,5] ]

Input: values = [1, 2, 3], target = 7
Output: [ ]

计分

这是,因此最短的代码获胜!


6
相关,可能是骗子。
朱塞佩

我认为这是一个骗子,但我宁愿关闭旧的,因为它已经过时了。
发布Rock Garf Hunter,

4
浮点数真的增加了挑战吗?不确定共识是什么,但是它们可能会导致许多语言出现精度错误。
Arnauld

我打算允许使用浮点数,是的
soapergem

14
Bleh,索引?我认为返回值列表将是一个更好的挑战,尽管我猜想这引发了一个问题,即子集中重复值的处理方式。
xnor

Answers:


3

外壳,10字节

ηλfo=¹ṁ⁰tṖ

1个索引。在线尝试!

说明

ηλfo=¹ṁ⁰tṖ  Inputs are a number n (explicit, accessed with ¹) and a list x (implicit).
η           Act on the incides of x
 λ          using this function:
         Ṗ   Take all subsets,
        t    remove the first one (the empty subset),
  f          and keep those that satisfy this:
      ṁ⁰      The sum of the corresponding elements of x
   o=¹        equals n.

这使用了Husk的最新功能η(作用于索引)。这个想法是η采用一个高阶函数α(这里是内联lambda函数)和一个列表x,并调用α的索引函数x在上面的程序中)和的索引x。例如,ṁ⁰获取索引的子集,将索引映射到x它们之上,然后对结果求和。


9

JavaScript(ES6),96个字节

以currying语法接受输入(list)(target)

a=>s=>a.reduce((b,_,x)=>[...b,...b.map(y=>[...y,x])],[[]]).filter(b=>!b.reduce((p,i)=>p-a[i],s))

测试用例

如果由于IEEE 754精度错误而将4.8和10交换了,则在第二个测试用例上将失败,即- 14.8 - 4.8 - 10 == 0但是14.8 - 10 - 4.8 != 0。我认为这很好,尽管meta中可能有更相关的参考。

已评论

a => s =>                 // given an array a[] of length N and an integer s
  a.reduce((b, _, x) =>   // step #1: build the powerset of [0, 1, ..., N-1]
    [ ...b,               //   by repeatedly adding to the previous list b[]
      ...b                //   new arrays made of:
      .map(y =>           //     all previous entries stored in y[]
        [...y, x]         //     followed by the new index x
      )                   //   leading to:
    ],                    //   [[]] -> [[],[0]] -> [[],[0],[1],[0,1]] -> ...
    [[]]                  //   we start with a list containing an empty array
  )                       // end of reduce()
  .filter(b =>            // step #2: filter the powerset
    !b.reduce((p, i) =>   //   keeping only entries b
      p - a[i],           //     for which sum(a[i] for i in b)
      s                   //     is equal to s
    )                     //   end of reduce()
  )                       // end of filter()

7
不是一个而是两个reduce秒?我必须对此表示赞同。
尼尔

1
@Neil鲜为人知的“ reduceMapReduce”
Farquaad勋爵,18年


7

R85 84字节

function(l,k){N=combn
o={}
for(i in I<-1:sum(l|1))o=c(o,N(I,i,,F)[N(l,i,sum)==k])
o}

在线尝试!

1个索引。

combn通常返回matrix,但是设置simplify=F返回list,从而允许我们将c所有结果一起分类。combn(I,i,,F)返回所有索引组合,然后将其N(l,i,sum)==k作为该列表的索引来确定等于的索引k


7

J32 31字节

(=1#.t#])<@I.@#t=.1-[:i.&.#.1"0

在线尝试!

                  1-[:i.&.#.1"0         Make a list of all masks
                                        for the input list. We flip the bits
                                        to turn the unnecessary (0...0)         
                                        into (1...1) that would be missing.
                                        Define it as t.

(=1#.t#])                               Apply the masks, sum and
                                        compare with the target

         <@I.@#                         Turn the matching masks into 
                                        lists of indices

我觉得明确的定义可以帮助您完成所有构图,但不幸的是,我只有相同的长度:4 :'<@I.t#~x=1#.y#~t=.#:}.i.2^#y'在线尝试!
科尔

5

Japt,14个字节

m, à f_x!gU ¥V

在线测试!

怎么运行的

m, à f_x!gU ¥V   Implicit: U = input array, V = target sum
m,               Turn U into a range [0, 1, ..., U.length - 1].
   à             Generate all combinations of this range.
     f_          Filter to only the combinations where
       x           the sum of
        !gU        the items at these indices in U
            ¥V     equals the target sum.
                 Implicit: output result of last expression

不错的把戏m,。我有Êo à k@VnXx@gX相同的字节数。
粗野的





2

Python 3,144字节

lambda a,t:[[e for e,_ in x]for r in range(len(a))for x in combinations(list(enumerate(a)),r+1)if sum(y for _,y in x)==t]
from itertools import*

在线尝试!

0索引。44个字节用于返回索引,而不仅仅是元素本身。


2

Brachylog18 15字节

hiᶠ⊇Shᵐ+~t?∧Stᵐ

在线尝试!

-3个字节,因为它现在可以用作生成器(可能有可能打更多的高尔夫球,但是解决使用索引的需求很尴尬。)

    S              The variable S
   ⊇               is a sublist of
  ᶠ                the list of all
 i                 pairs [element, index] from
h                  the first element of
                   the input;
     hᵐ            the first elements of each pair
       +           add up to
        ~t         the last element of
          ?        the input
           ∧       which isn't necessarily
            S      S,
             tᵐ    from which the last elements of each pair
                   are output.

hiᶠ⊇z+ʰXh~t?∧Xt出来的长度一样。
不相关的字符串,

1

Perl 6,45个字节

->\a,\b{grep {a[$_].sum==b},^a .combinations}

测试一下

展开:

->
  \a, # input list
  \b, # input target
{

  grep

  {
      a[ $_ ].sum # use the list under test as indexes into 「a」
    ==
      b
  },

  ^a              # Range upto 「a」 (uses 「a」 as a number)
  .combinations   # get all of the combinations
}

1

APL(NARS),49个字符,98个字节

{∨/b←⍺=+/¨{∊⍵⊂w}¨n←{⍵⊤⍨k⍴2}¨⍳¯1+2*k←≢w←⍵:⍸¨b/n⋄⍬}

1分索引;测试:

  f←{∨/b←⍺=+/¨{∊⍵⊂w}¨n←{⍵⊤⍨k⍴2}¨⍳¯1+2*k←≢w←⍵:⍸¨b/n⋄⍬}
  ⎕fmt 8 f 1 2 1 5
┌2──────────────┐
│┌3────┐ ┌3────┐│
││2 3 4│ │1 2 4││
│└~────┘ └~────┘2
└∊──────────────┘
  ⎕fmt   14.8  f  4.8 9.5 2.7 11.12 10
┌1────┐
│┌2──┐│
││1 5││
│└~──┘2
└∊────┘
  ⎕fmt 17 f 7, 8, 9, ¯10, 20, 27
┌3──────────────────┐
│┌2──┐ ┌2──┐ ┌3────┐│
││4 6│ │2 3│ │1 4 5││
│└~──┘ └~──┘ └~────┘2
└∊──────────────────┘
  ⎕fmt 7 f 1 2 3
┌0┐
│0│
└~┘

评论:

{∨/b←⍺=+/¨{∊⍵⊂w}¨n←{⍵⊤⍨k⍴2}¨⍳¯1+2*k←≢w←⍵:⍸¨b/n⋄⍬}
                             ⍳¯1+2*k←≢w←⍵         copy ⍵ in w, len(⍵) in k, return 1..2^(k-1) 
                 n←{⍵⊤⍨k⍴2}¨                     traslate in binary each element of  1..2^(k-1) and assign the result to n
          {∊⍵⊂w}¨                                for each binary element of n return the elemets of ⍵ in the place where there are the 1s
    b←⍺=+/¨                                       sum them and see if the sum is ⍺, that binary array saved in b
  ∨/                                     :⍸¨b/n   if or/b, get all the elements of n that are 1s for array b, and calculate each all indexs
                                               ⋄⍬ else return Zilde as void set

0

Pyth,11个字节

fqvzs@LQTyU

在此处在线尝试,或在此处一次验证所有测试用例。

fqvzs@LQTyUQ   Implicit: Q=input 1 (list of numbers), z=input 2 (target value, as string)
               Trailing Q inferred
          UQ   Generate range [0-<length of Q>)
         y     Powerset of the above
f              Keep elements of the above, as T, when the following is truthy:
      L T        Map elements of T...
     @ Q         ... to the indicies in Q
    s            Take the sum
 q               Is the above equal to...
  vz             z as an integer
               Implicit print of the remaining results
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.