Done puzzle 45
[project-euler.git] / euler17.rb
1 require 'logger'
2 log = Logger.new(STDERR)
3 log.level = Logger::WARN
4
5 $words = {1 => 'one',
6 2 => 'two',
7 3 => 'three',
8 4 => 'four',
9 5 => 'five',
10 6 => 'six',
11 7 => 'seven',
12 8 => 'eight',
13 9 => 'nine',
14 10 => 'ten',
15 11 => 'eleven',
16 12 => 'twelve',
17 13 => 'thirteen',
18 14 => 'fourteen',
19 15 => 'fifteen',
20 16 => 'sixteen',
21 17 => 'seventeen',
22 18 => 'eighteen',
23 19 => 'nineteen',
24 20 => 'twenty',
25 30 => 'thirty',
26 40 => 'forty',
27 50 => 'fifty',
28 60 => 'sixty',
29 70 => 'seventy',
30 80 => 'eighty',
31 90 => 'ninety',
32 100 => 'hundred',
33 1000 => 'thousand'}
34
35 def words_of_number(n)
36 case n
37 when (1..20)
38 [$words[n]]
39 when (21..99)
40 [$words[n.div(10) * 10], $words[n % 10]]
41 when (100..999)
42 [$words[n.div(100)], 'hundred'] + (n % 100 == 0 ? [] : ['and'] + words_of_number(n % 100))
43 when 1000
44 ['one', 'thousand']
45 end
46 end
47
48 if __FILE__==$0
49 words = []
50 1.upto(1000) do |i|
51 words += words_of_number(i)
52 log.info { "Number #{i} gives words #{words_of_number i}" }
53 end
54
55 puts words.join('').length
56 end
57
58 log.close