Genera combinazioni che si sommano a un valore target


14

Sfida

Supponiamo di avere un elenco di numeri e un valore target. Trova l'insieme di tutte le combinazioni dei tuoi numeri che si sommano al valore target, restituendole come indici di elenco.

Ingresso e uscita

L'input prenderà un elenco di numeri (non necessariamente univoci) e un numero di sommatoria target. L'output sarà un insieme di elenchi non vuoti, ogni elenco contenente valori interi corrispondenti alla posizione dei valori nell'elenco di input originale.

Esempi

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: [ ]

punteggio

Questo è , quindi vince il codice più corto!


6
Correlato , forse un duplicato.
— Giuseppe,

Penso che questo sia un duplicato, ma preferirei chiudere quello più vecchio perché è obsoleto.
— Post Rock Garf Hunter,

4
I numeri in virgola mobile aggiungono davvero qualcosa alla sfida? Non sono sicuro di quale sia il consenso, ma probabilmente porteranno a errori di precisione in molte lingue.
— Arnauld,

Avevo intenzione di consentire punti fluttuanti, sì
— soapergem,

14
Bleh, indici? Penso che questa sarebbe una sfida più bella restituire un elenco di valori, anche se immagino che sollevi una domanda su come i valori ripetuti vengono trattati nei sottoinsiemi.
— xnor

Risposte:


3

Buccia , 10 byte

ηλfo=¹ṁ⁰tṖ

1-indicizzati. Provalo online!

Spiegazione

ηλ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.

Questo utilizza l'ultima aggiunta a Husk, η(agire sugli indici). L'idea è che ηprende una funzione di ordine superiore α(qui la funzione lambda inline) e un elenco x, e chiama αla funzione di indicizzazione di x(che è ⁰nel programma sopra) e gli indici di x. Ad esempio, ṁ⁰prende un sottoinsieme di indici, mappa l'indicizzazione xsu di essi e somma i risultati.


9

JavaScript (ES6), 96 byte

Accetta input nella sintassi del curry (list)(target).

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

Casi test

Ciò fallirebbe nel secondo caso di test se 4.8 e 10 fossero scambiati a causa di un errore di precisione IEEE 754, ovvero 14.8 - 4.8 - 10 == 0ma 14.8 - 10 - 4.8 != 0. Penso che questo vada bene , anche se potrebbe esserci un riferimento più rilevante da qualche parte nella meta.

Commentate

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
Non uno ma due reduces? Devo votare questo.
— Neil,

1
@Neil Il meno noto "reduceMapReduce"
— Lord Farquaad,


7

R , 85 84 byte

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}

Provalo online!

1-indicizzati.

combndi solito restituisce a matrix, ma l'impostazione simplify=Frestituisce a listinvece, permettendoci di concatenare tutti i risultati insieme. combn(I,i,,F)restituisce tutte le combinazioni di indici e prendiamo N(l,i,sum)==kcome indice in tale elenco per determinare quelli uguali k.


7

J , 32 31 byte

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

Provalo online!

                  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

Mi sento come una definizione esplicita aiuterebbe dato tutte le composizioni, ma purtroppo ho avuto solo la stessa lunghezza: 4 :'<@I.t#~x=1#.y#~t=.#:}.i.2^#y'. Provalo online!
— Cole

5

Japt , 14 byte

m, à f_x!gU ¥V

Provalo online!

Come funziona

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

Bel trucco con m,. Ho avuto Êo à k@VnXx@gXper lo stesso numero di byte.
— Shaggy,





2

Python 3 , 144 byte

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*

Provalo online!

0-indicizzati. 44 byte spesi per restituire indici piuttosto che solo gli elementi stessi.


2

Brachylog , 18 15 byte

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

Provalo online!

-3 byte perché ora funziona come generatore . (Probabilmente è possibile giocare a golf di più, ma aggirare la necessità di utilizzare gli indici è scomodo.)

    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?∧Xtesce alla stessa lunghezza.
— Corda non correlata

1

Perl 6 , 45 byte

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

Provalo

Allargato:

->
  \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 caratteri, 98 byte

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

1-indicizzati; test:

  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│
└~┘

commento:

{∨/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 byte

fqvzs@LQTyU

Provalo online qui o verifica tutti i casi di test contemporaneamente qui .

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
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.