-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path816-Ambiguous-Coordinates.js
46 lines (36 loc) · 1.25 KB
/
816-Ambiguous-Coordinates.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
/**
* @param {string} s
* @return {string[]}
*/
const ambiguousCoordinates = (s) => {
const format = (i, j) => `(${i}, ${j})`;
const isValid = (num) => Number(num).toString().length === num.length;
const getAllOptions = (num) => {
const options = [num];
for (let i = 1; i < num.length; i++) {
const beforeDecimal = num.slice(0, i);
const afterDecimal = num.slice(i);
const candidate = `${beforeDecimal}.${afterDecimal}`;
if (isValid(candidate)) options.push(candidate);
}
return options;
};
const getCombinedOptions = (arr1, arr2) => {
const combined = [];
for (const el1 of arr1) {
for (const el2 of arr2) {
if (isValid(el1) && isValid(el2)) combined.push(format(el1, el2));
}
}
return combined;
};
const result = [];
for (let i = 2; i < s.length; i++) {
const leftPart = s.slice(1, i);
const rightPart = s.slice(i, s.length - 1);
const leftOptions = leftPart ? getAllOptions(leftPart) : [];
const rightOptions = rightPart ? getAllOptions(rightPart) : [];
result.push(...getCombinedOptions(leftOptions, rightOptions));
}
return result;
};