Choose $n$ elements from a set where their summand equals $S$

31 Views Asked by At

Given a set size $n$ consisting of elements from $1->n$, choose $k$ elements from the set such that their summand equals $S$.

For ex: $n = 5 = \{1,2,3,4,5\}$ , $k = 3$ and $S=9$ then elements chosen are $1,3$ and $5$

So is there a general formula or a general approach on how to choose such elements? because n and k can be really large.

You can give me the gist or go ahead.

1

There are 1 best solutions below

5
On BEST ANSWER

An hacky solution:

f[n_, k_, m_] := 
 Block[{down = Floor[m/k - (k - 1)/2], up = Floor[m/k + (k - 1)/2]}, 
  Range[down, up] + UnitStep[Range[-k, -1] + (m - (down + up)*k/2)]]

f[7, 3, 11]

{2,4,5}

for bigger lists:

f[70, 30, 700]

{8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38}