Created
July 11, 2014 16:44
-
-
Save O-I/88214196ad03d687e8d1 to your computer and use it in GitHub Desktop.
Generate n unique random natural numbers whose sum is m
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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