-
-
Notifications
You must be signed in to change notification settings - Fork 223
Expand file tree
/
Copy pathfrogRiverOne.js
More file actions
51 lines (39 loc) · 1.48 KB
/
frogRiverOne.js
File metadata and controls
51 lines (39 loc) · 1.48 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
function frogRiverOne(destinationPosition, positionsList) {
const positions = new Set();
for(let i = 0; i < positionsList.length; i++) {
positions.add(positionsList[i]);
if(positions.size === destinationPosition) {
return i;
}
}
return -1;
}
function frogRiverTwo(destinationPosition, positionsList) {
const seen = Array(destinationPosition).fill(false);
let uncovered = destinationPosition;
for(let i = 0; i < positionsList.length; i++) {
if(!seen[positionsList[i]-1]) {
seen[positionsList[i]-1] = true;
uncovered--;
if(uncovered === 0) {
return i;
}
}
}
return -1;
}
// Example 1: Multiple positions in different times
console.log(frogRiverOne(5, [1, 3, 1, 4, 2, 3, 5, 4])); // Output: 6
console.log(frogRiverTwo(5, [1, 3, 1, 4, 2, 3, 5, 4])); // Output: 6
// Example 2: Missing position, frog can't cross
console.log(frogRiverOne(3, [1, 3, 1, 1])); // Output: -1
console.log(frogRiverTwo(3, [1, 3, 1, 1])); // Output: -1
// Example 3: Immediate success
console.log(frogRiverOne(1, [1])); // Output: 0
console.log(frogRiverTwo(1, [1])); // Output: 0
// Example 4: Leaves fall in reverse order
console.log(frogRiverOne(3, [3, 2, 1])); // Output: 2
console.log(frogRiverTwo(3, [3, 2, 1])); // Output: 2
// Example 5: Repeated positions
console.log(frogRiverOne(2, [1, 1, 1, 2])); // Output: 3
console.log(frogRiverTwo(2, [1, 1, 1, 2])); // Output: 3