| Bytes | Lang | Time | Link |
|---|---|---|---|
| 007 | Nekomata | 240620T063759Z | alephalp |
| 098 | APLNARS | 190707T212101Z | user5898 |
| 015 | Brachylog | 190220T085355Z | Unrelate |
| 011 | Pyth | 190220T103543Z | Sok |
| 031 | J | 180115T035343Z | FrownyFr |
| 010 | Husk | 180115T101729Z | Zgarb |
| 096 | JavaScript ES6 | 180115T022750Z | Arnauld |
| 043 | Wolfram Language Mathematica | 180115T103513Z | alephalp |
| nan | 180115T235544Z | Brad Gil | |
| 084 | R | 180115T152049Z | Giuseppe |
| 011 | Jelly | 180115T022117Z | hyper-ne |
| 098 | Clean | 180115T044631Z | Οurous |
| 076 | Haskell | 180115T080610Z | Cristian |
| 110 | Python 2 | 180115T051456Z | Chas Bro |
| 014 | Japt | 180115T030101Z | ETHprodu |
| 144 | Python 3 | 180115T021429Z | hyper-ne |
Nekomata, 7 bytes
xSᵖ{@∑=
xSᵖ{@∑=
S Find a subset of
x [0, 1, ..., len(first input) - 1]
ᵖ{ such that
∑ the sum of
@ the corresponding elements of the first input
= equals the second input
By default, Nekomata prints all possible solutions.
APL(NARS), 49 chars, 98 bytes
{∨/b←⍺=+/¨{∊⍵⊂w}¨n←{⍵⊤⍨k⍴2}¨⍳¯1+2*k←≢w←⍵:⍸¨b/n⋄⍬}
1-indexed; 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│
└~┘
comment:
{∨/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
Brachylog, 18 15 bytes
hiᶠ⊇Shᵐ+~t?∧Stᵐ
-3 bytes because it now works as a generator. (It's probably possible to golf more, but working around the need to use indices is awkward.)
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.
Pyth, 11 bytes
fqvzs@LQTyU
Try it online here, or verify all the test cases at once here.
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
J, 32 31 bytes
(=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
Husk, 10 bytes
ηλfo=¹ṁ⁰tṖ
1-indexed. Try it online!
Explanation
ηλ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.
This uses the latest addition to Husk, η (act on indices).
The idea is that η takes a higher order function α (here the inline lambda function) and a list x, and calls α on the indexing function of x (which is ⁰ in the above program) and the indices of x.
For example, ṁ⁰ takes a subset of indices, maps indexing to x over them and sums the results.
JavaScript (ES6), 96 bytes
Takes input in currying syntax (list)(target).
a=>s=>a.reduce((b,_,x)=>[...b,...b.map(y=>[...y,x])],[[]]).filter(b=>!b.reduce((p,i)=>p-a[i],s))
Test cases
This would fail on the 2nd test case if 4.8 and 10 were swapped because of an IEEE 754 precision error -- i.e. 14.8 - 4.8 - 10 == 0 but 14.8 - 10 - 4.8 != 0. I think this is fine, although there may be a more relevant reference somewhere in meta.
let f =
a=>s=>a.reduce((b,_,x)=>[...b,...b.map(y=>[...y,x])],[[]]).filter(b=>!b.reduce((p,i)=>p-a[i],s))
console.log(JSON.stringify(f([1, 2, 1, 5])(8)))
console.log(JSON.stringify(f([4.8, 9.5, 2.7, 11.12, 10])(14.8)))
console.log(JSON.stringify(f([7, 8, 9, -10, 20, 27])(17)))
console.log(JSON.stringify(f([1, 2, 3])(7)))
Commented
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()
Perl 6, 45 bytes
->\a,\b{grep {a[$_].sum==b},^a .combinations}
Expanded:
->
\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
}
R, 85 84 bytes
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-indexed.
combn usually returns a matrix, but setting simplify=F returns a list instead, allowing us to concatenate all the results together. combn(I,i,,F) returns all combinations of indices, and we take N(l,i,sum)==k as an index into that list to determine those which equal k.
Jelly, 11 bytes
ị³S=
JŒPçÐf
1-indexed. 4 bytes spent on returning indices rather than just the elements themselves.
-1 byte thanks to user202729
-1 byte thanks to Jonathan Allan
Clean, 104 102 98 bytes
import StdEnv
@n=[[]:[[i:b]\\i<-[0..n-1],b<- @i]]
?l n=[e\\e<-tl(@(length l))|sum(map((!!)l)e)==n]
Haskell, 76 bytes
x#t=[i|i<-tail$concat<$>mapM(\z->[[],[z]])[0..length x-1],t==sum[x!!k|k<-i]]
Python 2, 110 bytes
lambda a,n:[b for b in[[i for i in range(len(a))if j&1<<i]for j in range(2**len(a))]if sum(a[c]for c in b)==n]
Japt, 14 bytes
m, à f_x!gU ¥V
How it works
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
Python 3, 144 bytes
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-indexed. 44 bytes spent on returning indices rather than just the elements themselves.