-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtwo-characters.js
More file actions
39 lines (33 loc) · 835 Bytes
/
two-characters.js
File metadata and controls
39 lines (33 loc) · 835 Bytes
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
/**
* @title Two Characters
* @difficulty Easy
* @link https://www.hackerrank.com/challenges/two-characters/problem
*/
const alternate = originString => {
const chars = [...originString];
const uniques = [...new Set(chars)];
let max = 0;
forUniquePairs(uniques, pair => {
const alteredChars = chars.filter(char => pair.includes(char));
if (isValid(alteredChars)) {
max = Math.max(max, alteredChars.length);
}
});
return max;
};
const forUniquePairs = (array, fn) => {
const {length} = array;
for (let i = 0; i < length - 1; i++) {
for (let j = i + 1; j < length; j++) {
fn([array[i], array[j]]);
}
}
};
const isValid = array => (
array.every((char, index, {length}) => {
if (index >= length - 1) {
return true;
}
return char !== array[index + 1];
})
);