Skip to content

Instantly share code, notes, and snippets.

@TheSavior
Last active June 15, 2016 22:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheSavior/7887740 to your computer and use it in GitHub Desktop.
Save TheSavior/7887740 to your computer and use it in GitHub Desktop.
Quad Tree overlap (My first Google interview question ever)
/*
Given two images of equal size, whose dimensions are square with edge length of a power of 2,
calculate the overlap of those imagesin O(log(N)) average case where N is the number of pixels.
n1 =
+----+----+
| 2 | 3 |
+----|----|
| 2 | 2 |
+----|----+
n2 =
+---------+--------+
| | |
| 2 | 3 |
+----+----|--------|
| 4 | 4 | |
+----|----| 5 |
| 4 | 2 | |
+----+----+--------+
result =
+---------+--------+
| | |
| 2 | 3 |
+----+----|--------|
| -1 | -1 | |
+----|----| -1 |
| -1 | 2 | |
+----+----+--------+
*/
var util = require('util');
var counter = 0;
function Node(data) {
var obj = {
_id: counter++,
_children: {},
_data: -1,
_hasChildren: false,
setChild: function(index, child) {
if (!this._hasChildren) {
this._hasChildren = true;
for(var i = 0; i < 4; i++) {
this._children[i] = new Node(this._data);
}
}
this._children[index] = child;
}
}
obj._data = data;
return obj;
}
function check(node1, node2, work) {
if (node1 == undefined || node2 == undefined)
return;
// console.log();
//console.log("--calling check", node1, node2, work);
if (!node1._hasChildren && !node2._hasChildren) {
if(node1._data == node2._data) {
work._data = node1._data;
}
else
{
work._data = -1;
}
}
else if (!node1._hasChildren && node2._hasChildren) {
for(var i = 0; i < 4; i++) {
var childWork = new Node(-1);
check(node1, node2._children[i], childWork);
if (childWork._data != -1 || childWork._hasChildren) {
work.setChild(i, childWork);
}
}
}
else if (node1._hasChildren && !node2._hasChildren) {
for(var i = 0; i < 4; i++) {
var childWork = new Node(-1);
check(node1._children[i], node2, childWork);
if (childWork._data != -1 || childWork._hasChildren) {
work.setChild(i, childWork);
}
}
}
else
{
// both have children
for (var i = 0; i < 4; i++) {
var childWork = new Node(-1);
check(node1._children[i], node2._children[i], childWork);
if (childWork._data != -1 || childWork._hasChildren) {
work.setChild(i, childWork);
}
}
}
return work;
}
var n1 = new Node(2);
var n4 = new Node(3);
n1.setChild(1, n4);
var n2 = new Node(-1);
n2.setChild(0, new Node(2));
n2.setChild(1, new Node(3));
n3 = new Node(4);
n3.setChild(3, new Node(2));
n2.setChild(2, n3);
n2.setChild(3, new Node(5));
var work = new Node(-1);
console.log(util.inspect(check(n1, n2, work), false, null));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment