Skip to content

Instantly share code, notes, and snippets.

@parabuzzle
Created March 21, 2015 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parabuzzle/c63585ce4255f12871c6 to your computer and use it in GitHub Desktop.
Save parabuzzle/c63585ce4255f12871c6 to your computer and use it in GitHub Desktop.
Mensa number question
#!/usr/bin/env ruby
# Find a SIX digit number in which the FIRST digit is ONE more than the THIRD,
# the SECOND digit is ONE less than the FOURTH, the FIFTH digit is ONE less than
# the THIRD, and the SIXTH digit is ONE more than the FOURTH. The sum of the
# SECOND and THIRD digits equal the FIRST. The sum of all digits is 30.
# Returns 6 digit numbers that the sum of the digits are 30
def possible_numbers
numbers = []
num = 0
while num <= 999999 do
numbers << "%06d" % num if num.to_s.each_char.map {|c| c.to_i }.reduce(:+) == 30
num += 1
end
return numbers
end
# Filter number_array to only return numbers that digit in position_one == digit in position_two op 1
def filter_numbers(position_one, position_two, op, number_array)
number_array.each_with_object([]) do |number, numbers|
numbers << number if number.chars[position_one-1].to_i == number.chars[position_two-1].to_i.send(op, 1)
end
end
# Filter number_array to only return numbers that digit 2 and digit 3 add up to digit 1
def the_sum_of_second_and_third_is_the_first(number_array)
number_array.each_with_object([]) do |number, numbers|
numbers << number if (number.chars[1].to_i + number.chars[2].to_i) == number.chars[0].to_i
end
end
# you could futher simplify this by chaining everything (but its kinda hard to read)
puts(
the_sum_of_second_and_third_is_the_first(
filter_numbers( 6, 4, "+",
filter_numbers( 2, 4, "-",
filter_numbers( 5, 3, "-",
filter_numbers( 1, 3, "+",
possible_numbers
)
)
)
)
)
)
@parabuzzle
Copy link
Author

Should have called the filter_numbers method enhance

enhance

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment