samedi 29 octobre 2016

Get set of random numbers from input List having fixed sum using C#

I am looking for a C# algorithm that would give me a set of random integers from input List, such that the sum of obtained random integers is N.

For example: If the list is {1,2,3,4,5,6...100} and N is 20, then the algorithm should return a set of random numbers like {5,6,9} or {9,11} or {1,2,3,4,10} etc.

Note that the count of integers in result set need not be fixed. Also, the input list can have duplicate integers. Performance is one of my priority as the input list can be large (around 1000 integers) and I need to randomize about 2-3 times in a single web request. I am flexible with not sticking to List as datatype if there is a performance issue with Lists.

I have tried below method which is very rudimentary and performance inefficient:

  1. Use the Random class to get a random index from the input list
  2. Get the integer from input list present at index obtained in #1. Lets call this integer X.
  3. Sum = Sum + X.
  4. Remove X from input list so that it does not get selected next.
  5. If Sum is less than required total N, add X to outputList and go back to #1.
  6. If the Sum is more than required total N, reinitialize everything and restart the process.
  7. If the Sum is equal to required total N, return outputList.



Aucun commentaire:

Enregistrer un commentaire