-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
225 lines (192 loc) · 5.84 KB
/
index.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
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
document.getElementById("startGameButton").addEventListener("click", startGame);
document.getElementById("nextRoundButton").addEventListener("click", nextRound);
let randomNumber, randomIndex, numberArray;
function startGame() {
document.getElementById("gameArea").classList.remove("hidden");
document.getElementById("startGameButton").classList.add("hidden");
nextRound();
}
function nextRound() {
generateRandomNumbers();
randomNumber = Math.floor(Math.random() * 1000000) + 1;
randomIndex = numberArray.indexOf(randomNumber);
// Regenerate random number if not found
while (randomIndex === -1) {
randomNumber = Math.floor(Math.random() * 1000000) + 1;
randomIndex = numberArray.indexOf(randomNumber);
}
document.getElementById(
"randomNumberText"
).innerText = `Predict the index of the value: ${randomNumber}`;
displayChoices();
runSearchAlgorithms();
}
function generateRandomNumbers() {
numberArray = Array.from(
{ length: 5000 },
() => Math.floor(Math.random() * 1000000) + 1
);
randomNumber = Math.floor(Math.random() * 1000000) + 1;
numberArray.push(randomNumber); // Ensure the random number is added to the array
numberArray.sort((a, b) => a - b);
}
function displayChoices() {
const choicesContainer = document.getElementById("choices");
choicesContainer.innerHTML = "";
const choices = [
randomIndex,
randomIndex + 1,
randomIndex - 1,
Math.floor(Math.random() * 5000),
];
shuffleArray(choices);
choices.forEach((choice) => {
const button = document.createElement("button");
button.innerText = choice;
button.addEventListener("click", () => handleChoice(choice));
choicesContainer.appendChild(button);
});
}
function handleChoice(choice) {
const resultText = choice === randomIndex ? "Correct!" : "Wrong!";
alert(resultText);
if (resultText === "Correct!") {
const playerName = prompt("Enter your name:");
saveUserScore(playerName, randomNumber, choice);
}
document.getElementById("nextRoundButton").classList.remove("hidden");
}
function saveName() {
const playerName = document.getElementById("playerNameInput").value;
if (playerName.trim() !== "") {
saveUserScore(playerName, randomNumber, randomIndex);
document.getElementById("nameModal").classList.add("hidden");
} else {
alert("Please enter a valid name.");
}
}
function saveUserScore(name, value, index) {
const data = { name, value, index };
fetch("http://localhost:4001/saveResponse", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
})
.then((response) => {
if (response.ok) {
alert("Score saved successfully!");
} else {
alert("Error saving score.");
}
})
.catch((error) => {
console.error("Error:", error);
alert("An error occurred while saving the score.");
});
}
function runSearchAlgorithms() {
const searchMethods = [
{ name: "Binary Search", func: binarySearch },
{ name: "Jump Search", func: jumpSearch },
{ name: "Exponential Search", func: exponentialSearch },
{ name: "Fibonacci Search", func: fibonacciSearch },
{ name: "Interpolation Search", func: interpolationSearch },
];
const resultsList = document.getElementById("resultsList");
resultsList.innerHTML = "";
searchMethods.forEach((method) => {
const start = performance.now();
const index = method.func(numberArray, randomNumber);
const end = performance.now();
const timeTaken = (end - start).toFixed(4);
const li = document.createElement("li");
li.innerText = `${method.name}: Index found = ${index}, Time taken = ${timeTaken} ms`;
resultsList.appendChild(li);
});
document.getElementById("statistics").classList.remove("hidden");
}
function binarySearch(arr, x) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === x) return mid;
if (arr[mid] < x) left = mid + 1;
else right = mid - 1;
}
return -1;
}
function jumpSearch(arr, x) {
const n = arr.length;
const m = Math.floor(Math.sqrt(n));
let prev = 0;
let curr = m;
while (arr[Math.min(curr, n) - 1] < x) {
prev = curr;
curr += m;
if (prev >= n) return -1;
}
for (let i = prev; i < Math.min(curr, n); i++) {
if (arr[i] === x) return i;
}
return -1;
}
function exponentialSearch(arr, x) {
if (arr[0] === x) return 0;
let i = 1;
while (i < arr.length && arr[i] <= x) {
i *= 2;
}
return binarySearch(arr.slice(i / 2, Math.min(i, arr.length)), x);
}
function fibonacciSearch(arr, x) {
const n = arr.length;
let fibSec = 0; // (m-2)'th Fibonacci number
let fibfst = 1; // (m-1)'th Fibonacci number
let f = fibSec + fibfst; // m'th Fibonacci number
while (f < n) {
fibSec = fibfst;
fibfst = f;
f = fibSec + fibfst;
}
let offset = -1;
while (f > 1) {
const i = Math.min(offset + fibSec, n - 1);
if (arr[i] < x) {
f = fibfst;
fibfst = fibSec;
fibSec = f - fibfst;
offset = i;
} else if (arr[i] > x) {
f = fibSec;
fibfst -= fibSec;
fibSec = f - fibfst;
} else return i;
}
if (fibfst && arr[offset + 1] === x) return offset + 1;
return -1;
}
function interpolationSearch(arr, x) {
let low = 0;
let high = arr.length - 1;
while (low <= high && x >= arr[low] && x <= arr[high]) {
if (low === high) {
if (arr[low] === x) return low;
return -1;
}
const idx = low + Math.floor(((high - low) / (arr[high] - arr[low])) * (x - arr[low]));
if (arr[idx] === x) return idx;
if (arr[idx] < x) low = idx + 1;
else high = idx - 1;
}
return -1;
}
// Utility Functions
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}