Last active
August 10, 2019 00:22
-
-
Save santiago/d9b622119fdc93e4325634b25fc50d11 to your computer and use it in GitHub Desktop.
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
function leastDistance(input) { | |
const rowDim = input[0].length | |
const colDim = input.length | |
const isValidInput = !input.find(r => r.length !== rowDim) | |
// Track all positions for 1 and 2s; | |
// the 1 will be the first element | |
const positions = [] | |
input.forEach((row, i) => { | |
Array.from(row).forEach((s, j) => { | |
// If it's a 1, then add it at the beggining | |
// of `positions` | |
// Comparison to int, thanks to (==) JS :) | |
if (s == 1) { | |
positions.unshift([i, j]) | |
} | |
if (s == 2) { | |
positions.push([i, j]) | |
} | |
}) | |
}) | |
// Now find the least distance | |
const onePos = positions.shift() | |
return positions.reduce((min, twoPos) => { | |
const downWise = Math.abs(twoPos[0]-onePos[0]) | |
const upWise = colDim - downWise | |
const rightWise = Math.abs(twoPos[1]-onePos[1]) | |
const leftWise = rowDim - rightWise | |
return Math.min( | |
min, | |
Math.min( | |
upWise + rightWise, | |
upWise + leftWise, | |
downWise + rightWise, | |
downWise + leftWise, | |
) | |
) | |
}, Infinity) | |
} |
Input may be expressed as strings
e.g.
const input = [
"00000",
"00020",
"00000",
"00100",
]
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The problem of this code is that it's always expecting to find at least one instance of 1 and 2, while it should return 0 on some conditions