Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Adding "Ugly Numbers" solution (not yet complete)

  • Loading branch information...
commit ca4ae1bd40292eb95c70d202104c83277865b35e 1 parent 3171ad5
@rxaviers authored
View
66 open_challenges/hard/ugly_numbers.rb
@@ -0,0 +1,66 @@
+#! /usr/bin/env ruby
+# CodeEval - Hard) Ugly Numbers
+# http://www.codeeval.com/open_challenges/42/
+# author: Rafael Xavier <rxaviers at gmail.com>
+# FAILs due to performance: time exceeds 5s limit
+
+DEBUG = false
+
+class Test
+ def initialize(line)
+ @n = line.strip
+ end
+
+ def run
+ c = 0
+ @n.amusing_expressions {|exp|
+ evaled_exp = eval(exp.without_octals)
+ puts "#{exp} = #{evaled_exp} #{evaled_exp.ugly_number? ? "ugly" : ""}" if DEBUG
+ c += 1 if evaled_exp.ugly_number?
+ }
+ puts c
+ end
+end
+
+class Integer
+ def ugly_number?
+ return true if self == 0
+ [2, 3, 5, 7].map {|d| self % d}.include?(0)
+ end
+end
+
+class String
+ def amusing_expressions(head = "", &block)
+ arrayed = chars.to_a
+ if arrayed.length == 1
+ yield self.to_s
+ elsif arrayed.length == 2
+ arrayed.amusing_expressions.each {|exp|
+ yield head + exp
+ }
+ else
+ [arrayed[0], ""].amusing_expressions.each {|exp|
+ new_number = arrayed[1..-1].join('')
+ new_number.amusing_expressions(head + exp, &block)
+ }
+ end
+ nil
+ end
+
+ def without_octals
+ gsub(/^0+([^0]+)/, '\1').gsub(/([+-])0+([^0]+)/, '\1\2')
+ end
+end
+
+class Array
+ def amusing_expressions
+ raise "ops" if length != 2
+ ["", "+", "-"].map {|op| "#{self[0]}#{op}#{self[1]}"}
+ end
+end
+
+
+File.open(ARGV[0]).each_line do |line|
+ t = Test.new(line)
+ t.run
+end
View
28 open_challenges/hard/ugly_numbers.testcases
@@ -0,0 +1,28 @@
+0
+1
+9
+13
+011
+277
+413
+0876
+7192
+7329
+8126
+9893
+12345
+17214
+20204
+160176
+1566843
+9716463
+54275347
+84091195
+91920744
+216589640
+845048810
+3747766429
+4802642960
+8224853717
+9712606483
+0000000000277
Please sign in to comment.
Something went wrong with that request. Please try again.