Skip to content

Instantly share code, notes, and snippets.

@MMintzer
Last active June 3, 2021 07:32
Show Gist options
  • Save MMintzer/4c1db673541939eeae986c140fd6e46a to your computer and use it in GitHub Desktop.
Save MMintzer/4c1db673541939eeae986c140fd6e46a to your computer and use it in GitHub Desktop.
// RIVER SIZES
// You are given a two-dimensiona array (matrix) of potentially unequal height and width containing only 0s and 1s.
// Each 0 represents land, and each 1 represents part of a river. A river consists of any number of adjacent 1s forming
// a river determine its size. Write a function that returns an array of the sizes of all rivers represented in the input
// matrix. Note that these sizes do not need to be in any particular order.
Sample input:
[
[1,0,0,1,0],
[1,0,1,0,0],
[0,0,1,0,1],
[1,0,1,0,1],
[1,0,1,1,0]
]
Sample output:
[1,2,2,2,5]
(1 length of 1 river,
3 length of 2 rivers,
1 length of 5 river)
HOW TO INTERVIEW:
//Guide them into splitting the problem up into sections. Most candidates should figure that they need nested for loops to look
// at every location in the matrix. They will likely struggle on how to check adjacent spots. Have them speak out loud of how
// they would access the different spots once they have an i and j.
My solution
// I initialize a results array then loop through the matrix
// I use a nested for loop in order to access the integers at each y,x location
// if the location === 1, I'm on a river and I need to check the adjacent spaces.
function riverSizes(matrix) {
let results = [];
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] === 1) {
results.push(checkAdj(i, j, matrix));
}
}
}
return results;
}
// the first thing I do here is flip the spot I'm currently at from a river to land. I do this so I don't end up double
// checking it.
// I initialize a riverSize variable and give it a starting value of 1 because 1 river is 1 length.
// I have 4 conditionals to check each of the 4 adjacent spots on the matrix. If they are === 1, they are a river
// and I now need to check the adjacent tiles on THAT spot so I recursively call checkAdj on the new location, passing
// in our matrix
function checkAdj(i, j, matrix) {
matrix[i][j] = 0;
let riverSize = 1;
if (matrix[i + 1] && matrix[i + 1][j] === 1) {
riverSize += checkAdj(i + 1, j, matrix);
}
if (matrix[i - 1] && matrix[i - 1][j] === 1) {
riverSize += checkAdj(i - 1, j, matrix);
}
if (matrix[i][j + 1] === 1) {
riverSize += checkAdj(i, j + 1, matrix);
}
if (matrix[i][j - 1] === 1) {
riverSize += checkAdj(i, j - 1, matrix);
}
return riverSize;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment