-
Notifications
You must be signed in to change notification settings - Fork 1
/
day-04.ts
48 lines (41 loc) · 1.61 KB
/
day-04.ts
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
export const getNumberOfPossiblePasswords = (rangeStart: number, rangeEnd: number): number => {
let numberOfPWs = rangeEnd - rangeStart;
for (; rangeStart < rangeEnd; rangeStart++) {
if (!isValidPassword(rangeStart)) {
numberOfPWs--;
}
}
return numberOfPWs;
};
export const getNumberOfPossiblePasswordsPartTwo = (rangeStart: number, rangeEnd: number): number => {
let numberOfPWs = rangeEnd - rangeStart;
for (; rangeStart < rangeEnd; rangeStart++) {
if (!isValidPasswordPartTwo(rangeStart)) {
numberOfPWs--;
}
}
return numberOfPWs;
};
export const isValidPassword = (num: number): boolean => {
const digits = splitNumberIntoDigits(num);
return hasTwoEqualAdjacentDigits(digits) && !hasDecreasingDigits(digits);
};
export const isValidPasswordPartTwo = (num: number): boolean => {
const digits = splitNumberIntoDigits(num);
return hasTwoEqualSeparateAdjacentDigits(digits) && !hasDecreasingDigits(digits);
};
const splitNumberIntoDigits = (num: number): number[] => {
const digits = num.toString().split('');
return digits.map((digit) => parseInt(digit, 10));
};
const hasTwoEqualAdjacentDigits = (digits: number[]): boolean => {
const indexOfEqualDigits = digits.findIndex((digit, i) => digit === digits[i + 1]);
return indexOfEqualDigits !== -1;
};
const hasTwoEqualSeparateAdjacentDigits = (digits: number[]): boolean => {
return digits.some((digit, i) => digit === digits[i + 1] && digit !== digits[i + 2]);
};
const hasDecreasingDigits = (digits: number[]): boolean => {
const indexOfDecreasingDigit = digits.findIndex((digit, i) => digit > digits[i + 1]);
return indexOfDecreasingDigit !== -1;
};