Cybernetic
Cybernetic

Reputation: 13354

find all possible sums in vector (R)

I have a vector of dollar values like this (vec):

[1]  460.08 3220.56 1506.20 1363.76 1838.00 1838.00 3684.94 2352.66 1606.02
[10] 1840.05  518.98 1603.53 1556.94  347.32  253.16   12.95 1828.81 1896.32
[19] 4962.60  426.33 3237.04 1601.40 2004.57  183.80 1570.75 3622.96  230.04
[28]  426.33 3237.04 1601.40 2004.57  183.80

If I have a charge that resulted from some sum of these numbers, how could I find it? For example, if the charge was 6747.81, then it must have resulted from 1506.20 + 3237.04 + 2004.57 (the 3rd, 29th and 31st vector elements). How could I solve for these vector elements given the sum?

I would imagine finding all possible sums is the answer then matching it to the vector elements that led to it.

I have played with using combn(vec, 3) to find all 3 but this doesn't quite quite give what I want.

Upvotes: 3

Views: 2380

Answers (1)

Dason
Dason

Reputation: 62003

You'll want to use colSums (or apply) after combn to get the sums.

set.seed(100)
# Generate fake data
vec <- rpois(10, 20)
# Get all combinations of 3 elements
combs <- combn(vec, 3)
# Find the resulting sums
out <- colSums(combs)
# Making up a value to search for
val <- vec[2]+vec[6]+vec[8]
# Find which combinations lead to that value
id <- which(out == val)
# Pull out those combinations
combs[,id]

Some output to show the results for this example

> vec
 [1] 17 12 23 20 21 17 21 18 22 22
> val
[1] 47
> combs[,id]
     [,1] [,2]
[1,]   17   12
[2,]   12   17
[3,]   18   18

Edit: Just saw that there isn't necessarily a restriction to use 3 items. One could generalize this just by doing it for every possible sample size but I don't have time to do that right now. It would also be fairly slow for even moderately sized problems.

Upvotes: 4

Related Questions