Skip to content

Instantly share code, notes, and snippets.

Created Jul 11, 2014
What would you like to do?
Generate n unique random natural numbers whose sum is m
# Question source:
# 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment