-
Notifications
You must be signed in to change notification settings - Fork 0
/
part2.toki
58 lines (49 loc) Β· 1.16 KB
/
part2.toki
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import "../../tokiscript/examples/std.toki"
let wordToDigitMap = [
# zero isnt used
["one", "1"],
["two", "2"],
["three", "3"],
["four", "4"],
["five", "5"],
["six", "6"],
["seven", "7"],
["eight", "8"],
["nine", "9"],
]
fun FindDigit(line, compFunc, substrFunc, findFunc)
# Search for word
let wordDigit, wordPos
foreach v in wordToDigitMap
let pos = line:substrFunc(v[0])
if pos == nil
continue
end
if wordPos == nil
wordPos = pos
wordDigit = v[1]
elif compFunc(pos, wordPos)
wordPos = pos
wordDigit = v[1]
end
end
# Search for number
let numDigit, numPos = strtobytes(line):findFunc(fun(x) = ByteIsDigit(x))
if numPos /= nil
numDigit = line[numPos]
end
if numPos == nil
return wordDigit
elif wordPos == nil
return numDigit
end
# Return whichever appears sooner/later
return if compFunc(numPos, wordPos) then numDigit else wordDigit
end
let sum = 0
freadstr("input.txt"):ForeachDelimed("\n", fun(line)
let first = line:FindDigit(fun(a, b) = a < b, FindFirstSubstr, FindFirstIf)
let last = line:FindDigit(fun(a, b) = a > b, FindLastSubstr, FindLastIf)
sum ++ strtonum(first + last)
end)
println(sum)