Reputation: 2415
I know how to generate a random number within a range in ruby:
rand(10..45)
but how to generate a number form a given number?
example:
def generate_random_number(n)
#what to put here
end
if I run:
generate_random_number(123)
it will return an array of possible generated number from given number:
[123, 321, 231, 132 etc ...]
is there any ruby function to solve this?
Upvotes: 0
Views: 113
Reputation: 122363
What you are looking for is permutation
:
123.to_s.chars.permutation.map {|a| a.join.to_i}
# => [123, 132, 213, 231, 312, 321]
If you want the order to be random, shuffle
it:
123.to_s.chars.permutation.map {|a| a.join.to_i}.shuffle
# => [312, 123, 213, 132, 231, 321]
Upvotes: 3