Skip to content

Instantly share code, notes, and snippets.

@CAYdenberg
Last active November 23, 2015 23:22
Show Gist options
  • Save CAYdenberg/c797de4e5a165c51b0e6 to your computer and use it in GitHub Desktop.
Save CAYdenberg/c797de4e5a165c51b0e6 to your computer and use it in GitHub Desktop.
General solution to the Number Shuffle problem
# from https://rubymonk.com/learning/books/1-ruby-primer/problems/154-permutations
# Problem statement: Given a 3 or 4 digit number with distinct digits, return a sorted array of all the unique numbers that can be formed with those digits.
# This solution will work for any number (within limits of memory and stack depth)
def number_shuffle(number)
digits = number.to_s.split('')
if digits.length == 1
return [number]
end
combinations = []
digits.each do |digit|
remaining = digits.select { |d| d != digit }.join
if remaining.length != 0
sub_combinations = number_shuffle(remaining.to_i)
sub_combinations.each do |sub_combination|
combination = (digit.to_s + sub_combination.to_s).to_i
combinations = combinations.push(combination)
end
end
end
return combinations
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment