1

Is there a more efficient way to determine all possible values of 4 numbers that sum a particular value. I have used the following but if I expand it more then ten numbers per group or more then 4 groups it will be inefficient

Grid <- expand.grid(a=seq(0, 100, 10), b= seq(0,100,10), c= seq(0,100,10), d=seq(0,100,10))
Grid$total <- apply(Grid, 1, sum)
Grid[Grid$total==100,]

I my real application, the number will be percentages that will equal to 1 and will be adjusted by intervals of no less then 5

user273463
  • 23
  • 4
  • Have you looked into the [combinat](http://cran.r-project.org/web/packages/combinat/combinat.pdf) package? You could use the `combn` function to generate every combination of numbers (efficiently, I assume), and then subset the sums that match your criteria. – Alexey Shiklomanov Jun 18 '15 at 01:26

1 Answers1

3

I'm sure there are many solutions, here is one with partitions library,

library(partitions)
restrictedparts(10, 4, include.zero = FALSE)

# [1,] 7 6 5 4 5 4 3 4 3
# [2,] 1 2 3 4 2 3 3 2 3
# [3,] 1 1 1 1 2 2 3 2 2
# [4,] 1 1 1 1 1 1 1 2 2

This would be the 4 integers that sum to 10 (not including 0).

Rorschach
  • 31,301
  • 5
  • 78
  • 129