-
Notifications
You must be signed in to change notification settings - Fork 0
/
day-1-part-2.js
117 lines (100 loc) · 2.87 KB
/
day-1-part-2.js
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
const readInputToArray = require('./inputHelper');
const exampleInput = [
'two1nine',
'eightwothree',
'abcone2threexyz',
'xtwone3four',
'4nineeightseven2',
'zoneight234',
'7pqrstsixteen',
]
const validDigits = {
one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine:9
}
const findNumInStr = (letters) => {
let foundNum;
for (let key in validDigits) {
if (validDigits.hasOwnProperty(key)) {
if (letters.includes(key)) {
foundNum = validDigits[key].toString(); //keep it a string
break;
}
}
}
return foundNum;
}
// search left to right, stop at 1st found
const numifyStrLtr = (str) => {
let letters = '';
let foundNum;
let iteratedUpTo = 0;
for (let i=0; i<str.length; i++) {
if (!!foundNum) {
break;
}
const char = str[i];
if (!isNum(char)) {
// append char
letters = letters + char;
found = findNumInStr(letters);
if (found) {
foundNum = found;
}
} else {
// if a number is found, that's the first number
foundNum = char
}
iteratedUpTo = i;
}
return [foundNum, iteratedUpTo];
}
// search right to left
// i know this isn't perfectly dry
const numifyStrRtl = (str) => {
let letters = '';
let foundNum;
for (let i=str.length - 1; i>=0; i--) {
if (!!foundNum) {
break;
}
const char = str[i];
if (!isNum(char)) {
// prepend char
letters = char + letters;
found = findNumInStr(letters);
if (found) {
foundNum = found;
}
} else {
// if a number is found, that's the first number
foundNum = char;
}
}
return foundNum
}
const isNum = (char) => !isNaN(parseInt(char));
const trebuString = (str) => {
let lastNum;
let foundIndex = 0;
// get first strNum or num
const [firstNum, i] = numifyStrLtr(str);
lastNum = firstNum;
// don't include what ltr already searched through
const foundNum = numifyStrRtl(str.substring(i+1))
lastNum = foundNum || lastNum;
return parseInt(firstNum + lastNum)
}
console.log(trebuString(exampleInput[0])) // 29
console.log(trebuString(exampleInput[1])) // 83
console.log(trebuString(exampleInput[2])) // 13
console.log(trebuString(exampleInput[3])) // 24
console.log(trebuString(exampleInput[4])) // 42
console.log(trebuString(exampleInput[5])) // 14
console.log(trebuString(exampleInput[6])) // 76
const trebuchet = (arr) => {
const total = arr.map(trebuString).reduce((acc, curr) => acc + curr, 0);
console.log(total);
}
trebuchet(exampleInput) // 281
const inputArr = readInputToArray('day-1');
trebuchet(inputArr) // 54719