Skip to content

Instantly share code, notes, and snippets.

@masotime
Created December 7, 2015 17:00
Show Gist options
  • Select an option

  • Save masotime/ade1e09a8d75738ee607 to your computer and use it in GitHub Desktop.

Select an option

Save masotime/ade1e09a8d75738ee607 to your computer and use it in GitHub Desktop.
Karat Puzzle
/*var _ = require('underscore')
function sayHello() {
console.log('Hello, World');
}
_.times(5, sayHello);
*/
var image = [
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 0, 0, 0, 1],
[1, 1, 1, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1]
];
var image = [
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 0, 0, 0, 1],
[1, 0, 1, 0, 0, 0, 1],
[1, 0, 1, 1, 1, 1, 1],
[1, 0, 1, 0, 0, 1, 1],
[1, 1, 1, 0, 0, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
];
function findAPixel(image) {
var height = image.length;
var width = image[0].length;
var x,y;
// naive solution first, search whole image
for (y=0; y<height; y+=1) {
for (x=0; x<width; x+=1) {
if (image[y][x] === 0) {
return { x: x, y: y};
}
}
}
}
function solveTheSize(image, coords) {
// will have x,y, width, height
var height = image.length;
var width = image[0].length;
var rect = { x: coords.x, y: coords.y };
// find the upper-left corner first
var upperX, upperY;
for (upperX = rect.x; upperX > 0; upperX -= 1) {
if (image[rect.y][upperX] === 1) {
rect.x = upperX + 1;
break;
}
}
for (upperY = rect.y; upperY > 0; upperY -= 1) {
if (image[upperY][rect.x] === 1) {
rect.y = upperY + 1;
break;
}
}
// find the width and height of the rectangle
var lowerX, lowerY;
for (lowerX = rect.x; lowerX < width; lowerX += 1) {
if (image[rect.y][lowerX] === 1) {
rect.width = lowerX - rect.x;
break;
}
}
for (lowerY = rect.y; lowerY < height; lowerY += 1) {
if (image[lowerY][rect.x] === 1) {
rect.height = lowerY - rect.y;
break;
}
}
return rect;
}
var aPixel = findAPixel(image);
var dimensions = solveTheSize(image, aPixel);
console.log(aPixel);
console.log(dimensions);
/*
Your previous Markdown content is preserved below:
var image = [
[-1, 1, 1, 1, 1, 1, 1],
[1, -1, 1, 1, 1, 1, 1],
[1, 1, -1, 0, 0, 0, 1],
[1, 1, 1, -0, 0, -0, 1],
[1, 1, 1, 1, 1, 1, -1]
];
var answer = {
top: [2,3], // y coord, x coord
width: 3,
height: 2
}
image[0][0]
image[1][0] // down
image[0][1] // right
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment