Skip to content

Instantly share code, notes, and snippets.

@Ephygtz
Last active February 16, 2024 13:26
Show Gist options
  • Save Ephygtz/19f480c4fed48a28433e610cf7ec32cc to your computer and use it in GitHub Desktop.
Save Ephygtz/19f480c4fed48a28433e610cf7ec32cc to your computer and use it in GitHub Desktop.
JS practise algos
// 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);
@Ephygtz
Copy link
Author

Ephygtz commented Feb 16, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment