Skip to content

Instantly share code, notes, and snippets.

@prakashmurthy
Created September 28, 2010 00:32
Show Gist options
  • Save prakashmurthy/600173 to your computer and use it in GitHub Desktop.
Save prakashmurthy/600173 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# Solution for a Quick Ruby Kata by Noel Rappin -
# http://railsrx.com/2010/09/27/a-quick-ruby-kata/
# Modification of the Solution for Problem number 76 on Project Euler
# http://projecteuler.net/index.php?section=problems&id=76
class Array
def meets_criteria?
meets_criteria = false
count_hash = Hash.new(0)
self.each do |number|
count_hash[number] += 1
end
max_count = 0
count_hash.each do |key, value|
max_count = value if value > max_count
end
meets_criteria = true if max_count == 2
meets_criteria
end
end
start_time = Time.new
required_sum = 15
max_number = 9
combinations = [] # To find all combinations of 1-9 irrespective of the count that add up to 15
while max_number > 0
combination_array = []
divisor, remainder = required_sum.divmod(max_number)
divisor.times {combination_array << max_number}
if remainder > 0
combination_array << remainder
end
combinations << Array.new(combination_array)
while (max_number + combination_array.length - 1) < required_sum # When all items other than max_number are 1
total = 0
to_reduce = combination_array.pop
total += to_reduce
while to_reduce == 1
to_reduce = combination_array.pop
total += to_reduce
end
next_max_number = to_reduce -1
divisor, remainder = total.divmod(next_max_number)
divisor.times {combination_array << next_max_number}
if remainder > 0
combination_array << remainder
end
combination_array = combination_array.sort.reverse
combinations << Array.new(combination_array)
end
max_number -= 1
end
count = 1
combinations.each do |combination|
if combination.meets_criteria?
puts "Number #{count} : #{combination.join(', ')}"
count += 1
end
end
puts "\n\nTime spent is #{(Time.now - start_time) / 60 } minutes."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment