目標値に達する組み合わせを生成する


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
関連、おそらくpossibly。
ジュゼッペ

これはだましだと思いますが、古いので古いものを閉じたいと思います。
ポストロックガーフハンター

4
浮動小数点数は本当にチャレンジに何かを追加しますか?コンセンサスが何であるかはわかりませんが、おそらく多くの言語で精度エラーにつながります。
アーナウド

浮動小数点を許可するつもりだった、はい
soapergem

14
Bleh、インデックス?これは、値のリストを返すより良い挑戦になると思いますが、それはサブセットで繰り返し値がどのように扱われるかという疑問を引き起こすと思います。
xnor

回答:


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への最新の追加を使用ηします(インデックスに作用します)。アイデアは、それがあるη高次機能取りα(ここでインラインラムダ関数)とリストx、およびコールαの割り出し機能にxある(上記のプログラムで)とのインデックスをx。たとえばṁ⁰、インデックスのサブセットを取得し、インデックスをxそれらにマッピングし、結果を合計します。


9

JavaScript(ES6)、96バイト

カリー化構文の入力を受け取ります(list)(target)

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

テストケース

これは、4.8と10があるためIEEE 754精度誤差を入れ替えた場合の第二のテストケースに失敗するだろう-すなわち14.8 - 4.8 - 10 == 0けど14.8 - 10 - 4.8 != 0。メタのどこかにもっと関連する参照があるかもしれませんが、これは問題ないと思います。

コメント済み

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
1つではなく2つreduceですか?これに賛成しなければなりません。
ニール

1
@ニールあまり知られていない「reduceMapReduce」
ファークァードLord 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一緒にすべての結果をoncatenate。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同じバイト数でした。
シャギー



4

ゼリー、11バイト

ị³S=
JŒPçÐf

オンラインでお試しください!

1インデックス付き。要素自体ではなく、インデックスを返すために4バイトを費やしました。

user202729のおかげで
-1バイトジョナサンアランのおかげで-1バイト



@ user202729クール、ありがとう!
ハイパーニュートリノ

1
-1バイト:ではなくを使用する場合は不要です。çÇ
ジョナサンアラン

@JonathanAllanおめでとうございます!
ハイパーニュートリノ



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
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.