-
Notifications
You must be signed in to change notification settings - Fork 0
/
part2.js
79 lines (68 loc) · 2.64 KB
/
part2.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
// const input = require('./example-input')
const input = require('./input')
const data = input.split('\n');
const outputValues = data.map(note => {
const noteParts = note.split(' | ')
const signals = noteParts[0].split(' ')
// make output parts alpabatical order for easy string match
const outputs = noteParts[1].split(' ').map(o => o.split('').sort().join(''))
// placeholder array for numbers
const numbers = new Array(10)
signals.forEach(signal => {
switch (signal.length) {
case 2: // if 2 segments are on, its #1
numbers[1] = signal
break;
case 3: // if 3 segments are on, its #7
numbers[7] = signal
break;
case 4: // if 4 segments are on, its #4
numbers[4] = signal
break;
case 7: // if 7 segments are on, its #8
numbers[8] = signal
break;
}
})
// for numbers with 6 segments on
signals.filter(s => s.length === 6).forEach(signal => {
if (!numbers[7].split('').every(s => signal.includes(s))) {
// if 6 segments on and also all segments belog to #7 is not on,
// its #6
numbers[6] = signal
} else if (numbers[4].split('').every(s => signal.includes(s))) {
// if 6 segments on and also all segments belog to #4 is on,
// its #9
numbers[9] = signal
} else {
// otherwise its #0
numbers[0] = signal
}
})
// for numbers with 5 segments on
signals.filter(s => s.length === 5).forEach(signal => {
if (signal.split('').every(s => numbers[6].split('').includes(s))) {
// if 5 segments on and also all segments belog to #6,
// its #5
numbers[5] = signal
} else if (numbers[1].split('').every(s => signal.includes(s))) {
// if 5 segments on and also all segments belog to #1 is on,
// its #3
numbers[3] = signal
} else {
// otherwise its #2
numbers[2] = signal
}
})
// sort it alphabetically so its easier to compare
const sortedNumbers = numbers.map(number => number.split('').sort().join(''))
// find the index of matching number and join it together to get output value
const outputValue = outputs.map(
o => sortedNumbers.findIndex(number => number === o)
).join('')
return outputValue
});
// sum of all of the output values
const sumOfOutputValues = outputValues.map(Number).reduce((p, c) => p + c, 0);
console.log(sumOfOutputValues)
// 946346