Created
May 11, 2018 05:14
-
-
Save skiano/0ece3c6d23e609c414ddbfee09c00c14 to your computer and use it in GitHub Desktop.
binary-blob-challenge created by skiano - https://repl.it/@skiano/binary-blob-challenge
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
// SOLUTION 1 | |
const getBlobBoundingBox1 = (blobString) => { | |
blobString = blobString.trim() | |
const width = (/\s/.exec(blobString) || {}).index | |
const one = /1/g | |
blobString = blobString.replace(/\s+/g, '') | |
let top = Infinity | |
let left = Infinity | |
let right = 0 | |
let bottom = 0 | |
let match | |
let i | |
let x | |
let y | |
while ((match = one.exec(blobString)) !== null) { | |
i = one.lastIndex - 1 // index of the 1 | |
x = i % width | |
y = Math.floor(i / width) | |
top = Math.min(top, y) | |
left = Math.min(left, x) | |
right = Math.max(right, x) | |
bottom = Math.max(bottom, y) | |
} | |
return { top, left, right, bottom } | |
} | |
// SOLUTION 2 | |
// the extra args just allo the instantiation to | |
// be grouped for common values | |
// i = current loop index | |
// x = x coordinate of loop index | |
// y = y coordinate of loop index | |
// t = top of bounding box | |
// l = left of bounding box | |
// r = right of bounding box | |
// b = bottom of bounding box | |
function getBlobBoundingBox2 (blob, i, x, y, t, l, r, b) { | |
blob = blob.trim().replace(/\s+/g, '.') | |
i = x = y = r = b = 0 | |
t = l = Infinity | |
for (i; i < blob.length; i ++) { | |
switch (blob[i]) { | |
case '0': | |
x++ | |
break | |
case '1': | |
t = t > y ? y : t | |
l = l > x ? x : l | |
r = r < x ? x : r | |
b = b < y ? y : b | |
x++ | |
break | |
default: | |
y += 1 | |
x = 0 | |
} | |
} | |
return { top: t, left: l, right: r, bottom: b } | |
} | |
const blobString = ` | |
0000000000 | |
0011100000 | |
0011111000 | |
0010001000 | |
0011111000 | |
0000101000 | |
0000101000 | |
0000111000 | |
0000000000 | |
0000000000 | |
` | |
console.log(getBlobBoundingBox1(blobString)) | |
console.log(getBlobBoundingBox2(blobString)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment