#!/usr/bin/env ruby
# Solution to Project Euler problem 62
# Author: David J. Oftedal.
class Integer
# Sort the digits. Reverse the sort to allow for a leading 0.
def sort_digits
to_s.chars.sort.reverse.join.to_i
end
end
# Store all the permutations of cubes which are also cubes.
cubes = Hash.new{|cubes, cube| cubes[cube] = []}
# Find the lowest cube which has five permutations that are also cubes.
i = 1
loop do
cube = i**3
# Record this cube as a permutation of any cube which has these digits.
cubes[cube.sort_digits] << cube
i += 1
# When moving on to cubes with more digits:
if (i**3).to_s.length > cube.to_s.length
# Find all the cubes with five permutations that are also cubes
found = cubes.select{|key, value| value.length == 5}
if found.length > 0
# Upon finding one, return the lowest one and exit.
found = found.values if found.class == Hash
puts "The cube #{found.flatten.sort[0]} is the smallest cube that can be permuted to produce four other cubes."
exit
end
end
end