Last active
February 16, 2024 13:26
-
-
Save Ephygtz/19f480c4fed48a28433e610cf7ec32cc to your computer and use it in GitHub Desktop.
JS practise algos
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Reserve first available seat in a two dimensional array | |
let seats = [ | |
[1, 1, 0, 1, 0], | |
[0, 1, 1, 1, 0], | |
[1, 0, 1, 0, 0], | |
]; | |
//traverse the array | |
function reserveFirstAvailableSeat(seats) { | |
for (let i = 0; i < seats.length; i++) { | |
for (let j = 0; j < seats[i].length; j++) { | |
if (seats[i][j] === 0) { | |
seats[i][j] = 1; // Reserve the seat | |
console.log(`Reserved seat at row ${i + 1}, column ${j + 1}`); | |
break; //use return instead of break, alternatively, use labelled statements to explicitly break out of the loop | |
} | |
} | |
} | |
} | |
reserveFirstAvailableSeat(seats); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The code ends up making 3 reservations instead of 1. This is because the break statement only breaks out of the inner loop, not the outer loop. To fix this, you can replace the break statement with a return statement.