Last active
April 3, 2020 22:49
-
-
Save dukuo/4a7124aa8230a7608154181c313c6983 to your computer and use it in GitHub Desktop.
Find the first slot to insert a 1D array inside a 2D array
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
/* | |
@author @dukuo | |
| |
Sample usage: | |
const size_X = 10; | |
const size_Y = 10; | |
const sampleArray = new Array(size_X).fill(new Array(size_Y).fill(null)); | |
| |
// Fill array with random occurrence of values or null. | |
for(var j = 0; j < size_Y; j++) { | |
const rnd1 = Math.random(); | |
for(var i = 0; i < size_X; i++) { | |
const rnd2 = Math.random(); | |
if(rnd1 + rnd2 >= .6) { | |
sampleArray[i][j] = rnd1; | |
} else { | |
sampleArray[i][j] = null; | |
} | |
} | |
} | |
const sampleArrayToInsert = new Array(2); | |
if(checkNearestEmptySlot(sampleArray, sampleArrayToInsert.length)) { | |
console.log("Insertion Logic") | |
} | |
*/ | |
const checkNearestEmptySlot = (array, insertLength, filter = null) => { | |
const size_X = array[0].length | |
const size_Y = array.length | |
const err = -1 | |
let start = err | |
let end = err | |
for (let j = 0; j < size_Y; j++) { | |
for (let i = 0; i < size_X; i++) { | |
if (start === err && array[i][j] === filter) { | |
start = [i, j] | |
// console.log("FOUND A START AT ", start) | |
} else if (start !== err && end === err && array[i][j] === filter) { | |
end = [i, j] | |
// console.log("FOUND AN END AT ", end) | |
} | |
if (start !== err && end !== err && (Math.abs(start[0] - end[0]) >= insertLength - 1 || Math.abs(start[1] - end[1]) >= 1)) { | |
// console.log("FOUND A SLOT TO FIT ", insertLength, " BETWEEN ", start, " AND ", end) | |
return start | |
} | |
} | |
} | |
return err | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment