-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day 3.js
74 lines (59 loc) · 2.04 KB
/
Day 3.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
const fs = require('fs');
const { parse } = require('path');
const path = require('path')
const data = fs.readFileSync(path.resolve(__dirname, 'data.txt'), 'utf8');
const parsedData = data.split(/(?:\s)\s/g);
// final results
let prioritySum = 0;
let badgePrioritySum = 0;
// group count used for finding badges
let groupCount = 0;
//accept string input, split in two based on string length.
splitString = (input) => {
return (
{
first: input.slice(0, input.length / 2),
second: input.slice(input.length / 2, input.length)
}
)
}
//returns priority based on letter provided.
priotize = (letter) => {
const isLower = /[a-z]/.test(letter);
if (!isLower) {
return letter.charCodeAt(0) - 38;
} else {
return letter.charCodeAt(0) - 96;
}
}
//returns found char for badges. Requires first index of where you'd like to search
badges = (groupIndex) => {
for (let i = 0; i < parsedData[groupIndex].length; i++) {
const secondGroupIndex = parsedData[groupIndex + 1].indexOf(parsedData[groupIndex][i]);
const thirdGroupIndex = parsedData[groupIndex + 2].indexOf(parsedData[groupIndex][i]);
if (secondGroupIndex !== -1 && thirdGroupIndex !== -1) {
groupCount = 3;
return parsedData[groupIndex][i];
}
}
}
//iterate over data provided.
parsedData.forEach((rucksack, index) => {
const twoCompartments = splitString(rucksack);
//badge and group check
while (groupCount === 0) {
const matchedLetter = badges(index);
badgePrioritySum += priotize(matchedLetter);
}
groupCount--;
for (let i = 0; i < twoCompartments.first.length; i++) {
// search second string for match of char. Returning index
const itemIndex = twoCompartments.second.indexOf(twoCompartments.first[i]);
if (itemIndex !== -1) {
prioritySum += priotize(twoCompartments.first[i]);
break;
}
}
})
console.log(prioritySum);
console.log(badgePrioritySum);