Created
October 1, 2014 18:16
-
-
Save gertig/1e5be0fc9c34a0690b99 to your computer and use it in GitHub Desktop.
Ugly Numbers Challenge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Numeric | |
def ugly? | |
self == 0 || self % 2 == 0 || self % 3 == 0 || self % 5 == 0 || self % 7 == 0 | |
end | |
end | |
# lines.each do |line| | |
orig_arr = line.strip.split(//) | |
line_arr = line.strip.gsub(/(0+)/, "0").split(//) # replace multiple zeros with one (for speed) | |
missing_zeros = orig_arr.length - line_arr.length | |
# perm_count = 3**(line_arr.length - 1) | |
# All permutations of operators | |
ops = [] | |
["","-","+"].repeated_permutation(line_arr.length - 1) { |p| ops << p } | |
numbers = [] | |
ops.each do |op_arr| | |
# zip interleaves into multiple arrays then flatten and join into a sinle line again | |
l = line_arr.zip(op_arr).flatten.join | |
if l == "0" | |
new_line = "0" | |
else | |
# Remove all leading zeros, remove all zeros that follow a + or a - and remove any trailing + or - | |
new_line = l.gsub(/\A(0+)/, "").gsub(/\+(0+)/, "+").gsub(/\-(0+)/, "-").gsub(/(\-\z)|(\+\z)/, "") | |
end | |
numbers << eval(new_line) | |
end | |
# Count the uglies | |
ugly_count = 0 | |
numbers.each do |n| | |
ugly_count +=1 if n.ugly? | |
end | |
puts "#{line}-#{ugly_count}" | |
puts ugly_count * 3**missing_zeros | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment