Lua Implementation of Problem 22
View source code here on GitHub!
Includes
Solution
- solution()
- Returns:
The solution to problem 22
- Return type:
number
1-- Project Euler Problem 22
2--
3-- Problem:
4--
5-- Using names.txt (right click and 'Save Link/Target As...'), a 46K text file
6-- containing over five-thousand first names, begin by sorting it into
7-- alphabetical order. Then working out the alphabetical value for each name,
8-- multiply this value by its alphabetical position in the list to obtain a name
9-- score.
10--
11-- For example, when the list is sorted into alphabetical order, COLIN, which is
12-- worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would
13-- obtain a score of 938 × 53 = 49714.
14--
15-- What is the total of all the name scores in the file?
16
17local get_data_file = loadlib("utils").get_data_file
18
19return {
20 solution = function()
21 local answer = 0
22 local array = {get_data_file("p0022_names.txt"):gsub('"', ''):gmatch("([^,]+)")}
23 table.sort(array)
24 for idx, name in ipairs(array) do
25 local score = 0
26 for i = 1,#name do
27 score = score + string.byte(name, i) - string.byte('A', 1) + 1
28 end
29 answer = answer + score * idx
30 end
31 return answer
32 end
33}