-
Notifications
You must be signed in to change notification settings - Fork 236
/
Copy pathpatternMatcher.js
76 lines (59 loc) · 1.84 KB
/
patternMatcher.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
// pattern = "xxyxxy"
// string = "gogopowerrangergogopowerranger"
// output: ["go", "powerranger"]
function patternMatcher(pattern, string) {
if (pattern.length > string.length) {
return [];
}
const newPattern = getNewPattern(pattern);
const hasPatternSwitched = pattern[0] !== newPattern[0];
const counts = { x: 0, y: 0 };
const firstYIndex = getCountsAndFirstYIndex(newPattern, counts);
if (counts.y !== 0) {
for (let lengOfX = 1; lengOfX <= string.length; lengOfX++) {
const lengOfY = (string.length - lengOfX * counts.x) / counts.y;
if (lengOfY <= 0 || lengOfY % 1 !== 0) {
continue;
}
const x = string.slice(0, lengOfX);
const yPosition = firstYIndex * lengOfX;
const y = string.slice(yPosition, yPosition + lengOfY);
const potentialMatch = newPattern
.map((char) => (char === 'x' ? x : y))
.join('');
if (potentialMatch === string) {
return hasPatternSwitched ? [y, x] : [x, y];
}
}
} else {
const lengOfX = string.length / counts.x;
if (lengOfX % 1 !== 0) {
return [];
}
const x = string.slice(0, lengOfX);
const potentialMatch = newPattern.map(() => x).join('');
if (potentialMatch === string) {
return hasPatternSwitched ? ['', x] : [x, ''];
}
}
return [];
}
function getNewPattern(pattern) {
let patternArray = pattern.split('');
if (patternArray[0] === 'x') {
return patternArray;
}
return patternArray.map((item) => (item === 'x' ? 'y' : 'x'));
}
function getCountsAndFirstYIndex(newPattern, counts) {
let firstYIndex = null;
newPattern.map((item, i) => {
if (item === 'y' && firstYIndex === null) {
firstYIndex = i;
}
counts[item]++;
});
return firstYIndex;
}
const result = patternMatcher('xxyxxy', 'gogopowerrangergogopowerranger');
console.log(result);