How to store depth of Binary Search Tree - javascript

I'm trying to determine if a Binary Search Tree is balanced. I'm not too clear on how to store the depth of the childnodes of the left and right branch. I'm trying to return true if the right branch is greater than the left branch by a length of a max of 1 and vice versa.
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* #param {TreeNode} root
* #return {boolean}
*/
var isBalanced = function(root) {
var checkChild = function(root) {
if (this.left) {
var left = 1;
this.left.checkChild(root);
if (this.right) {
left += 1;
this.right.checkChild(root);
}
if (this.right) {
var right = 1;
this.right.checkChild(root);
if (this.left) {
right += 1;
this.right.checkChild(root);
}
}
}
if (left - right > 1 || right - left > 1) {
return false;
}
return true;
};
};
I was thinking of creating a var to increment every-time a node is traversed for both the right and left branches starting from the head. But I'm realizing that this will compare the total number of nodes from the left branch to the total number of nodes on the right branch, which won't work.

At each check why are you sending the head again like
why root again?
this.left.checkChild(root)
Instead, if you want to find the depth, your implementation should look something like this:
function treeDepth(tree)
{
if (tree === null)
return 0;
else
{
/* compute the depth of each subtree */
let leftDepth = treeDepth(tree.left);
let rightDepth = treeDepth(tree.right);
/* use the larger one */
if (leftDepth > rightDepth)
return(leftDepth+1);
else return(rightDepth+1);
}
}

At first find max depth of the root, then find min depth of the root. It is easy using dfs. Next step is to check difference of these depths.
The code will look like this:
class Node {
constructor(value) {
this.value = value
this.left = null
this.right = null
}
}
var isBalanced = function(root) {
var foo = function(root, fun) {
if (root === null) return 0
l = foo(root.left, fun)
r = foo(root.right, fun)
return fun(l, r);
}
return foo(root, Math.max) - foo(root, Math.min) < 2
}
let tree = new Node(1)
tree.left = new Node(2)
tree.left.left = new Node(3)
tree.left.left.left = new Node(4)
tree.right = new Node(5)
tree.right.left = new Node(6)
document.write(isBalanced(tree))

If you want to use checkChild as a method, you should define it as such, not as a variable. I would also suggest to not return a boolean, but the real difference in depth between left and right subtree. This will give more information to the caller, who can still treat that value as a boolean if so desired (falsy means balanced, truthy means tilted).
Here is how your implementation could look:
class TreeNode {
constructor(val) {
this.val = val;
}
add(node) {
const dir = node.val < this.val ? "left" : "right";
if (this[dir]) {
this[dir].add(node);
} else {
this[dir] = node;
}
}
height() {
return Math.max(
this.left ? this.left.height() + 1 : 0,
this.right ? this.right.height() + 1 : 0
);
}
tilt() {
return (this.left ? this.left.height() + 1 : 0)
- (this.right ? this.right.height() + 1 : 0);
}
static from(...data) {
if (!data.length) return;
const root = new TreeNode(data[0]);
for (let v of data.slice(1)) {
root.add(new TreeNode(v));
}
return root;
}
}
const root = TreeNode.from(13, 4, 9, 16);
console.log(root);
console.log('Tilt at root = ', root.tilt());
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related

Splay Tree implementation: Search function - Zag zag rotation wrong

I am testing Zag-zag rotation with a right-skewed tree. Before that, I had tested Zig-zig, Zig-zag rotation with a left-skewed tree and OK.
Here is my code:
// An AVL tree node
class Node {
constructor(key) {
this.key = key;
this.left = this.right = null;
}
}
function rightRotate(root) {
const rootLeft = root.left; // saving the reference
root.left = rootLeft.right;
rootLeft.right = root;
return rootLeft; // new root
}
function leftRotate(root) {
const rootRight = root.right;
root.right = rootRight.left;
rootRight.left = root;
return rootRight;
}
// This function modifies the tree and returns the new root
// - If has key, Brings the key at root
// - Else, brings the last accessed item at root.
function splay(root, key) {
// Base cases
if (root === null || root.key === key) return root; // bring last accessed element or founded element as root of left-left (sub)tree
// Grandparent start here
// Key lies in Left
if (key < root.key) {
// Key is not in tree
if (root.left === null) return root; // If not founded, Bring last accessed element root of left (sub)tree
// Parent start here
// Zig-Zig (Left Left)
if (key < root.left.key) {
root.left.left = splay(root.left.left, key);
// Do first rotation for root, brind child as parent of subtree
root = rightRotate(root);
}
// Zig-Zag (Left Right)
else if (key > root.left.key) {
root.left.right = splay(root.left.right, key);
// Do first rotation for root.left, brind child as parent of subtree
if (root.left.right != null) root.left = leftRotate(root.left);
}
// 1 cong 2 viec
// 1. Do second rotation, bring child as grandparent of subtree
// 2. Bring parent (level 2) as root of tree when last recursive splay() finish
return rightRotate(root);
// Parent end
}
// Key lies in Right
else {
if (root.right === null) return root;
// Parent start here
// Zag-Zag (Right Right)
if (key > root.right.key) {
root.right.right = splay(root.right.right, key);
root = leftRotate(root);
}
// Zag-Zig (Right Left)
else if (key < root.right.key) {
root.right.left = splay(root.right.left, key);
if (root.right.left != null) root.right = rightRotate(root.right);
}
return leftRotate(root);
// End parent
}
// Grandparent end
}
// The search function for Splay tree.
// This function returns the new root of Splay Tree.
// If key is present in tree then, it is moved to root.
// else, last accessed element is moved to root
function search(root, key) {
return splay(root, key);
}
// A utility function to print
// preorder traversal of the tree.
// The function also prints height of every node
function preOrder(root) {
if (root != null) {
console.log(root.key);
preOrder(root.left);
preOrder(root.right);
}
}
// Right-skewed tree for Zag-zag and Zag-zig test
// Using root2 to console.log in other function like splay, search (because they have argument name "root")
let root2 = new Node(10);
root2.right = new Node(15);
root2.right.right = new Node(16);
root2.right.right.right = new Node(20);
root2.right.right.right.right = new Node(21);
root2.right.right.right.right.right = new Node(22);
root2 = splay(root2, 20);
console.log(root2)
Assume we search for node 20. The rotation should happen as follow:
Zag-zag rotation: Replace node 15 with 20.
Zag rotation: Replace node 10 with 20
However, my code result is:
Demo of image used this
Both your algorithm and the imaged algorithm perform double rotations correctly, every time taking a pair of edges on the path to the target node, and applying a double rotation on that pair.
However, when the path to the target node has an odd length, then there is one edge that will undergo a single rotation. The choice of this single edge is different:
your algorithm will "split" the path in pairs starting from the root node, treating the remaining single edge at the end of the path separately.
the imaged algorithm will "split" the path in pairs starting from the target node, treating the remaining single edge at the start of the path (at the root) separately.
Here is your code aligned with that second strategy:
function splay(root, key) {
function splaySub(root) {
if (!root) throw new RangeError; // Value not found in tree
if (root.key === key) return root;
let side = key < root.key ? "left" : "right";
root[side] = splaySub(root[side]);
// Check if odd: then caller to deal with rotation
if (root[side].key === key) return root;
// Apply a double rotation, top-down:
root = key < root.key ? rightRotate(root) : leftRotate(root);
return key < root.key ? rightRotate(root) : leftRotate(root);
}
try {
root = splaySub(root);
return !root || root.key === key
// Path had even length: all OK
? root
// Odd length: Perform a final, single rotation
: key < root.key ? rightRotate(root) : leftRotate(root);
} catch(e) {
if (!(e instanceof RangeError)) throw e;
return root; // Not found: return original tree
}
}
When the searched value is not in the tree, this code will trigger an Exception, so to exit quickly out of recursion without any update to the tree. In this case that approach makes the code a bit cleaner (fewer checks for null values...).
Addendum
As in comments you explained that the splay function should also bring a node to the top when it doesn't find the value, I provide here the updated code. I took the opportunity to turn the code into more OOP style, so you'll find here some of your functions turned into methods:
class Node {
constructor(key, left=null, right=null) {
this.key = key;
this.left = left;
this.right = right;
}
* inOrder(depth=0) {
if (this.right) yield * this.right.inOrder(depth+1);
yield [depth, this.key];
if (this.left) yield * this.left.inOrder(depth+1);
}
_rotate(toRight) {
const [side, otherSide] = toRight ? ["right", "left"] : ["left", "right"];
const orig = this[otherSide];
this[otherSide] = orig[side];
orig[side] = this;
return orig;
}
rightRotate() {
return this._rotate(true);
}
leftRotate() {
return this._rotate(false);
}
insert(key) {
const side = key < this.key ? "left" : "right";
if (this[side]) return this[side].insert(key);
this[side] = new Node(key);
}
}
class SplayTree {
constructor(...values) {
this.root = null;
for (const value of values) this.insert(value);
}
insert(value) {
if (this.root) this.root.insert(value);
else this.root = new Node(value);
}
splay(key) {
if (!this.root) return;
function splaySub(root) {
if (root.key === key) return root;
const side = key < root.key ? "left" : "right";
// Not found? Then do as if we looked for current node's key
if (!root[side]) {
key = root.key; // Modifies the outer-scoped variable
return root;
}
root[side] = splaySub(root[side]);
// Check if odd: then caller to deal with rotation
if (root[side].key === key) return root;
// Apply a double rotation, top-down:
root = root._rotate(key < root.key);
return root._rotate(key < root.key);
}
this.root = splaySub(this.root);
if (this.root.key !== key) this.root = this.root._rotate(key < this.root.key);
}
search(key) {
this.splay(key);
}
* inOrder() {
if (this.root) yield * this.root.inOrder();
}
toString() {
return Array.from(tree.inOrder(), ([depth, key]) => " ".repeat(depth) + key).join("\n");
}
}
const tree = new SplayTree(10, 15, 16, 20, 21, 22);
console.log("Initial tree:");
console.log(tree.toString());
tree.search(19); // Not found, so it splays 20.
console.log("Final tree:");
console.log(tree.toString());

Min Stack Solution Error with Top Method?

Leetcode problem
My output for the input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
is
[null,null,null,null,-3,null,-3,-2]
whereas the expected is
[null,null,null,null,-3,null,0,-2]
I expect the "top" method is where my problem is but I can't figure out what I am doing wrong. Can someone point it out for me? I am using two stacks to solve the problem. One stack to push the inputs and a minStack that the inputs get pushed into by comparing its values to the values of the first stack.
/**
* initialize your data structure here.
*/
let MinStack = function() {
this.stack = new Stack();
this.minStack = new Stack();
};
/**
* #param {number} x
* #return {void}
*/
MinStack.prototype.push = function(x) {
this.stack.push(x);
if (this.minStack.size === 0) {
this.minStack.push(x);
} else if (x <= this.minStack.peek()) {
this.minStack.push(x);
}
};
/**
* #return {void}
*/
MinStack.prototype.pop = function() {
let popped = this.stack.peek();
if (popped === this.minStack.peek()) {
this.minStack.pop()
}
};
/**
* #return {number}
*/
MinStack.prototype.top = function() {
return this.stack.peek();
};
/**
* #return {number}
*/
MinStack.prototype.getMin = function() {
return this.minStack.peek();
};
class Stack {
constructor() {
this.storage = {};
this.size = 0;
}
push(val) {
this.storage[this.size] = val;
this.size++;
}
pop() {
let top = this.storage[this.size - 1];
delete this.storage[this.size - 1];
this.size--;
return top;
}
peek() {
return this.storage[this.size - 1];
}
getSize() {
return this.size;
}
empty() {
return this.size === 0;
}
}
Good question!
Not sure about your bug, we can just use the JavaScript array for this problem. This'll pass just fine:
var MinStack = function() {
this.stack = [];
};
MinStack.prototype.push = function(x) {
this.stack.push({
value: x,
min: this.stack.length === 0 ? x : Math.min(x, this.getMin()),
});
};
MinStack.prototype.pop = function() {
this.stack.pop();
};
MinStack.prototype.top = function() {
return this.stack[this.stack.length - 1].value;
};
MinStack.prototype.getMin = function() {
return this.stack[this.stack.length - 1].min;
};
If you like to use your own Stack(), plug it in the above code here:
this.stack = [];
and it should work fine. For that you're gonna have to write a min() method and I guess it would go like:
class MyOwnMinStack {
constructor() {
this.storage = {};
this.size = 0;
this.currMin = null
}
push(val) {
this.storage[this.size] = val;
this.size++;
}
pop() {
let top = this.storage[this.size - 1];
delete this.storage[this.size - 1];
this.size--;
return top;
}
peek() {
return this.storage[this.size - 1];
}
getSize() {
return this.size;
}
empty() {
return this.size === 0;
}
min() {
// To do
return this.currMin;
}
}
Every time we would push() or pop(), we'd keep track of this.currMin, such that we'd return it at constant time complexity O(1) once min() is called.
Here, I'll copy some other ways to solve the problem with other languages, might help you to figure it out. For example, this c++ method uses two stacks:
class MinStack {
private:
stack<int> stack_one;
stack<int> stack_two;
public:
void push(int x) {
stack_one.push(x);
if (stack_two.empty() || x <= getMin())
stack_two.push(x);
}
void pop() {
if (stack_one.top() == getMin())
stack_two.pop();
stack_one.pop();
}
int top() {
return stack_one.top();
}
int getMin() {
return stack_two.top();
}
};
Python
class MinStack:
def __init__(self):
self.stack = [(float('inf'), float('inf'))]
def push(self, x):
self.stack.append((x, min(x, self.stack[-1][1])))
def pop(self):
if len(self.stack) > 1:
self.stack.pop()
def top(self):
if len(self.stack) > 1:
return self.stack[-1][0]
return
def getMin(self):
if len(self.stack) > 1:
return self.stack[-1][1]
return
Java
class MinStack {
int min = Integer.MAX_VALUE;
Stack<Integer> stack = new Stack<Integer>();
public void push(int x) {
if (x <= min) {
stack.push(min);
min = x;
}
stack.push(x);
}
public void pop() {
if (stack.pop() == min)
min = stack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return min;
}
}
References
For additional details, you can see the Discussion Board. There are plenty of accepted solutions with a variety of languages and explanations, efficient algorithms, as well as asymptotic time/space complexity analysis1, 2 in there.

Implementing BST TREE DUPLICATES KEYS - JS

I'm trying to implement a self balancing tree (beginning with BST first ).
So i have multiple keys with same value. So i have decided to make primary and secondary comparison to place a value in a node.
My node structure looks like ->
var Node = function (value) {
this.fine = value.fine ; // primary comparison
this.index = value.index ; // secondary comparison
this.left = null ;
this.right = null ;
};
fine is int value and index is array index.
my BST insert looks like this->
function insert(root, data) {
if(root == null) {
root = new Node(data)
}
// base case for secondary comparison .
if(root.fine === data.fine ) {
if(root.index > data.index ) {
root.left = new Node(data) ;
} else {
root.right = new Node(data)
}
}
if(root.fine > data.fine ) {
root.left = insert(root.left, data) ;
} else if(root.fine < data.fine ) {
root.right = insert(root.right , data) ;
return root;
}
but i am getting MAXIMUM STACK CALL. i think the base case is not right! What should be the base case of this problem?

Issues with a recursive function when trying to create a BST using Pseudoclassical Inheritance

So I'm trying to create a Binary Search Tree using Pseudoclassical inheritance. It accepts an array, sorts it, uses the middle value as the starting point, and inserts the remaining values from the array into the BST. I guess I'm trying my best to utilize functional programming (correct me if I'm wrong please) by using reuseable methods and also because a BST insert method needs to be recursive.
I've pointed out where the code errors out. I believe it takes 3 as the initial value, I also believe 1 (the next value in the array) successfully gets inserted, but I believe the number 2 is where the error occurs when it says that "TypeError: this.left.insert is not a function". Can anyone point out what I'm doing wrong? Why won't the insert method call itself for this.left?
var NoDuplicatesBST = function(array) {
var tempArr = arguments[0].sort(function(a, b) {
return a-b;
});
var middle = Math.floor(((tempArr.length - 1) / 2));
var sliced = tempArr.splice(middle, 1);
this.createBST(sliced[0]);
// now insert the rest of tempArr into the BST
for (var i = 0; i < tempArr.length; i++) {
this.insert(tempArr[i]);
}
};
NoDuplicatesBST.prototype.createBST = function(number) {
this.value = number;
this.left = null;
this.right = null;
};
NoDuplicatesBST.prototype.insert = function(number) {
if (number < this.value) {
if (this.left === null) {
this.left = new this.createBST(number);
} else {
// ------------CODE BELOW DOES NOT WORK!, LINED 77 ALSO PROBABLY. TypeError: this.left.insert is not a function----------------------
this.left.insert(number);
}
} else if (number > this.value) {
if (this.right === null) {
this.right = new this.createBST(number);
} else {
this.right.insert(number);
}
} else {
// Do nothing
}
};
var testBST = new NoDuplicatesBST([2,3,4,5,1]);
console.log("The testBST:", testBST);
That's not written in functional way, take a look and try to go thru this tutorial to learn more about functional programming in JS: http://reactivex.io/learnrx/
And to the original question why you see the "TypeError: this.left.insert is not a function". Check my comments in your code:
var NoDuplicatesBST = function(arr) {
var middle, left = [], center, right = [];
if (!Array.isArray(arr) || arr.length == 0) {
return this;
}
if (arr.length == 1) {
center = arr[0];
} else {
middle = Math.floor((arr.length / 2));
center = arr[middle];
left = arr.slice(0, middle);
right = arr.slice(middle + 1, arr.length);
console.log('left:', left);
console.log('middle:', center);
console.log('right:', right);
}
this.createBST(center);
// now insert left and right parts to BST
if (left.length > 0) {
this.insert(left);
}
if (right.length > 0) {
this.insert(right);
}
};
NoDuplicatesBST.prototype.createBST = function(number) {
this.value = number;
this.left = null;
this.right = null;
};
NoDuplicatesBST.prototype.insert = function(arr) {
if (arr.length > 0) {
//array is sorted and we took the middle element, so we can compare just the first element
if (arr[0] < this.value) {
/** Here you use createBST as a constructor, it creates a new element,
with left and right values, but you break the prototypal inheritance chain,
that's why you don't have access to the insert function */
// this.left = new this.createBST(number);
// it's better to pass the part of the array to build the tree further
this.left = new NoDuplicatesBST(arr);
} else {
this.right = new NoDuplicatesBST(arr); //the same as above
}
}
};
var arr = [2, 3, 4, 5, 1];
var tempArr = arr.reduce(function (noDuplicatesArr, current) { //remove duplicates
if (noDuplicatesArr.indexOf(current) === -1) {
noDuplicatesArr.push(current);
}
return noDuplicatesArr;
}, []).sort(function(a, b) {
return a - b;
});
var testBST = new NoDuplicatesBST(tempArr);
console.log("The testBST:", testBST);
For prototypal chain inheritance check: https://developer.mozilla.org/en/docs/Web/JavaScript/Inheritance_and_the_prototype_chain
BTW. I changed your code to accept arrays instead of numbers, now that will build a BST

Canvas drawing using query/angular

Here's what I'm trying to achieve. Draw a circle(first circle) on the screen on a mouse click. Then draw successive circles on successive mouse clicks and connect each to the first circle.
I've managed to get till here.
Now the task is if any of the circles have the same y-coordinate as the first one, the connection is a straight line, else it should be a s-curve/inverted s-curve depending on whether the next circle is above or below the first one based on its y-axis.
It may be assumed that all successive circle will be on the right of the first circle.
Here's my code
var app = angular.module('plunker', []);
app.controller('MainController', function($scope) {
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
function reOffset(){
var BB=canvas.getBoundingClientRect();
offsetX=BB.left;
offsetY=BB.top;
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }
var isDown=false;
var startX,startY;
var radius=10;
var lastX,lastY;
ctx.fillStyle='red';
$("#canvas").mousedown(function(e){handleMouseDown(e);});
function drawCircle(cx,cy){
if(lastX){
ctx.globalCompositeOperation='destination-over';
ctx.beginPath();
ctx.moveTo(lastX,lastY);
ctx.lineTo(cx,cy);
ctx.stroke();
ctx.globalCompositeOperation='source-over';
}else{
lastX=cx;
lastY=cy;
}
ctx.beginPath();
ctx.arc(cx,cy,radius,0,Math.PI*2);
ctx.closePath();
ctx.fill();
}
function handleMouseDown(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
mx=parseInt(e.clientX-offsetX);
my=parseInt(e.clientY-offsetY);
drawCircle(mx,my);
}
});
Here's a link to the plunk that will demonstrate the behavior
http://plnkr.co/edit/rYVLgB14IutNh1F4MN6T?p=preview
Any help appreciated.
I don't know exactly which kind of s-curve are you interested in. As I understand it will be always only two points to connect, the first point and the rest, and you are looking for some sort of quadratic curve to do so. Under this situation you can build a s-curve by joining two ctx.quadraticCurveTo calls.
ctx.beginPath();
ctx.moveTo(lastX,lastY);
ctx.quadraticCurveTo(
(lastX+cx)/2, lastY,
(lastX+cx)/2, (lastY+cy)/2
);
ctx.quadraticCurveTo(
(lastX+cx)/2, cy,
cx, cy
);
ctx.lineWidth = 3;
http://plnkr.co/edit/t10cMPcUtX5ifkWi2LBF?p=preview
To make each of your connectors avoid existing circles, you must use a pathfinding algorithm (A* for example).
Pathfinding algorithms will give you a set of points from Circle1 to Circle2 that avoid all other circles.
Then you can use that set of points to build a connector between those circles using a Spline. See this very good answer by Stackoverflow's Ken Fyrstenberg on how to draw a spline. Make sure you keep the tension on the spline tight (closer to zero) so that your spline connector doesn't stray too far from the unobstructed path:
how to draw smooth curve through N points using javascript HTML5 canvas?
This is a nice script implementing the A* algorithm by Brian Grinstead:
https://github.com/bgrins/javascript-astar/
And here's a Demo of Brian Grinstead's A* script:
http://www.briangrinstead.com/files/astar/
To avoid a link-only answer, I'm attaching Brian's script from GitHub below...
But seriously...if GitHub disappears many of us subscribers are in trouble!
// javascript-astar 0.4.0
// http://github.com/bgrins/javascript-astar
// Freely distributable under the MIT License.
// Implements the astar search algorithm in javascript using a Binary Heap.
// Includes Binary Heap (with modifications) from Marijn Haverbeke.
// http://eloquentjavascript.net/appendix2.html
(function(definition) {
/* global module, define */
if(typeof module === 'object' && typeof module.exports === 'object') {
module.exports = definition();
} else if(typeof define === 'function' && define.amd) {
define([], definition);
} else {
var exports = definition();
window.astar = exports.astar;
window.Graph = exports.Graph;
}
})(function() {
function pathTo(node){
var curr = node,
path = [];
while(curr.parent) {
path.push(curr);
curr = curr.parent;
}
return path.reverse();
}
function getHeap() {
return new BinaryHeap(function(node) {
return node.f;
});
}
var astar = {
/**
* Perform an A* Search on a graph given a start and end node.
* #param {Graph} graph
* #param {GridNode} start
* #param {GridNode} end
* #param {Object} [options]
* #param {bool} [options.closest] Specifies whether to return the
path to the closest node if the target is unreachable.
* #param {Function} [options.heuristic] Heuristic function (see
* astar.heuristics).
*/
search: function(graph, start, end, options) {
graph.cleanDirty();
options = options || {};
var heuristic = options.heuristic || astar.heuristics.manhattan,
closest = options.closest || false;
var openHeap = getHeap(),
closestNode = start; // set the start node to be the closest if required
start.h = heuristic(start, end);
openHeap.push(start);
while(openHeap.size() > 0) {
// Grab the lowest f(x) to process next. Heap keeps this sorted for us.
var currentNode = openHeap.pop();
// End case -- result has been found, return the traced path.
if(currentNode === end) {
return pathTo(currentNode);
}
// Normal case -- move currentNode from open to closed, process each of its neighbors.
currentNode.closed = true;
// Find all neighbors for the current node.
var neighbors = graph.neighbors(currentNode);
for (var i = 0, il = neighbors.length; i < il; ++i) {
var neighbor = neighbors[i];
if (neighbor.closed || neighbor.isWall()) {
// Not a valid node to process, skip to next neighbor.
continue;
}
// The g score is the shortest distance from start to current node.
// We need to check if the path we have arrived at this neighbor is the shortest one we have seen yet.
var gScore = currentNode.g + neighbor.getCost(currentNode),
beenVisited = neighbor.visited;
if (!beenVisited || gScore < neighbor.g) {
// Found an optimal (so far) path to this node. Take score for node to see how good it is.
neighbor.visited = true;
neighbor.parent = currentNode;
neighbor.h = neighbor.h || heuristic(neighbor, end);
neighbor.g = gScore;
neighbor.f = neighbor.g + neighbor.h;
graph.markDirty(neighbor);
if (closest) {
// If the neighbour is closer than the current closestNode or if it's equally close but has
// a cheaper path than the current closest node then it becomes the closest node
if (neighbor.h < closestNode.h || (neighbor.h === closestNode.h && neighbor.g < closestNode.g)) {
closestNode = neighbor;
}
}
if (!beenVisited) {
// Pushing to heap will put it in proper place based on the 'f' value.
openHeap.push(neighbor);
}
else {
// Already seen the node, but since it has been rescored we need to reorder it in the heap
openHeap.rescoreElement(neighbor);
}
}
}
}
if (closest) {
return pathTo(closestNode);
}
// No result was found - empty array signifies failure to find path.
return [];
},
// See list of heuristics: http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html
heuristics: {
manhattan: function(pos0, pos1) {
var d1 = Math.abs(pos1.x - pos0.x);
var d2 = Math.abs(pos1.y - pos0.y);
return d1 + d2;
},
diagonal: function(pos0, pos1) {
var D = 1;
var D2 = Math.sqrt(2);
var d1 = Math.abs(pos1.x - pos0.x);
var d2 = Math.abs(pos1.y - pos0.y);
return (D * (d1 + d2)) + ((D2 - (2 * D)) * Math.min(d1, d2));
}
},
cleanNode:function(node){
node.f = 0;
node.g = 0;
node.h = 0;
node.visited = false;
node.closed = false;
node.parent = null;
}
};
/**
* A graph memory structure
* #param {Array} gridIn 2D array of input weights
* #param {Object} [options]
* #param {bool} [options.diagonal] Specifies whether diagonal moves are allowed
*/
function Graph(gridIn, options) {
options = options || {};
this.nodes = [];
this.diagonal = !!options.diagonal;
this.grid = [];
for (var x = 0; x < gridIn.length; x++) {
this.grid[x] = [];
for (var y = 0, row = gridIn[x]; y < row.length; y++) {
var node = new GridNode(x, y, row[y]);
this.grid[x][y] = node;
this.nodes.push(node);
}
}
this.init();
}
Graph.prototype.init = function() {
this.dirtyNodes = [];
for (var i = 0; i < this.nodes.length; i++) {
astar.cleanNode(this.nodes[i]);
}
};
Graph.prototype.cleanDirty = function() {
for (var i = 0; i < this.dirtyNodes.length; i++) {
astar.cleanNode(this.dirtyNodes[i]);
}
this.dirtyNodes = [];
};
Graph.prototype.markDirty = function(node) {
this.dirtyNodes.push(node);
};
Graph.prototype.neighbors = function(node) {
var ret = [],
x = node.x,
y = node.y,
grid = this.grid;
// West
if(grid[x-1] && grid[x-1][y]) {
ret.push(grid[x-1][y]);
}
// East
if(grid[x+1] && grid[x+1][y]) {
ret.push(grid[x+1][y]);
}
// South
if(grid[x] && grid[x][y-1]) {
ret.push(grid[x][y-1]);
}
// North
if(grid[x] && grid[x][y+1]) {
ret.push(grid[x][y+1]);
}
if (this.diagonal) {
// Southwest
if(grid[x-1] && grid[x-1][y-1]) {
ret.push(grid[x-1][y-1]);
}
// Southeast
if(grid[x+1] && grid[x+1][y-1]) {
ret.push(grid[x+1][y-1]);
}
// Northwest
if(grid[x-1] && grid[x-1][y+1]) {
ret.push(grid[x-1][y+1]);
}
// Northeast
if(grid[x+1] && grid[x+1][y+1]) {
ret.push(grid[x+1][y+1]);
}
}
return ret;
};
Graph.prototype.toString = function() {
var graphString = [],
nodes = this.grid, // when using grid
rowDebug, row, y, l;
for (var x = 0, len = nodes.length; x < len; x++) {
rowDebug = [];
row = nodes[x];
for (y = 0, l = row.length; y < l; y++) {
rowDebug.push(row[y].weight);
}
graphString.push(rowDebug.join(" "));
}
return graphString.join("\n");
};
function GridNode(x, y, weight) {
this.x = x;
this.y = y;
this.weight = weight;
}
GridNode.prototype.toString = function() {
return "[" + this.x + " " + this.y + "]";
};
GridNode.prototype.getCost = function(fromNeighbor) {
// Take diagonal weight into consideration.
if (fromNeighbor && fromNeighbor.x != this.x && fromNeighbor.y != this.y) {
return this.weight * 1.41421;
}
return this.weight;
};
GridNode.prototype.isWall = function() {
return this.weight === 0;
};
function BinaryHeap(scoreFunction){
this.content = [];
this.scoreFunction = scoreFunction;
}
BinaryHeap.prototype = {
push: function(element) {
// Add the new element to the end of the array.
this.content.push(element);
// Allow it to sink down.
this.sinkDown(this.content.length - 1);
},
pop: function() {
// Store the first element so we can return it later.
var result = this.content[0];
// Get the element at the end of the array.
var end = this.content.pop();
// If there are any elements left, put the end element at the
// start, and let it bubble up.
if (this.content.length > 0) {
this.content[0] = end;
this.bubbleUp(0);
}
return result;
},
remove: function(node) {
var i = this.content.indexOf(node);
// When it is found, the process seen in 'pop' is repeated
// to fill up the hole.
var end = this.content.pop();
if (i !== this.content.length - 1) {
this.content[i] = end;
if (this.scoreFunction(end) < this.scoreFunction(node)) {
this.sinkDown(i);
}
else {
this.bubbleUp(i);
}
}
},
size: function() {
return this.content.length;
},
rescoreElement: function(node) {
this.sinkDown(this.content.indexOf(node));
},
sinkDown: function(n) {
// Fetch the element that has to be sunk.
var element = this.content[n];
// When at 0, an element can not sink any further.
while (n > 0) {
// Compute the parent element's index, and fetch it.
var parentN = ((n + 1) >> 1) - 1,
parent = this.content[parentN];
// Swap the elements if the parent is greater.
if (this.scoreFunction(element) < this.scoreFunction(parent)) {
this.content[parentN] = element;
this.content[n] = parent;
// Update 'n' to continue at the new position.
n = parentN;
}
// Found a parent that is less, no need to sink any further.
else {
break;
}
}
},
bubbleUp: function(n) {
// Look up the target element and its score.
var length = this.content.length,
element = this.content[n],
elemScore = this.scoreFunction(element);
while(true) {
// Compute the indices of the child elements.
var child2N = (n + 1) << 1,
child1N = child2N - 1;
// This is used to store the new position of the element, if any.
var swap = null,
child1Score;
// If the first child exists (is inside the array)...
if (child1N < length) {
// Look it up and compute its score.
var child1 = this.content[child1N];
child1Score = this.scoreFunction(child1);
// If the score is less than our element's, we need to swap.
if (child1Score < elemScore){
swap = child1N;
}
}
// Do the same checks for the other child.
if (child2N < length) {
var child2 = this.content[child2N],
child2Score = this.scoreFunction(child2);
if (child2Score < (swap === null ? elemScore : child1Score)) {
swap = child2N;
}
}
// If the element needs to be moved, swap it, and continue.
if (swap !== null) {
this.content[n] = this.content[swap];
this.content[swap] = element;
n = swap;
}
// Otherwise, we are done.
else {
break;
}
}
}
};
return {
astar: astar,
Graph: Graph
};
});

Categories