Skip to content

Instantly share code, notes, and snippets.

@O-I
Created July 11, 2014 16:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save O-I/88214196ad03d687e8d1 to your computer and use it in GitHub Desktop.
Save O-I/88214196ad03d687e8d1 to your computer and use it in GitHub Desktop.
Generate n unique random natural numbers whose sum is m
# Question source: http://codegolf.stackexchange.com/q/8574/12268
# Write an algorithm in any programming language you desire
# that generates n unique randomly-distributed random natural
# numbers (i.e. positive integers, no zero), sum of which is
# equal to t, where t is bigger than or equal to n*(n+1)/2.
# Example: Generate 10 unique random natural numbers, sum of which is equal to 500.
def rand_sum(size, sum)
rand_set = []
rand_set |= [rand(1...sum)] until rand_set.size == size - 1
rand_set << 0 << sum
rand_set = rand_set.sort.each_cons(2).map { |x, y| y - x }.uniq
rand_set.size == size ? rand_set : rand_sum(size, sum)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment