Lua Implementation of Problem 17

View source code here on GitHub!

Solution

solution()
Returns:

The solution to problem 17

Return type:

number

 1-- Project Euler Problem 17
 2--
 3-- The key here was remembering I don't need to return the whole string, just the length
 4--
 5-- Problem:
 6--
 7-- If the numbers 1 to 5 are written out in words: one, two, three, four, five,
 8-- then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
 9--
10-- If all the numbers from 1 to 1000 (one thousand) inclusive were written out in
11-- words, how many letters would be used?
12--
13-- NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and
14-- forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20
15-- letters. The use of "and" when writing out numbers is in compliance with
16-- British usage.
17
18local function to_string_len(n)
19    if n >= 1000 then
20        local thousands = to_string_len(math.floor(n / 1000 % 100)) + 8
21
22        if n % 1000 ~= 0 then
23            thousands = thousands + to_string_len(n % 1000)
24        end
25
26        return thousands
27    end
28
29    if n >= 100 then
30        local hundreds = to_string_len(math.floor(n / 100 % 10)) + 7
31
32        if n % 100 ~= 0 then
33            hundreds = hundreds + 3 + to_string_len(n % 100)
34        end
35
36        return hundreds
37    end
38
39    if n >= 20 then
40        local tens_t = {
41            [2] = 6,
42            [3] = 6,
43            [4] = 5,
44            [5] = 5,
45            [6] = 5,
46            [7] = 7,
47            [8] = 6,
48            [9] = 6,
49        }
50        local tens = tens_t[math.floor(n / 10)]
51
52        if n % 10 ~= 0 then
53            tens = tens + to_string_len(n % 10)
54        end
55
56        return tens
57    end
58
59    local final = {
60        [0] = 4,
61        [1] = 3,
62        [2] = 3,
63        [3] = 5,
64        [4] = 4,
65        [5] = 4,
66        [6] = 3,
67        [7] = 5,
68        [8] = 5,
69        [9] = 4,
70        [10] = 3,
71        [11] = 6,
72        [12] = 6,
73        [13] = 8,
74        [14] = 8,
75        [15] = 7,
76        [16] = 7,
77        [17] = 9,
78        [18] = 8,
79        [19] = 8,
80    }
81    return final[n]
82end
83
84return {
85    solution = function()
86        local answer = 0
87
88        for x = 1,1000 do
89            answer = answer + to_string_len(x)
90        end
91
92        return answer
93    end
94}

Tags: word-problem, combinatorics