Let’s say I have a fixed sized array. I want to fill the array with either 1s or 2s so that all element sums up to X.
Example:
- Required sum = 12
- Array size = 7
Possible combinations:
array( 1, 2, 2, 2, 1, 2, 2 ) // sums to 12
array( 1, 1, 2, 2, 2, 2, 2 ) // sums to 12
Find the number of 2’s in the array, this number is:
Chose
randomarbitrary#2'selements (for example the first elements), andgive them the value 2, the rest of the elements will get the value 1.
Note: it is easy to see that if
X < array_sizeorX> 2*array_sizethere is no solution to the problem (and obviously the above algorithm will fail)