Skip to content

Instantly share code, notes, and snippets.

@O-I
Created Jul 11, 2014
Embed
What would you like to do?
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