-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
87 lines (71 loc) · 2.29 KB
/
main.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
const data = require('./input.js');
const parseData = (data) => data.split(`\n`);
const shiftToMinute = (shiftPattern) => {
const [_, minute] = shiftPattern.match(/\d\d:(\d\d)/);
return +minute;
};
const incrementSleepingMinutes = (guardMinutes, sleepMin, wakeMin) => {
for (let i = sleepMin; i < wakeMin; i++) {
guardMinutes[i] += 1;
}
return guardMinutes;
};
const findGuardAndMinute = (guardsAndMinutes) => {
const likelyGuard = { id: null, sleepiestMin: null, sleepMins: -Infinity };
Object.entries(guardsAndMinutes).forEach(([guard, minutes]) => {
const currentGuardSleepMins = minutes.reduce((a, b) => a + b);
if (currentGuardSleepMins > likelyGuard.sleepMins) {
likelyGuard.sleepMins = currentGuardSleepMins;
likelyGuard.id = guard;
const highestSleepFrequency = Math.max(...minutes);
likelyGuard.sleepiestMin = minutes.findIndex(
(e) => e === highestSleepFrequency
);
}
});
return likelyGuard;
};
const createGuardShiftData = (shifts) => {
const guardsAndMinutes = {};
let currentGuard = null;
for (let i = 0; i < shifts.length; i++) {
const guardId = shifts[i].match(/#\d+/);
if (guardId) {
currentGuard = guardId;
if (!guardsAndMinutes.hasOwnProperty(guardId)) {
guardsAndMinutes[guardId] = Array(60).fill(0);
}
} else if (shifts[i].includes('asleep')) {
incrementSleepingMinutes(
guardsAndMinutes[currentGuard],
shiftToMinute(shifts[i]),
shiftToMinute(shifts[i + 1])
);
i++;
}
}
return guardsAndMinutes;
};
const extractTimeStampAsNumber = (shift) => {
return +shift.split(']')[0].replace(/\D/g, '');
};
const sortShiftsByDate = (shifts) => {
shifts.sort((a, b) => {
return extractTimeStampAsNumber(a) - extractTimeStampAsNumber(b);
});
return shifts;
};
const calculateMostLikelyGuardsMostLikelyMinute = (data) => {
const sortedShiftData = sortShiftsByDate(parseData(data));
const guardShiftData = createGuardShiftData(sortedShiftData);
return findGuardAndMinute(guardShiftData);
};
console.log(calculateMostLikelyGuardsMostLikelyMinute(data));
module.exports = {
shiftToMinute,
incrementSleepingMinutes,
createGuardShiftData,
extractTimeStampAsNumber,
sortShiftsByDate,
calculateMostLikelyGuardsMostLikelyMinute,
};