-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path185-number-mind.js
More file actions
109 lines (86 loc) · 2.6 KB
/
185-number-mind.js
File metadata and controls
109 lines (86 loc) · 2.6 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/*
* Number Mind
* Time Complexity: O(10^(L/2) * N)
* Space Complexity: O(10^(L/2))
*/
function processData(input) {
const lines = input.trim().split("\n");
if (lines.length < 2) return;
let lineIdx = 0;
while (lineIdx < lines.length && !lines[lineIdx].trim()) lineIdx++;
const N = parseInt(lines[lineIdx++].trim(), 10);
const guesses = [];
for (let i = 0; i < N; i++) {
while (lineIdx < lines.length && !lines[lineIdx].trim()) lineIdx++;
if (lineIdx >= lines.length) break;
const parts = lines[lineIdx++].trim().split(/\s+/);
guesses.push({
str: parts[0],
target: parseInt(parts[1], 10),
});
}
const HALF_LEN = 6;
const TOTAL_LEN = 12;
const firstHalfMap = new Map();
const currentMatches = new Int8Array(N);
function generateFirstHalf(idx, currentStr) {
if (idx === HALF_LEN) {
const key = currentMatches.join("");
if (!firstHalfMap.has(key)) {
firstHalfMap.set(key, currentStr);
}
return;
}
for (let d = 0; d <= 9; d++) {
const char = String(d);
let possible = true;
for (let i = 0; i < N; i++) {
if (guesses[i].str[idx] === char) currentMatches[i]++;
if (currentMatches[i] > guesses[i].target) possible = false;
}
if (possible) generateFirstHalf(idx + 1, currentStr + char);
for (let i = 0; i < N; i++) {
if (guesses[i].str[idx] === char) currentMatches[i]--;
}
}
}
generateFirstHalf(0, "");
let finalAnswer = null;
function generateSecondHalf(idx, currentStr) {
if (finalAnswer) return;
if (idx === TOTAL_LEN) {
let keyBuilder = "";
for (let i = 0; i < N; i++) {
keyBuilder += guesses[i].target - currentMatches[i];
}
if (firstHalfMap.has(keyBuilder)) {
finalAnswer = firstHalfMap.get(keyBuilder) + currentStr;
}
return;
}
for (let d = 0; d <= 9; d++) {
const char = String(d);
let possible = true;
for (let i = 0; i < N; i++) {
if (guesses[i].str[idx] === char) currentMatches[i]++;
if (currentMatches[i] > guesses[i].target) possible = false;
}
if (possible) generateSecondHalf(idx + 1, currentStr + char);
if (finalAnswer) return;
for (let i = 0; i < N; i++) {
if (guesses[i].str[idx] === char) currentMatches[i]--;
}
}
}
generateSecondHalf(HALF_LEN, "");
console.log(finalAnswer);
};
process.stdin.resume();
process.stdin.setEncoding("ascii");
let _input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});