Skip to content

Instantly share code, notes, and snippets.

@braveulysses
Created November 11, 2010 19:54
Show Gist options
  • Save braveulysses/673072 to your computer and use it in GitHub Desktop.
Save braveulysses/673072 to your computer and use it in GitHub Desktop.
Kaprekar's routine. Undoubtedly not the best way to do it.
#!/usr/bin/env ruby
# See: http://en.wikipedia.org/wiki/Kaprekar_constant
$MAX_DIGITS = 4
$KAPREKARS_CONSTANT = 6174
class Fixnum
def sort(padding=0)
ordered = Array.new
self.to_s.each_char do |c|
ordered << c
end
if padding > 0
(padding - self.to_s.size).times do
ordered << '0'
end
end
ordered.sort
end
protected :sort
def sort_ascending(padding)
self.sort(padding).join.to_i
end
def sort_descending(padding)
self.sort(padding).reverse.join.to_i
end
def is_repdigits?
product_of_first = self.to_s.chars.next.to_i * $MAX_DIGITS
sum_of_all = 0
self.to_s.each_char do |c|
sum_of_all += c.to_i
end
product_of_first == sum_of_all
end
end
def kaprekar(number)
return number if number == $KAPREKARS_CONSTANT
asc = number.sort_ascending $MAX_DIGITS
desc = number.sort_descending $MAX_DIGITS
if asc > desc
greater = asc
lesser = desc
else
greater = desc
lesser = asc
end
result = greater - lesser
puts "#{greater.to_s} - #{lesser.to_s} = #{result.to_s}"
return kaprekar(result)
end
number = ARGV[0]
if number.size > $MAX_DIGITS or number.size < 1 or number.to_i == 0
puts "Number must be a nonzero four-digit number!"
exit
end
if number.to_i.is_repdigits?
puts "Number cannot be a repdigit, like 1111 or 3333."
exit
end
kaprekar number.to_i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment