From 6fb12c20c1c0751ee141de7bb08c83e262f93a09 Mon Sep 17 00:00:00 2001 From: Ward Ruth Date: Mon, 1 Feb 2016 10:03:08 -0800 Subject: [PATCH 01/70] unecessary to re-set stack array in WeakMap since it is a pointer reference and has not been deleted. --- chapter03/01-Stack3.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/chapter03/01-Stack3.js b/chapter03/01-Stack3.js index fd490ffa..d13a87dd 100644 --- a/chapter03/01-Stack3.js +++ b/chapter03/01-Stack3.js @@ -11,13 +11,11 @@ let Stack3 = (function () { push(element){ let s = items.get(this); s.push(element); - items.set(this, s); } pop(){ let s = items.get(this); let r = s.pop(); - items.set(this, s); return r; } From ad6b7eb3306b442542ddcaa1e42e59b37f26da51 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Fri, 29 Jan 2016 09:51:19 -0200 Subject: [PATCH 02/70] updated code chapter 5 - linked lists --- .../{01-Linked-List.js => 01-LinkedList.js} | 18 +++++++-------- chapter05/02-UsingLinkedLists.html | 3 ++- chapter05/02-UsingLinkedLists.js | 2 +- chapter05/03-Doubly-Linked-List.js | 22 +++++++++---------- chapter05/04-UsingDoublyLinkedLists.js | 2 +- chapter05/05-CircularLinkedList.js | 18 +++++++-------- chapter05/06-UsingCircularLinkedList.js | 2 +- ...06-UsingHashCollisionSeparateChaining.html | 2 +- 8 files changed, 35 insertions(+), 34 deletions(-) rename chapter05/{01-Linked-List.js => 01-LinkedList.js} (90%) diff --git a/chapter05/01-Linked-List.js b/chapter05/01-LinkedList.js similarity index 90% rename from chapter05/01-Linked-List.js rename to chapter05/01-LinkedList.js index d4f4637f..99f3c81e 100644 --- a/chapter05/01-Linked-List.js +++ b/chapter05/01-LinkedList.js @@ -1,17 +1,17 @@ function LinkedList() { - var Node = function(element){ + let Node = function(element){ this.element = element; this.next = null; }; - var length = 0; - var head = null; + let length = 0; + let head = null; this.append = function(element){ - var node = new Node(element), + let node = new Node(element), current; if (head === null){ //first node on list @@ -37,7 +37,7 @@ function LinkedList() { //check for out-of-bounds values if (position >= 0 && position <= length){ - var node = new Node(element), + let node = new Node(element), current = head, previous, index = 0; @@ -70,7 +70,7 @@ function LinkedList() { //check for out-of-bounds values if (position > -1 && position < length){ - var current = head, + let current = head, previous, index = 0; @@ -100,13 +100,13 @@ function LinkedList() { this.remove = function(element){ - var index = this.indexOf(element); + let index = this.indexOf(element); return this.removeAt(index); }; this.indexOf = function(element){ - var current = head, + let current = head, index = 0; while (current) { @@ -134,7 +134,7 @@ function LinkedList() { this.toString = function(){ - var current = head, + let current = head, string = ''; while (current) { diff --git a/chapter05/02-UsingLinkedLists.html b/chapter05/02-UsingLinkedLists.html index da977b75..0482b174 100644 --- a/chapter05/02-UsingLinkedLists.html +++ b/chapter05/02-UsingLinkedLists.html @@ -5,7 +5,8 @@ - + + \ No newline at end of file diff --git a/chapter05/02-UsingLinkedLists.js b/chapter05/02-UsingLinkedLists.js index 9c92c483..bef9d86e 100644 --- a/chapter05/02-UsingLinkedLists.js +++ b/chapter05/02-UsingLinkedLists.js @@ -1,4 +1,4 @@ -var list = new LinkedList(); +let list = new LinkedList2(); list.append(15); list.print(); console.log(list.indexOf(15)); diff --git a/chapter05/03-Doubly-Linked-List.js b/chapter05/03-Doubly-Linked-List.js index 1ca53298..6d4de9c5 100644 --- a/chapter05/03-Doubly-Linked-List.js +++ b/chapter05/03-Doubly-Linked-List.js @@ -1,19 +1,19 @@ function DoublyLinkedList() { - var Node = function(element){ + let Node = function(element){ this.element = element; this.next = null; this.prev = null; //NEW }; - var length = 0; - var head = null; - var tail = null; //NEW + let length = 0; + let head = null; + let tail = null; //NEW this.append = function(element){ - var node = new Node(element), + let node = new Node(element), current; if (head === null){ //first node on list @@ -35,7 +35,7 @@ function DoublyLinkedList() { //check for out-of-bounds values if (position >= 0 && position <= length){ - var node = new Node(element), + let node = new Node(element), current = head, previous, index = 0; @@ -84,7 +84,7 @@ function DoublyLinkedList() { //check for out-of-bounds values if (position > -1 && position < length){ - var current = head, + let current = head, previous, index = 0; @@ -130,13 +130,13 @@ function DoublyLinkedList() { this.remove = function(element){ - var index = this.indexOf(element); + let index = this.indexOf(element); return this.removeAt(index); }; this.indexOf = function(element){ - var current = head, + let current = head, index = -1; //check first item @@ -175,7 +175,7 @@ function DoublyLinkedList() { this.toString = function(){ - var current = head, + let current = head, s = current ? current.element : ''; while(current && current.next){ @@ -188,7 +188,7 @@ function DoublyLinkedList() { this.inverseToString = function() { - var current = tail, + let current = tail, s = current ? current.element : ''; while(current && current.prev){ diff --git a/chapter05/04-UsingDoublyLinkedLists.js b/chapter05/04-UsingDoublyLinkedLists.js index 00534d49..ffd8aacb 100644 --- a/chapter05/04-UsingDoublyLinkedLists.js +++ b/chapter05/04-UsingDoublyLinkedLists.js @@ -1,4 +1,4 @@ -var list = new DoublyLinkedList(); +let list = new DoublyLinkedList(); list.append(15); list.print(); diff --git a/chapter05/05-CircularLinkedList.js b/chapter05/05-CircularLinkedList.js index 590c08f4..06439c69 100644 --- a/chapter05/05-CircularLinkedList.js +++ b/chapter05/05-CircularLinkedList.js @@ -1,17 +1,17 @@ function CircularLinkedList() { - var Node = function(element){ + let Node = function(element){ this.element = element; this.next = null; }; - var length = 0; - var head = null; + let length = 0; + let head = null; this.append = function(element){ - var node = new Node(element), + let node = new Node(element), current; if (head === null){ //first node on list @@ -40,7 +40,7 @@ function CircularLinkedList() { //check for out-of-bounds values if (position >= 0 && position <= length){ - var node = new Node(element), + let node = new Node(element), current = head, previous, index = 0; @@ -84,7 +84,7 @@ function CircularLinkedList() { //check for out-of-bounds values if (position > -1 && position < length){ - var current = head, + let current = head, previous, index = 0; @@ -121,13 +121,13 @@ function CircularLinkedList() { this.remove = function(element){ - var index = this.indexOf(element); + let index = this.indexOf(element); return this.removeAt(index); }; this.indexOf = function(element){ - var current = head, + let current = head, index = -1; //check first item @@ -170,7 +170,7 @@ function CircularLinkedList() { this.toString = function(){ - var current = head, + let current = head, s = current.element; while(current.next !== head){ diff --git a/chapter05/06-UsingCircularLinkedList.js b/chapter05/06-UsingCircularLinkedList.js index 33d9f8c9..d3ad949a 100644 --- a/chapter05/06-UsingCircularLinkedList.js +++ b/chapter05/06-UsingCircularLinkedList.js @@ -1,4 +1,4 @@ -var circularLinkedList = new CircularLinkedList(); +let circularLinkedList = new CircularLinkedList(); circularLinkedList.append(15); circularLinkedList.print(); diff --git a/chapter07/06-UsingHashCollisionSeparateChaining.html b/chapter07/06-UsingHashCollisionSeparateChaining.html index e1741527..d671e133 100644 --- a/chapter07/06-UsingHashCollisionSeparateChaining.html +++ b/chapter07/06-UsingHashCollisionSeparateChaining.html @@ -5,7 +5,7 @@ - + From f375ff353bf371d7d21949a8148af68efa2b5a90 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 6 Feb 2016 10:46:04 -0200 Subject: [PATCH 03/70] removed unnecessary condition --- chapter05/05-CircularLinkedList.js | 4 ---- 1 file changed, 4 deletions(-) diff --git a/chapter05/05-CircularLinkedList.js b/chapter05/05-CircularLinkedList.js index 06439c69..5f05e85f 100644 --- a/chapter05/05-CircularLinkedList.js +++ b/chapter05/05-CircularLinkedList.js @@ -64,10 +64,6 @@ function CircularLinkedList() { } node.next = current; previous.next = node; - - if (node.next === null){ //update in case last element - node.next = head; - } } length++; //update size of list From 7641833b2bfe847178a7f8b651d5f9fc062f5fcd Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 6 Feb 2016 10:47:22 -0200 Subject: [PATCH 04/70] added LinkedList class in ES6 syntax --- chapter05/01-LinkedList2.js | 157 +++++++++++++++++++++++++++++++ chapter05/02-UsingLinkedLists.js | 2 +- 2 files changed, 158 insertions(+), 1 deletion(-) create mode 100644 chapter05/01-LinkedList2.js diff --git a/chapter05/01-LinkedList2.js b/chapter05/01-LinkedList2.js new file mode 100644 index 00000000..2a620ee7 --- /dev/null +++ b/chapter05/01-LinkedList2.js @@ -0,0 +1,157 @@ +let LinkedList2 = (function () { + + class Node { + constructor(element, priority){ + this.element = element; + this.next = null; + } + } + + let length = 0; + let head = null; + + class LinkedList2 { + + append(element) { + + let node = new Node(element), + current; + + if (head === null) { //first node on list + head = node; + } else { + + current = head; + + //loop the list until find last item + while (current.next) { + current = current.next; + } + + //get last item and assign next to added item to make the link + current.next = node; + } + + length++; //update size of list + } + + insert(position, element) { + + //check for out-of-bounds values + if (position >= 0 && position <= length) { + + let node = new Node(element), + current = head, + previous, + index = 0; + + if (position === 0) { //add on first position + + node.next = current; + head = node; + + } else { + while (index++ < position) { + previous = current; + current = current.next; + } + node.next = current; + previous.next = node; + } + + length++; //update size of list + + return true; + + } else { + return false; + } + } + + removeAt(position) { + + //check for out-of-bounds values + if (position > -1 && position < length) { + + let current = head, + previous, + index = 0; + + //removing first item + if (position === 0) { + head = current.next; + } else { + + while (index++ < position) { + + previous = current; + current = current.next; + } + + //link previous with current's next - skip it to remove + previous.next = current.next; + } + + length--; + + return current.element; + + } else { + return null; + } + } + + remove(element) { + + let index = this.indexOf(element); + return this.removeAt(index); + } + + indexOf(element) { + + let current = head, + index = 0; + + while (current) { + if (element === current.element) { + return index; + } + index++; + current = current.next; + } + + return -1; + } + + isEmpty() { + return length === 0; + } + + size() { + return length; + } + + getHead() { + return head; + } + + toString() { + + let current = head, + string = ''; + + while (current) { + string += current.element + (current.next ? '\n' : ''); + current = current.next; + } + return string; + + } + + print() { + console.log(this.toString()); + } + } + + return LinkedList2; +})(); diff --git a/chapter05/02-UsingLinkedLists.js b/chapter05/02-UsingLinkedLists.js index bef9d86e..fe917f4a 100644 --- a/chapter05/02-UsingLinkedLists.js +++ b/chapter05/02-UsingLinkedLists.js @@ -1,4 +1,4 @@ -let list = new LinkedList2(); +let list = new LinkedList(); list.append(15); list.print(); console.log(list.indexOf(15)); From 4c18af4ad070ea45ede4493a73598e90284d89b4 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 6 Feb 2016 11:20:07 -0200 Subject: [PATCH 05/70] added LinkedList class in ES6 syntax --- chapter05/01-LinkedList.js | 2 +- chapter05/01-LinkedList2.js | 64 ++++++++++++++++++++---------- chapter05/02-UsingLinkedLists.html | 4 +- chapter05/02-UsingLinkedLists.js | 2 +- 4 files changed, 46 insertions(+), 26 deletions(-) diff --git a/chapter05/01-LinkedList.js b/chapter05/01-LinkedList.js index 99f3c81e..3e52bc80 100644 --- a/chapter05/01-LinkedList.js +++ b/chapter05/01-LinkedList.js @@ -138,7 +138,7 @@ function LinkedList() { string = ''; while (current) { - string += current.element + (current.next ? '\n' : ''); + string += current.element + (current.next ? ', ' : ''); current = current.next; } return string; diff --git a/chapter05/01-LinkedList2.js b/chapter05/01-LinkedList2.js index 2a620ee7..0de3d5f2 100644 --- a/chapter05/01-LinkedList2.js +++ b/chapter05/01-LinkedList2.js @@ -1,27 +1,34 @@ let LinkedList2 = (function () { class Node { - constructor(element, priority){ + constructor(element){ this.element = element; this.next = null; } } - let length = 0; - let head = null; + const length = new WeakMap(); + const head = new WeakMap(); class LinkedList2 { + constructor () { + length.set(this, 0); + head.set(this, null); + } + append(element) { let node = new Node(element), - current; + current, + _head = this.getHead(); - if (head === null) { //first node on list - head = node; + if (_head === null) { //first node on list + _head = node; + head.set(this, _head); } else { - current = head; + current = _head; //loop the list until find last item while (current.next) { @@ -32,23 +39,28 @@ let LinkedList2 = (function () { current.next = node; } - length++; //update size of list + //update size of list + let l = this.size(); + l++; + length.set(this, l); } insert(position, element) { //check for out-of-bounds values - if (position >= 0 && position <= length) { + if (position >= 0 && position <= this.size()) { let node = new Node(element), - current = head, + _head = this.getHead(), + current = _head, previous, index = 0; if (position === 0) { //add on first position node.next = current; - head = node; + _head = node; + head.set(this, _head); } else { while (index++ < position) { @@ -59,7 +71,10 @@ let LinkedList2 = (function () { previous.next = node; } - length++; //update size of list + //update size of list + let l = this.size(); + l++; + length.set(this, l); return true; @@ -71,15 +86,17 @@ let LinkedList2 = (function () { removeAt(position) { //check for out-of-bounds values - if (position > -1 && position < length) { + if (position > -1 && position < this.size()) { - let current = head, + let _head = this.getHead(), + current = _head, previous, index = 0; //removing first item if (position === 0) { - head = current.next; + _head = current.next; + head.set(this, _head); } else { while (index++ < position) { @@ -92,7 +109,9 @@ let LinkedList2 = (function () { previous.next = current.next; } - length--; + let l = this.size(); + l--; + length.set(this, l); return current.element; @@ -109,7 +128,8 @@ let LinkedList2 = (function () { indexOf(element) { - let current = head, + let _head = this.getHead(), + current = _head, index = 0; while (current) { @@ -124,24 +144,24 @@ let LinkedList2 = (function () { } isEmpty() { - return length === 0; + return this.size() === 0; } size() { - return length; + return length.get(this); } getHead() { - return head; + return head.get(this); } toString() { - let current = head, + let current = this.getHead(), string = ''; while (current) { - string += current.element + (current.next ? '\n' : ''); + string += current.element + (current.next ? ', ' : ''); current = current.next; } return string; diff --git a/chapter05/02-UsingLinkedLists.html b/chapter05/02-UsingLinkedLists.html index 0482b174..97210e70 100644 --- a/chapter05/02-UsingLinkedLists.html +++ b/chapter05/02-UsingLinkedLists.html @@ -5,8 +5,8 @@ - + - + \ No newline at end of file diff --git a/chapter05/02-UsingLinkedLists.js b/chapter05/02-UsingLinkedLists.js index fe917f4a..bef9d86e 100644 --- a/chapter05/02-UsingLinkedLists.js +++ b/chapter05/02-UsingLinkedLists.js @@ -1,4 +1,4 @@ -let list = new LinkedList(); +let list = new LinkedList2(); list.append(15); list.print(); console.log(list.indexOf(15)); From e0829621785cb4648e1893585e269514339edabe Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 6 Feb 2016 11:54:47 -0200 Subject: [PATCH 06/70] added LinkedList class in ES6 syntax --- chapter05/01-LinkedList2.js | 25 +++++++++---------------- 1 file changed, 9 insertions(+), 16 deletions(-) diff --git a/chapter05/01-LinkedList2.js b/chapter05/01-LinkedList2.js index 0de3d5f2..98452857 100644 --- a/chapter05/01-LinkedList2.js +++ b/chapter05/01-LinkedList2.js @@ -20,15 +20,13 @@ let LinkedList2 = (function () { append(element) { let node = new Node(element), - current, - _head = this.getHead(); + current; - if (_head === null) { //first node on list - _head = node; - head.set(this, _head); + if (this.getHead() === null) { //first node on list + head.set(this, node); } else { - current = _head; + current = this.getHead(); //loop the list until find last item while (current.next) { @@ -51,16 +49,14 @@ let LinkedList2 = (function () { if (position >= 0 && position <= this.size()) { let node = new Node(element), - _head = this.getHead(), - current = _head, + current = this.getHead(), previous, index = 0; if (position === 0) { //add on first position node.next = current; - _head = node; - head.set(this, _head); + head.set(this, node); } else { while (index++ < position) { @@ -88,15 +84,13 @@ let LinkedList2 = (function () { //check for out-of-bounds values if (position > -1 && position < this.size()) { - let _head = this.getHead(), - current = _head, + let current = this.getHead(), previous, index = 0; //removing first item if (position === 0) { - _head = current.next; - head.set(this, _head); + head.set(this, current.next); } else { while (index++ < position) { @@ -128,8 +122,7 @@ let LinkedList2 = (function () { indexOf(element) { - let _head = this.getHead(), - current = _head, + let current = this.getHead(), index = 0; while (current) { From fef6ca261ce39b230edb1a4a3ad6b4c291d36adf Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 6 Feb 2016 12:00:38 -0200 Subject: [PATCH 07/70] added DoublyLinkedList class in ES6 syntax --- ...-Linked-List.js => 03-DoublyLinkedList.js} | 0 chapter05/03-DoublyLinkedList2.js | 242 ++++++++++++++++++ chapter05/04-UsingDoublyLinkedLists.html | 5 +- chapter05/04-UsingDoublyLinkedLists.js | 2 +- 4 files changed, 246 insertions(+), 3 deletions(-) rename chapter05/{03-Doubly-Linked-List.js => 03-DoublyLinkedList.js} (100%) create mode 100644 chapter05/03-DoublyLinkedList2.js diff --git a/chapter05/03-Doubly-Linked-List.js b/chapter05/03-DoublyLinkedList.js similarity index 100% rename from chapter05/03-Doubly-Linked-List.js rename to chapter05/03-DoublyLinkedList.js diff --git a/chapter05/03-DoublyLinkedList2.js b/chapter05/03-DoublyLinkedList2.js new file mode 100644 index 00000000..3ddbcb33 --- /dev/null +++ b/chapter05/03-DoublyLinkedList2.js @@ -0,0 +1,242 @@ +let DoublyLinkedList2 = (function () { + + class Node { + constructor(element) { + this.element = element; + this.next = null; + this.prev = null; //NEW + } + } + + const length = new WeakMap(); + const head = new WeakMap(); + const tail = new WeakMap(); //NEW + + class DoublyLinkedList2 { + + constructor () { + length.set(this, 0); + head.set(this, null); + tail.set(this, null); + } + + append = function (element) { + + let node = new Node(element), + current, _tail; + + if (this.getHead() === null) { //first node on list + head.set(this, node); + tail.set(this, node); //NEW + } else { + //attach to the tail node //NEW + _tail = this.getTail(); + _tail.next = node; + node.prev = _tail; + tail.set(this, node); + } + + //update size of list + let l = this.size(); + l++; + length.set(this, l); + } + + insert = function (position, element) { + + //check for out-of-bounds values + if (position >= 0 && position <= this.size()) { + + let node = new Node(element), + current = this.getHead(), + previous, + index = 0; + + if (position === 0) { //add on first position + + if (!this.getHead()) { //NEW + head.set(this, node); + tail.set(this, node); + } else { + node.next = current; + current.prev = node; //NEW {1} + head.set(this, node); + } + + } else if (position === this.size()) { //last item //NEW + + current = tail; // {2} + current.next = node; + node.prev = current; + tail.set(this, node); + + } else { + while (index++ < position) { //{3} + previous = current; + current = current.next; + } + node.next = current; + previous.next = node; + + current.prev = node; //NEW + node.prev = previous; //NEW + } + + //update size of list + let l = this.size(); + l++; + length.set(this, l); + + return true; + + } else { + return false; + } + } + + removeAt = function (position) { + + //check for out-of-bounds values + if (position > -1 && position < this.size()) { + + let _head = this.getHead(), + _tail = this.getTail(), + current = _head, + previous, + index = 0; + + //removing first item + if (position === 0) { + + _head = current.next; // {1} + + //if there is only one item, then we update tail as well //NEW + if (this.size() === 1) { // {2} + _tail = null; + } else { + _head.prev = null; // {3} + } + + } else if (position === this.size() - 1) { //last item //NEW + + current = _tail; // {4} + _tail = current.prev; + _tail.next = null; + + } else { + + while (index++ < position) { // {5} + + previous = current; + current = current.next; + } + + //link previous with current's next - skip it to remove + previous.next = current.next; // {6} + current.next.prev = previous; //NEW + } + + head.set(this,_head); + tail.set(this,_tail); + + //update size of list + let l = this.size(); + l--; + length.set(this, l); + + return current.element; + + } else { + return null; + } + } + + remove = function (element) { + + let index = this.indexOf(element); + return this.removeAt(index); + } + + indexOf = function (element) { + + let current = this.getHead(), + index = -1; + + //check first item + if (element == current.element) { + return 0; + } + + index++; + + //check in the middle of the list + while (current.next) { + + if (element == current.element) { + return index; + } + + current = current.next; + index++; + } + + //check last item + if (element == current.element) { + return index; + } + + return -1; + } + + isEmpty() { + return this.size() === 0; + } + + size() { + return length.get(this); + } + + toString = function () { + + let current = this.getHead(), + s = current ? current.element : ''; + + while (current && current.next) { + current = current.next; + s += ', ' + current.element; + } + + return s; + } + + inverseToString = function () { + + let current = this.getTail(), + s = current ? current.element : ''; + + while (current && current.prev) { + current = current.prev; + s += ', ' + current.element; + } + + return s; + } + + print = function () { + console.log(this.toString()); + } + + printInverse = function () { + console.log(this.inverseToString()); + } + + getHead() { + return head.get(this); + } + + getTail = function () { + return tail.get(this); + } + } + return DoublyLinkedList2; +})(); \ No newline at end of file diff --git a/chapter05/04-UsingDoublyLinkedLists.html b/chapter05/04-UsingDoublyLinkedLists.html index d4b60521..58f959d5 100644 --- a/chapter05/04-UsingDoublyLinkedLists.html +++ b/chapter05/04-UsingDoublyLinkedLists.html @@ -5,7 +5,8 @@ - - + + + \ No newline at end of file diff --git a/chapter05/04-UsingDoublyLinkedLists.js b/chapter05/04-UsingDoublyLinkedLists.js index ffd8aacb..9ad4a17c 100644 --- a/chapter05/04-UsingDoublyLinkedLists.js +++ b/chapter05/04-UsingDoublyLinkedLists.js @@ -1,4 +1,4 @@ -let list = new DoublyLinkedList(); +let list = new DoublyLinkedList2(); list.append(15); list.print(); From f6332b4a6a91586d9d32169fbdcfb63a36aa48d7 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 6 Feb 2016 12:56:21 -0200 Subject: [PATCH 08/70] added DoublyLinkedList class in ES6 syntax --- chapter05/03-DoublyLinkedList2.js | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/chapter05/03-DoublyLinkedList2.js b/chapter05/03-DoublyLinkedList2.js index 3ddbcb33..9fe7d87b 100644 --- a/chapter05/03-DoublyLinkedList2.js +++ b/chapter05/03-DoublyLinkedList2.js @@ -20,7 +20,7 @@ let DoublyLinkedList2 = (function () { tail.set(this, null); } - append = function (element) { + append(element) { let node = new Node(element), current, _tail; @@ -42,7 +42,7 @@ let DoublyLinkedList2 = (function () { length.set(this, l); } - insert = function (position, element) { + insert(position, element) { //check for out-of-bounds values if (position >= 0 && position <= this.size()) { @@ -94,7 +94,7 @@ let DoublyLinkedList2 = (function () { } } - removeAt = function (position) { + removeAt(position) { //check for out-of-bounds values if (position > -1 && position < this.size()) { @@ -151,13 +151,13 @@ let DoublyLinkedList2 = (function () { } } - remove = function (element) { + remove(element) { let index = this.indexOf(element); return this.removeAt(index); } - indexOf = function (element) { + indexOf(element) { let current = this.getHead(), index = -1; @@ -196,7 +196,7 @@ let DoublyLinkedList2 = (function () { return length.get(this); } - toString = function () { + toString() { let current = this.getHead(), s = current ? current.element : ''; @@ -209,7 +209,7 @@ let DoublyLinkedList2 = (function () { return s; } - inverseToString = function () { + inverseToString() { let current = this.getTail(), s = current ? current.element : ''; @@ -222,11 +222,11 @@ let DoublyLinkedList2 = (function () { return s; } - print = function () { + print() { console.log(this.toString()); } - printInverse = function () { + printInverse() { console.log(this.inverseToString()); } @@ -234,7 +234,7 @@ let DoublyLinkedList2 = (function () { return head.get(this); } - getTail = function () { + getTail() { return tail.get(this); } } From d69668f7346766db7b77c67ecb113e799b7d49b2 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 6 Feb 2016 12:56:36 -0200 Subject: [PATCH 09/70] added CircularLinkedList class in ES6 syntax --- chapter05/05-CircularLinkedList2.js | 201 ++++++++++++++++++++++ chapter05/06-UsingCircularLinkedList.html | 5 +- chapter05/06-UsingCircularLinkedList.js | 6 +- 3 files changed, 207 insertions(+), 5 deletions(-) create mode 100644 chapter05/05-CircularLinkedList2.js diff --git a/chapter05/05-CircularLinkedList2.js b/chapter05/05-CircularLinkedList2.js new file mode 100644 index 00000000..f054725f --- /dev/null +++ b/chapter05/05-CircularLinkedList2.js @@ -0,0 +1,201 @@ +let CircularLinkedList2 = (function () { + + class Node { + constructor(element) { + this.element = element; + this.next = null; + } + } + + const length = new WeakMap(); + const head = new WeakMap(); + + class CircularLinkedList2 { + + constructor () { + length.set(this, 0); + head.set(this, null); + } + + append(element) { + + let node = new Node(element), + current; + + if (this.getHead() === null) { //first node on list + head.set(this, node); + } else { + + current = this.getHead(); + + //loop the list until find last item + while (current.next !== this.getHead()) { //last element will be head instead of NULL + current = current.next; + } + + //get last item and assign next to added item to make the link + current.next = node; + } + + //set node.next to head - to have circular list + node.next = this.getHead(); + + //update size of list + let l = this.size(); + l++; + length.set(this, l); + } + + insert(position, element) { + + //check for out-of-bounds values + if (position >= 0 && position <= this.size()) { + + let node = new Node(element), + current = this.getHead(), + previous, + index = 0; + + if (position === 0) { //add on first position + + node.next = current; + + //update last element + while (current.next !== head) { //last element will be head instead of NULL + current = current.next; + } + + head.set(this, node); + current.next = this.getHead(); + + } else { + while (index++ < position) { + previous = current; + current = current.next; + } + node.next = current; + previous.next = node; + } + + //update size of list + let l = this.size(); + l++; + length.set(this, l); + + return true; + + } else { + return false; + } + } + + removeAt(position) { + + //check for out-of-bounds values + if (position > -1 && position < this.size()) { + + let current = this.getHead(), + previous, + index = 0; + + //removing first item + if (position === 0) { + + while (current.next !== head) { //needs to update last element first + current = current.next; + } + + head.set(this, this.getHead().next); + current.next = this.getHead(); + + } else { //no need to update last element for circular list + + while (index++ < position) { + + previous = current; + current = current.next; + } + + //link previous with current's next - skip it to remove + previous.next = current.next; + } + + let l = this.size(); + l--; + length.set(this, l); + + return current.element; + + } else { + return null; + } + } + + remove(element) { + + let index = indexOf(element); + return removeAt(index); + } + + indexOf(element) { + + let current = this.getHead(), + index = -1; + + //check first item + if (element == current.element) { + return 0; + } + + index++; + + //check in the middle of the list + while (current.next !== this.getHead()) { + + if (element == current.element) { + return index; + } + + current = current.next; + index++; + } + + //check last item + if (element == current.element) { + return index; + } + + return -1; + } + + isEmpty() { + return this.size() === 0; + } + + size() { + return length.get(this); + } + + getHead() { + return head.get(this); + } + + toString() { + + let current = this.getHead(), + s = current.element; + + while (current.next !== this.getHead()) { + current = current.next; + s += ', ' + current.element; + } + + return s.toString(); + } + + print() { + console.log(this.toString()); + } + } + return CircularLinkedList2; +})(); \ No newline at end of file diff --git a/chapter05/06-UsingCircularLinkedList.html b/chapter05/06-UsingCircularLinkedList.html index 5a2fbb5d..ab39ba27 100644 --- a/chapter05/06-UsingCircularLinkedList.html +++ b/chapter05/06-UsingCircularLinkedList.html @@ -5,7 +5,8 @@ - - + + + \ No newline at end of file diff --git a/chapter05/06-UsingCircularLinkedList.js b/chapter05/06-UsingCircularLinkedList.js index d3ad949a..bbe8705c 100644 --- a/chapter05/06-UsingCircularLinkedList.js +++ b/chapter05/06-UsingCircularLinkedList.js @@ -1,6 +1,6 @@ -let circularLinkedList = new CircularLinkedList(); +let circularLinkedList = new CircularLinkedList2(); -circularLinkedList.append(15); +/*circularLinkedList.append(15); circularLinkedList.print(); circularLinkedList.append(16); @@ -25,4 +25,4 @@ circularLinkedList.removeAt(2); circularLinkedList.print(); console.log(circularLinkedList.indexOf(14.5)); -console.log(circularLinkedList.indexOf(16)); \ No newline at end of file +console.log(circularLinkedList.indexOf(16));*/ \ No newline at end of file From 5ebda8633dd162af6a49d1010d5c957d29acf8c3 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 6 Feb 2016 13:03:10 -0200 Subject: [PATCH 10/70] added CircularLinkedList class in ES6 syntax --- chapter05/05-CircularLinkedList2.js | 6 +++--- chapter05/06-UsingCircularLinkedList.js | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/chapter05/05-CircularLinkedList2.js b/chapter05/05-CircularLinkedList2.js index f054725f..13f36665 100644 --- a/chapter05/05-CircularLinkedList2.js +++ b/chapter05/05-CircularLinkedList2.js @@ -56,12 +56,12 @@ let CircularLinkedList2 = (function () { previous, index = 0; - if (position === 0) { //add on first position + if (position === 0) { //add on first position node.next = current; //update last element - while (current.next !== head) { //last element will be head instead of NULL + while (current.next !== this.getHead()) { //last element will be head instead of NULL current = current.next; } @@ -101,7 +101,7 @@ let CircularLinkedList2 = (function () { //removing first item if (position === 0) { - while (current.next !== head) { //needs to update last element first + while (current.next !== this.getHead()) { //needs to update last element first current = current.next; } diff --git a/chapter05/06-UsingCircularLinkedList.js b/chapter05/06-UsingCircularLinkedList.js index bbe8705c..a1feebbb 100644 --- a/chapter05/06-UsingCircularLinkedList.js +++ b/chapter05/06-UsingCircularLinkedList.js @@ -1,6 +1,6 @@ let circularLinkedList = new CircularLinkedList2(); -/*circularLinkedList.append(15); +circularLinkedList.append(15); circularLinkedList.print(); circularLinkedList.append(16); @@ -25,4 +25,4 @@ circularLinkedList.removeAt(2); circularLinkedList.print(); console.log(circularLinkedList.indexOf(14.5)); -console.log(circularLinkedList.indexOf(16));*/ \ No newline at end of file +console.log(circularLinkedList.indexOf(16)); \ No newline at end of file From dad7fdd8abe7583763398194e26e74da1085da3e Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 6 Feb 2016 13:06:55 -0200 Subject: [PATCH 11/70] rmeoved unnecessary code from Stack --- chapter03/02-UsingStacks.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/chapter03/02-UsingStacks.js b/chapter03/02-UsingStacks.js index a84703a3..9876e892 100644 --- a/chapter03/02-UsingStacks.js +++ b/chapter03/02-UsingStacks.js @@ -1,4 +1,4 @@ -let stack = new Stack2(); +let stack = new Stack3(); console.log(stack.isEmpty()); //outputs true stack.push(5); stack.push(8); @@ -15,10 +15,10 @@ let stack = new Stack2(); //how to ensure true privacy //in case using Stack 2 uncomment code below -let objectSymbols = Object.getOwnPropertySymbols(stack); +/*let objectSymbols = Object.getOwnPropertySymbols(stack); console.log(objectSymbols.length); // 1 console.log(objectSymbols); // [Symbol()] console.log(objectSymbols[0]); // Symbol() stack[objectSymbols[0]].push(1); - stack.print(); //5, 8, 1 \ No newline at end of file + stack.print(); //5, 8, 1*/ \ No newline at end of file From d0eacadadc999bef67af37b03a09369e23d303ec Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 6 Feb 2016 13:07:11 -0200 Subject: [PATCH 12/70] rmeoved unnecessary code from Queue ES6 code --- chapter04/01-Queue2.js | 2 -- chapter04/02-UsingQueues.js | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/chapter04/01-Queue2.js b/chapter04/01-Queue2.js index c35ea102..d4bc9891 100644 --- a/chapter04/01-Queue2.js +++ b/chapter04/01-Queue2.js @@ -11,13 +11,11 @@ let Queue2 = (function () { enqueue(element) { let q = items.get(this); q.push(element); - items.set(this, q) } dequeue() { let q = items.get(this); let r = q.shift(); - items.set(this, q); return r; } diff --git a/chapter04/02-UsingQueues.js b/chapter04/02-UsingQueues.js index 1b3f58ae..5411bad6 100644 --- a/chapter04/02-UsingQueues.js +++ b/chapter04/02-UsingQueues.js @@ -1,4 +1,4 @@ -let queue = new Queue(); +let queue = new Queue2(); console.log(queue.isEmpty()); //outputs true queue.enqueue("John"); queue.enqueue("Jack"); From f3fef3b67eb9d1ca305ac3762c8b16188b7e5f6d Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Fri, 12 Feb 2016 09:19:56 -0200 Subject: [PATCH 13/70] replaced var with let --- chapter06/01-Set.js | 38 +++++++++++++++++++------------------- chapter06/02-UsingSets.js | 2 +- chapter06/03-Operations.js | 24 ++++++++++++------------ 3 files changed, 32 insertions(+), 32 deletions(-) diff --git a/chapter06/01-Set.js b/chapter06/01-Set.js index fa2148b7..48cf351b 100644 --- a/chapter06/01-Set.js +++ b/chapter06/01-Set.js @@ -6,7 +6,7 @@ */ function Set() { - var items = {}; + let items = {}; this.add = function(value){ if (!this.has(value)){ @@ -48,8 +48,8 @@ function Set() { * @returns {number} */ this.sizeLegacy = function(){ - var count = 0; - for(var key in items) { + let count = 0; + for(let key in items) { if(items.hasOwnProperty(key)) ++count; } @@ -62,16 +62,16 @@ function Set() { * @returns {Array} */ this.values = function(){ - var values = []; - for (var i=0, keys=Object.keys(items); i otherSet.size()){ //{1} return false; } else { - var values = this.values(); - for (var i=0; i Date: Sat, 13 Feb 2016 11:33:36 -0200 Subject: [PATCH 14/70] updated readme - second edition --- README.md | 42 ++++++++++++++++++++++++------------------ 1 file changed, 24 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 9712708a..0e71c1d1 100644 --- a/README.md +++ b/README.md @@ -3,26 +3,32 @@ Learning JavaScript Data Structures and Algorithms Source code of **Learning JavaScript Data Structures and Algorithms** book. -Book link: - - [Packt](https://www.packtpub.com/application-development/learning-javascript-data-structures-and-algorithms) - - [Amazon](http://www.amazon.com/gp/product/1783554878/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1783554878&linkCode=as2&tag=loiagron-20&linkId=7VBQ7OMJ47XY7MUV) +Book link - first edition: + - [Packt](https://www.packtpub.com/application-development/learning-javascript-data-structures-and-algorithms){:target="_blank"} + - [Amazon](http://www.amazon.com/gp/product/1783554878/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1783554878&linkCode=as2&tag=loiagron-20&linkId=7VBQ7OMJ47XY7MUV){:target="_blank"} -###List of Chapters: +### List of Chapters: -* 1: JAVASCRIPT – A QUICK OVERVIEW -* 2: ARRAYS -* 3: STACKS -* 4: QUEUES -* 5: LINKED LISTS -* 6: SETS -* 7: DICTIONARIES AND HASHES -* 8: TREES -* 9: GRAPHS -* 10: SORTING AND SEARCHING ALGORITHMS -* 11: More about Algorithms (Recursion, Dynamic Programing, Greedy Algorithms and Big-O Notation) - Extra chapter that can be donwloaded from [Packt](https://www.packtpub.com/application-development/learning-javascript-data-structures-and-algorithms) website -* Apendix A: Big-O Cheat Sheet - Extra chapter that can be donwloaded from [Packt](https://www.packtpub.com/application-development/learning-javascript-data-structures-and-algorithms) website - -###Found an issue or have a question? +* 01: [JavaScript: a quick overview](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter01) +* 02: [Arrays](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter02) +* 03: [Stacks](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter03) +* 04: [Queues](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter04) +* 05: [Linked Lists](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter05) +* 06: [Sets](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter06) +* 07: Dictionaries and Hashes +* 08: Trees +* 09: Graphs +* 10: Sorting and searching algorithms +* 11: Pattern of algorithms +* 12: More about algorithms +* 13: Functional programming and data structures + +### First Edition source code: + +Please refer to [this link](https://github.com/loiane/javascript-datastructures-algorithms/tree/master) + + +### Found an issue or have a question? Please create an [Issue](https://github.com/loiane/javascript-datastructures-algorithms/issues) or [Pull Request](https://github.com/loiane/javascript-datastructures-algorithms/pulls) From ddda1f9fbff8fa1bea1a5c59087523c8f46b9ade Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 13 Feb 2016 11:34:52 -0200 Subject: [PATCH 15/70] updated readme - second edition --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0e71c1d1..8f5df566 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,8 @@ Learning JavaScript Data Structures and Algorithms Source code of **Learning JavaScript Data Structures and Algorithms** book. Book link - first edition: - - [Packt](https://www.packtpub.com/application-development/learning-javascript-data-structures-and-algorithms){:target="_blank"} - - [Amazon](http://www.amazon.com/gp/product/1783554878/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1783554878&linkCode=as2&tag=loiagron-20&linkId=7VBQ7OMJ47XY7MUV){:target="_blank"} + - [Packt](https://www.packtpub.com/application-development/learning-javascript-data-structures-and-algorithms) + - [Amazon](http://www.amazon.com/gp/product/1783554878/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1783554878&linkCode=as2&tag=loiagron-20&linkId=7VBQ7OMJ47XY7MUV) ### List of Chapters: From 0035140e056cdfcb444f13c0a4cfafb11ca5749b Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 13 Feb 2016 11:46:08 -0200 Subject: [PATCH 16/70] replaced var - let --- chapter06/01-Set.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapter06/01-Set.js b/chapter06/01-Set.js index 48cf351b..3fa90281 100644 --- a/chapter06/01-Set.js +++ b/chapter06/01-Set.js @@ -16,7 +16,7 @@ function Set() { return false; }; - this.remove = function(value){ + this.delete = function(value){ if (this.has(value)){ delete items[value]; return true; From 03cab496ab25667e53c22355a8041838ca2812e4 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 13 Feb 2016 11:46:31 -0200 Subject: [PATCH 17/70] Set class in ES6 --- chapter06/01-Set2.js | 115 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 chapter06/01-Set2.js diff --git a/chapter06/01-Set2.js b/chapter06/01-Set2.js new file mode 100644 index 00000000..10e11b45 --- /dev/null +++ b/chapter06/01-Set2.js @@ -0,0 +1,115 @@ +let Set2 = (function () { + + const items = new WeakMap(); + + class Set2 { + + constructor () { + items.set(this, {}); + } + + add(value){ + if (!this.has(value)){ + let items_ = items.get(this); + items_[value] = value; + return true; + } + return false; + } + + delete(value){ + if (this.has(value)){ + let items_ = items.get(this); + delete items_[value]; + return true; + } + return false; + } + + has(value){ + let items_ = items.get(this); + return items_.hasOwnProperty(value); + } + + clear(){ + items.set(this, {}); + } + + size(){ + let items_ = items.get(this); + return Object.keys(items_).length; + } + + + values(){ + let values = []; + let items_ = items.get(this); + for (let i=0, keys=Object.keys(items_); i otherSet.size()){ + return false; + } else { + let values = this.values(); + for (let i=0; i Date: Sat, 13 Feb 2016 11:46:51 -0200 Subject: [PATCH 18/70] added Set ES6 class example --- chapter06/02-UsingSets.html | 5 +++-- chapter06/02-UsingSets.js | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/chapter06/02-UsingSets.html b/chapter06/02-UsingSets.html index 362b02ad..022d2177 100644 --- a/chapter06/02-UsingSets.html +++ b/chapter06/02-UsingSets.html @@ -5,7 +5,8 @@ - - + + + \ No newline at end of file diff --git a/chapter06/02-UsingSets.js b/chapter06/02-UsingSets.js index 08a4f164..e74269ac 100644 --- a/chapter06/02-UsingSets.js +++ b/chapter06/02-UsingSets.js @@ -11,8 +11,8 @@ console.log(set.has(2)); //true console.log(set.size()); //2 console.log(set.sizeLegacy()); //3 -set.remove(1); +set.delete(1); console.log(set.values()); //outputs [2] -set.remove(2); +set.delete(2); console.log(set.values()); //outputs [] \ No newline at end of file From d0aa9d55bc5e849fb29d51024ecb8d2ce1b35862 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 13 Feb 2016 11:47:00 -0200 Subject: [PATCH 19/70] examples using ES6 Set class --- chapter06/04-UsingES6Set.html | 10 +++++ chapter06/04-UsingES6Set.js | 71 +++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 chapter06/04-UsingES6Set.html create mode 100644 chapter06/04-UsingES6Set.js diff --git a/chapter06/04-UsingES6Set.html b/chapter06/04-UsingES6Set.html new file mode 100644 index 00000000..a08e635c --- /dev/null +++ b/chapter06/04-UsingES6Set.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/chapter06/04-UsingES6Set.js b/chapter06/04-UsingES6Set.js new file mode 100644 index 00000000..bd965bde --- /dev/null +++ b/chapter06/04-UsingES6Set.js @@ -0,0 +1,71 @@ +let set = new Set(); + +set.add(1); +console.log(set.values()); //outputs @Iterator +console.log(set.has(1)); //outputs true +console.log(set.size); //outputs 1 + +set.add(2); +console.log(set.values()); //outputs [1, 2] +console.log(set.has(2)); //true +console.log(set.size); //2 + +set.delete(1); +console.log(set.values()); //outputs [2] + +set.delete(2); +console.log(set.values()); //outputs [] + +let setA = new Set(); +setA.add(1); +setA.add(2); +setA.add(3); + +let setB = new Set(); +setB.add(2); +setB.add(3); +setB.add(4); + +//--------- Union ---------- +let unionAb = new Set(); +for (let x of setA) unionAb.add(x); +for (let x of setB) unionAb.add(x); +console.log(unionAb); + +//--------- Intersection ---------- +let intersection = function(setA, setB){ + let intersectionSet = new Set(); + + for (let x of setA){ + if (setB.has(x)){ + intersectionSet.add(x); + } + } + + return intersectionSet; +}; +let intersectionAB = intersection(setA, setB); +console.log(intersectionAB); + +//alternative - works on FF only +//intersectionAb = new Set([x for (x of setA) if (setB.has(x))]); +//console.log(intersectionAB); + +//--------- Difference ---------- +let difference = function(setA, setB){ + let intersectionSet = new Set(); + + for (let x of setA){ + if (!setB.has(x)){ + intersectionSet.add(x); + } + } + + return intersectionSet; +}; +let differenceAB = difference(setA, setB); +console.log(differenceAB); + +//alternative - works on FF only +//differenceAB = new Set([x for (x of setA) if (!setB.has(x))]); +//console.log(differenceAB); From f2a60c67267b8f786a42d458d0f3ded6ceaae106 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Tue, 16 Feb 2016 09:50:17 -0200 Subject: [PATCH 20/70] renamed variable --- chapter06/04-UsingES6Set.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/chapter06/04-UsingES6Set.js b/chapter06/04-UsingES6Set.js index bd965bde..a39e4100 100644 --- a/chapter06/04-UsingES6Set.js +++ b/chapter06/04-UsingES6Set.js @@ -53,15 +53,15 @@ console.log(intersectionAB); //--------- Difference ---------- let difference = function(setA, setB){ - let intersectionSet = new Set(); + let differenceSet = new Set(); for (let x of setA){ if (!setB.has(x)){ - intersectionSet.add(x); + differenceSet.add(x); } } - return intersectionSet; + return differenceSet; }; let differenceAB = difference(setA, setB); console.log(differenceAB); From 205098a4d2631afd9ca06fac170cdb62d51a1ac1 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Wed, 17 Feb 2016 09:34:29 -0200 Subject: [PATCH 21/70] ES6 Map example --- chapter07/09-ES6Map.html | 10 ++++++++++ chapter07/09-ES6Map.js | 17 +++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 chapter07/09-ES6Map.html create mode 100644 chapter07/09-ES6Map.js diff --git a/chapter07/09-ES6Map.html b/chapter07/09-ES6Map.html new file mode 100644 index 00000000..e755aac7 --- /dev/null +++ b/chapter07/09-ES6Map.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/chapter07/09-ES6Map.js b/chapter07/09-ES6Map.js new file mode 100644 index 00000000..5e0c9dae --- /dev/null +++ b/chapter07/09-ES6Map.js @@ -0,0 +1,17 @@ +var map = new Map(); + +map.set('Gandalf', 'gandalf@email.com'); +map.set('John', 'johnsnow@email.com'); +map.set('Tyrion', 'tyrion@email.com'); + +console.log(map.has('Gandalf')); //outputs true +console.log(map.size); //outputs 3 + +console.log(map.keys()); //outputs ["Gandalf", "John", "Tyrion"] +console.log(map.values()); //outputs ["gandalf@email.com", "johnsnow@email.com", "tyrion@email.com"] +console.log(map.get('Tyrion')); //outputs tyrion@email.com + +map.delete('John'); + +console.log(map.keys()); //outputs ["Gandalf", "Tyrion"] +console.log(map.values()); //outputs ["gandalf@email.com", "tyrion@email.com"] \ No newline at end of file From 208df800ff58ba7309344e01bafd378daf94bec2 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Fri, 19 Feb 2016 17:09:52 -0200 Subject: [PATCH 22/70] renamed method from remove to delete --- chapter07/01-Dictionaries.js | 2 +- chapter07/02-UsingDictionaries.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/chapter07/01-Dictionaries.js b/chapter07/01-Dictionaries.js index ea26cd05..a22ec419 100644 --- a/chapter07/01-Dictionaries.js +++ b/chapter07/01-Dictionaries.js @@ -6,7 +6,7 @@ function Dictionary(){ items[key] = value; //{1} }; - this.remove = function(key){ + this.delete = function(key){ if (this.has(key)){ delete items[key]; return true; diff --git a/chapter07/02-UsingDictionaries.js b/chapter07/02-UsingDictionaries.js index 3fc4db6f..3ec30d4b 100644 --- a/chapter07/02-UsingDictionaries.js +++ b/chapter07/02-UsingDictionaries.js @@ -11,7 +11,7 @@ console.log(dictionary.keys()); //outputs ["Gandalf", "John", "Tyrion"] console.log(dictionary.values()); //outputs ["gandalf@email.com", "johnsnow@email.com", "tyrion@email.com"] console.log(dictionary.get('Tyrion')); //outputs tyrion@email.com -dictionary.remove('John'); +dictionary.delete(‘John'); console.log(dictionary.keys()); //outputs ["Gandalf", "Tyrion"] console.log(dictionary.values()); //outputs ["gandalf@email.com", "tyrion@email.com"] From 331095647cffa89205d90944ea44854638460401 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 20 Feb 2016 09:59:14 -0200 Subject: [PATCH 23/70] ES6 WeakMap example --- chapter07/10-ES6WeakMap.html | 10 ++++++++++ chapter07/10-ES6WeakMap.js | 18 ++++++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 chapter07/10-ES6WeakMap.html create mode 100644 chapter07/10-ES6WeakMap.js diff --git a/chapter07/10-ES6WeakMap.html b/chapter07/10-ES6WeakMap.html new file mode 100644 index 00000000..25b28e2d --- /dev/null +++ b/chapter07/10-ES6WeakMap.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/chapter07/10-ES6WeakMap.js b/chapter07/10-ES6WeakMap.js new file mode 100644 index 00000000..8efa16b8 --- /dev/null +++ b/chapter07/10-ES6WeakMap.js @@ -0,0 +1,18 @@ +var map = new WeakMap(); + +var ob1 = {name:'Gandalf'}, + ob2 = {name:'John'}, + ob3 = {name:'Tyrion'}; + +map.set(ob1, 'gandalf@email.com'); +map.set(ob2, 'johnsnow@email.com'); +map.set(ob3, 'tyrion@email.com'); + +console.log(map.has(ob1)); //outputs true +console.log(map.has(ob2)); //outputs true +console.log(map.has(ob3)); //outputs true + +console.log(map.get(ob3)); //outputs tyrion@email.com + +map.delete(ob2); +console.log(map.has(ob2)); //outputs false From 4ffc29ae936e2b02942eed220efe21700a051a5a Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 20 Feb 2016 09:59:21 -0200 Subject: [PATCH 24/70] ES6 WeakSet example --- chapter07/11-ES6WeakSet.html | 10 ++++++++++ chapter07/11-ES6WeakSet.js | 16 ++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 chapter07/11-ES6WeakSet.html create mode 100644 chapter07/11-ES6WeakSet.js diff --git a/chapter07/11-ES6WeakSet.html b/chapter07/11-ES6WeakSet.html new file mode 100644 index 00000000..68710e76 --- /dev/null +++ b/chapter07/11-ES6WeakSet.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/chapter07/11-ES6WeakSet.js b/chapter07/11-ES6WeakSet.js new file mode 100644 index 00000000..e54a40de --- /dev/null +++ b/chapter07/11-ES6WeakSet.js @@ -0,0 +1,16 @@ +var set = new WeakSet(); + +var ob1 = {name:'Gandalf'}, + ob2 = {name:'John'}, + ob3 = {name:'Tyrion'}; + +set.add(ob1); +set.add(ob2); +set.add(ob3); + +console.log(set.has(ob1)); //outputs true +console.log(set.has(ob2)); //outputs true +console.log(set.has(ob3)); //outputs true + +set.delete(ob2); +console.log(set.has(ob2)); //outputs false From 75ad17e44f618a90fb1200a91f5d371030765722 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 20 Feb 2016 09:59:27 -0200 Subject: [PATCH 25/70] updated Readme --- README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.md b/README.md index 8f5df566..222adb3a 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,6 @@ Book link - first edition: - [Packt](https://www.packtpub.com/application-development/learning-javascript-data-structures-and-algorithms) - [Amazon](http://www.amazon.com/gp/product/1783554878/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1783554878&linkCode=as2&tag=loiagron-20&linkId=7VBQ7OMJ47XY7MUV) - ### List of Chapters: * 01: [JavaScript: a quick overview](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter01) @@ -16,7 +15,7 @@ Book link - first edition: * 04: [Queues](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter04) * 05: [Linked Lists](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter05) * 06: [Sets](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter06) -* 07: Dictionaries and Hashes +* 07: [Dictionaries and Hashes](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter07) * 08: Trees * 09: Graphs * 10: Sorting and searching algorithms @@ -28,7 +27,6 @@ Book link - first edition: Please refer to [this link](https://github.com/loiane/javascript-datastructures-algorithms/tree/master) - ### Found an issue or have a question? Please create an [Issue](https://github.com/loiane/javascript-datastructures-algorithms/issues) or [Pull Request](https://github.com/loiane/javascript-datastructures-algorithms/pulls) From fedf84ed9e9a0bb9dc470762af4423d302764819 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sun, 21 Feb 2016 14:04:50 -0300 Subject: [PATCH 26/70] removed type="text/javascript" --- chapter08/02-UsingBinarySearchTree.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chapter08/02-UsingBinarySearchTree.html b/chapter08/02-UsingBinarySearchTree.html index ed25a2c4..dd40cf48 100644 --- a/chapter08/02-UsingBinarySearchTree.html +++ b/chapter08/02-UsingBinarySearchTree.html @@ -5,7 +5,7 @@ - - + + \ No newline at end of file From 124f6680db4867abb2e16caa0cad543597ebcbe9 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 27 Feb 2016 15:56:38 -0300 Subject: [PATCH 27/70] AVL tree code --- chapter08/02-UsingBinarySearchTree.js | 6 +- chapter08/03-AVLTree.js | 149 ++++++++++++++++++++++++++ chapter08/04-UsingAVLTree.html | 4 +- chapter08/04-UsingAVLTree.js | 62 +++++++++++ 4 files changed, 218 insertions(+), 3 deletions(-) diff --git a/chapter08/02-UsingBinarySearchTree.js b/chapter08/02-UsingBinarySearchTree.js index 3caef17c..41f2c691 100644 --- a/chapter08/02-UsingBinarySearchTree.js +++ b/chapter08/02-UsingBinarySearchTree.js @@ -49,4 +49,8 @@ tree.remove(15); tree.inOrderTraverse(printNode); console.log('********* raw data structure ***********'); -console.log(tree.getRoot()); \ No newline at end of file +console.log(tree.getRoot()); + +console.log('********* printing HTML tree ***********'); +var parent = document.getElementsByTagName('body')[0]; +printHTMLTree(tree.getRoot(), parent, 255); \ No newline at end of file diff --git a/chapter08/03-AVLTree.js b/chapter08/03-AVLTree.js index e69de29b..2eed4f3e 100644 --- a/chapter08/03-AVLTree.js +++ b/chapter08/03-AVLTree.js @@ -0,0 +1,149 @@ +function AVLTree() { + + var Node = function(key){ + this.key = key; + this.left = null; + this.right = null; + }; + + var root = null; + + this.getRoot = function(){ + return root; + }; + + var heightNode = function(node) { + if (node === null) { + return -1; + } else { + return Math.max(heightNode(node.left), heightNode(node.right)) + 1; + } + }; + + var rotationLL = function(node) { + var tmp = node.left; + node.left = tmp.right; + tmp.right = node; + + return tmp; + }; + + var rotationRR = function(node) { + var tmp = node.right; + node.right = tmp.left; + tmp.left = node; + + return tmp; + }; + + var rotationLR = function(node) { + node.left = rotationRR(node.left); + return rotationLL(node); + }; + + var rotationRL = function(node) { + node.right = rotationLL(node.right); + return rotationRR(node); + }; + + var insertNode = function(node, element) { + + if (node === null) { + node = new Node(element); + + } else if (element < node.key) { + + node.left = insertNode(node.left, element); + + if (node.left !== null) { + + if ((heightNode(node.left) - heightNode(node.right)) > 1){ + if (element < node.left.key){ + node = rotationLL(node); + } else { + node = rotationLR(node); + } + } + } + } else if (element > node.key) { + + node.right = insertNode(node.right, element); + + if (node.right !== null) { + + if ((heightNode(node.right) - heightNode(node.left)) > 1){ + + if (element > node.right.key){ + node = rotationRR(node); + } else { + node = rotationRL(node); + } + } + } + } + + return node; + }; + + this.insert = function(element) { + root = insertNode(root, element); + }; + + var parentNode; + var nodeToBeDeleted; + + var removeNode = function(node, element) { + if (node === null) { + return null; + } + parentNode = node; + + if (element < node.key) { + node.left = removeNode(node.left, element); + } else { + nodeToBeDeleted = node; + node.right = removeNode(node.right, element); + } + + if (node === parentNode) { //remove node + if (nodeToBeDeleted !== null && element === nodeToBeDeleted.key) { + if (nodeToBeDeleted === parentNode) { + node = node.left; + } else { + var tmp = nodeToBeDeleted.key; + nodeToBeDeleted.key = parentNode.key; + parentNode.key = tmp; + node = node.right; + } + } + } else { //do balancing + + if (node.left === undefined) node.left = null; + if (node.right === undefined) node.right = null; + + if ((heightNode(node.left) - heightNode(node.right)) === 2) { + if (element < node.left.key) { + node = rotationLR(node); + } else { + node = rotationLL(node); + } + } + + if ((heightNode(node.right) - heightNode(node.left)) === 2) { + if (element > node.right.key) { + node = rotationRL(node); + } else { + node = rotationRR(node); + } + } + } + + return node; + }; + + this.remove = function(element) { + parentNode = null; + nodeToBeDeleted = null; + root = removeNode(root, element); + }; +} \ No newline at end of file diff --git a/chapter08/04-UsingAVLTree.html b/chapter08/04-UsingAVLTree.html index f7ce18b0..fda15f71 100644 --- a/chapter08/04-UsingAVLTree.html +++ b/chapter08/04-UsingAVLTree.html @@ -5,7 +5,7 @@ - - + + \ No newline at end of file diff --git a/chapter08/04-UsingAVLTree.js b/chapter08/04-UsingAVLTree.js index e69de29b..fd77d395 100644 --- a/chapter08/04-UsingAVLTree.js +++ b/chapter08/04-UsingAVLTree.js @@ -0,0 +1,62 @@ +var avlTree = new AVLTree(); + +avlTree.insert(1); +avlTree.insert(2); +avlTree.insert(3); +avlTree.insert(4); +avlTree.insert(5); +avlTree.insert(6); +avlTree.insert(7); +avlTree.insert(14); +avlTree.insert(15); +avlTree.insert(13); +avlTree.insert(12); +avlTree.insert(11); + +//RR rotation +/*avlTree.insert(50); +avlTree.insert(30); +avlTree.insert(70); +avlTree.insert(60); +avlTree.insert(80); +avlTree.insert(90);*/ + +//LL rotation +/*avlTree.insert(50); +avlTree.insert(30); +avlTree.insert(70); +avlTree.insert(10); +avlTree.insert(40); +avlTree.insert(5);*/ + +//LR rotation +/*avlTree.insert(50); +avlTree.insert(30); +avlTree.insert(70); +avlTree.insert(40); +avlTree.insert(10); +avlTree.insert(35);*/ + +//RL rotation +/*avlTree.insert(70); +avlTree.insert(50); +avlTree.insert(80); +avlTree.insert(72); +avlTree.insert(90); +avlTree.insert(75);*/ + +console.log('********* raw data structure ***********'); +console.log(avlTree.getRoot()); + +/*avlTree.remove(12); +avlTree.remove(15); +avlTree.remove(11); +avlTree.remove(14); +avlTree.remove(13); +avlTree.remove(7); +avlTree.remove(6); +avlTree.remove(2); +avlTree.remove(4); + +console.log(avlTree.getRoot());*/ + From 81bb9421c18f67188298e7b29f8a5263eff17566 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 27 Feb 2016 15:56:46 -0300 Subject: [PATCH 28/70] Red Black tree code --- chapter08/05-RedBlackTree.js | 101 ++++++++++++++++++++++++++++ chapter08/06-UsingRedBlackTree.html | 11 +++ chapter08/06-UsingRedBlackTree.js | 17 +++++ 3 files changed, 129 insertions(+) create mode 100644 chapter08/05-RedBlackTree.js create mode 100644 chapter08/06-UsingRedBlackTree.html create mode 100644 chapter08/06-UsingRedBlackTree.js diff --git a/chapter08/05-RedBlackTree.js b/chapter08/05-RedBlackTree.js new file mode 100644 index 00000000..7a985d2e --- /dev/null +++ b/chapter08/05-RedBlackTree.js @@ -0,0 +1,101 @@ +function RedBlackTree() { + + var Colors = { + RED: 0, + BLACK: 1 + }; + + var Node = function (key, color) { + this.key = key; + this.left = null; + this.right = null; + this.color = color; + + this.flipColor = function(){ + if (this.color === Colors.RED) { + this.color = Colors.BLACK; + } else { + this.color = Colors.RED; + } + }; + }; + + var root = null; + + this.getRoot = function () { + return root; + }; + + var isRed = function(node){ + if (!node){ + return false; + } + return node.color === Colors.RED; + }; + + var flipColors = function(node){ + node.left.flipColor(); + node.right.flipColor(); + }; + + var rotateLeft = function(node){ + var temp = node.right; + if (temp !== null) { + node.right = temp.left; + temp.left = node; + temp.color = node.color; + node.color = Colors.RED; + } + return temp; + }; + + var rotateRight = function (node) { + var temp = node.left; + if (temp !== null) { + node.left = temp.right; + temp.right = node; + temp.color = node.color; + node.color = Colors.RED; + } + return temp; + }; + + var insertNode = function(node, element) { + + if (node === null) { + return new Node(element, Colors.RED); + } + + var newRoot = node; + + if (element < node.key) { + + node.left = insertNode(node.left, element); + + } else if (element > node.key) { + + node.right = insertNode(node.right, element); + + } else { + node.key = element; + } + + if (isRed(node.right) && !isRed(node.left)) { + newRoot = rotateLeft(node); + } + + if (isRed(node.left) && isRed(node.left.left)) { + newRoot = rotateRight(node); + } + if (isRed(node.left) && isRed(node.right)) { + flipColors(node); + } + + return newRoot; + }; + + this.insert = function(element) { + root = insertNode(root, element); + root.color = Colors.BLACK; + }; +} diff --git a/chapter08/06-UsingRedBlackTree.html b/chapter08/06-UsingRedBlackTree.html new file mode 100644 index 00000000..f0fdfcc9 --- /dev/null +++ b/chapter08/06-UsingRedBlackTree.html @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/chapter08/06-UsingRedBlackTree.js b/chapter08/06-UsingRedBlackTree.js new file mode 100644 index 00000000..31136f99 --- /dev/null +++ b/chapter08/06-UsingRedBlackTree.js @@ -0,0 +1,17 @@ +var rbTree = new RedBlackTree(); + +rbTree.insert(1); +rbTree.insert(2); +rbTree.insert(3); +rbTree.insert(4); +rbTree.insert(5); +rbTree.insert(6); +rbTree.insert(7); +rbTree.insert(14); +rbTree.insert(15); +rbTree.insert(13); +rbTree.insert(12); +rbTree.insert(11); + +console.log('********* raw data structure ***********'); +console.log(rbTree.getRoot()); \ No newline at end of file From 9b83a6c31ab8a97bbcd5793c4965c4a091f36457 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 27 Feb 2016 15:56:53 -0300 Subject: [PATCH 29/70] updated readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 222adb3a..f73f9b53 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Book link - first edition: * 05: [Linked Lists](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter05) * 06: [Sets](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter06) * 07: [Dictionaries and Hashes](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter07) -* 08: Trees +* 08: [Trees](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter08) * 09: Graphs * 10: Sorting and searching algorithms * 11: Pattern of algorithms From 4c06ab32c6ca523e1c731b3c9df4488da2aa3a7d Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 27 Feb 2016 20:44:03 -0300 Subject: [PATCH 30/70] readme --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index f73f9b53..5a55fa56 100644 --- a/README.md +++ b/README.md @@ -3,10 +3,18 @@ Learning JavaScript Data Structures and Algorithms Source code of **Learning JavaScript Data Structures and Algorithms** book. +| 1st edition | 2nd edition | +| ------------- |:-------------:| +| ![1st edition](https://d1ldz4te4covpm.cloudfront.net/sites/default/files/imagecache/ppv4_main_book_cover/4874OS_Learning%20JavaScript%20Data%20Structures%20and%20Algorithms.jpg) | ![2nd edition](https://dz13w8afd47il.cloudfront.net/sites/default/files/imagecache/ppv4_main_book_cover/B05348_MockupCover_Normal.jpg) | +|[Book link](https://www.packtpub.com/application-development/learning-javascript-data-structures-and-algorithms)| [Book link](https://www.packtpub.com/web-development/learning-javascript-data-structures-and-algorithms-second-edition)| + Book link - first edition: - [Packt](https://www.packtpub.com/application-development/learning-javascript-data-structures-and-algorithms) - [Amazon](http://www.amazon.com/gp/product/1783554878/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1783554878&linkCode=as2&tag=loiagron-20&linkId=7VBQ7OMJ47XY7MUV) +Book link - second edition: + - [Packt](https://www.packtpub.com/web-development/learning-javascript-data-structures-and-algorithms-second-edition) + ### List of Chapters: * 01: [JavaScript: a quick overview](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter01) From 994206e62ffe92c6a238c21e7a66f951a0a1f409 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 27 Feb 2016 20:45:04 -0300 Subject: [PATCH 31/70] readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5a55fa56..0315efe5 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ Source code of **Learning JavaScript Data Structures and Algorithms** book. | 1st edition | 2nd edition | | ------------- |:-------------:| | ![1st edition](https://d1ldz4te4covpm.cloudfront.net/sites/default/files/imagecache/ppv4_main_book_cover/4874OS_Learning%20JavaScript%20Data%20Structures%20and%20Algorithms.jpg) | ![2nd edition](https://dz13w8afd47il.cloudfront.net/sites/default/files/imagecache/ppv4_main_book_cover/B05348_MockupCover_Normal.jpg) | -|[Book link](https://www.packtpub.com/application-development/learning-javascript-data-structures-and-algorithms)| [Book link](https://www.packtpub.com/web-development/learning-javascript-data-structures-and-algorithms-second-edition)| +| [Book link](https://www.packtpub.com/application-development/learning-javascript-data-structures-and-algorithms)| [Book link](https://www.packtpub.com/web-development/learning-javascript-data-structures-and-algorithms-second-edition)| Book link - first edition: - [Packt](https://www.packtpub.com/application-development/learning-javascript-data-structures-and-algorithms) From f2f455643451954d3d0ee18793a144334e8c8464 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Fri, 4 Mar 2016 18:53:48 -0300 Subject: [PATCH 32/70] readme --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0315efe5..5d46a31c 100644 --- a/README.md +++ b/README.md @@ -6,14 +6,17 @@ Source code of **Learning JavaScript Data Structures and Algorithms** book. | 1st edition | 2nd edition | | ------------- |:-------------:| | ![1st edition](https://d1ldz4te4covpm.cloudfront.net/sites/default/files/imagecache/ppv4_main_book_cover/4874OS_Learning%20JavaScript%20Data%20Structures%20and%20Algorithms.jpg) | ![2nd edition](https://dz13w8afd47il.cloudfront.net/sites/default/files/imagecache/ppv4_main_book_cover/B05348_MockupCover_Normal.jpg) | -| [Book link](https://www.packtpub.com/application-development/learning-javascript-data-structures-and-algorithms)| [Book link](https://www.packtpub.com/web-development/learning-javascript-data-structures-and-algorithms-second-edition)| +| [Book link](http://amzn.to/1Y1OWPx)| [Book link](http://amzn.to/1TSkcA1)| Book link - first edition: - [Packt](https://www.packtpub.com/application-development/learning-javascript-data-structures-and-algorithms) - - [Amazon](http://www.amazon.com/gp/product/1783554878/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1783554878&linkCode=as2&tag=loiagron-20&linkId=7VBQ7OMJ47XY7MUV) + - [Amazon](http://amzn.to/1Y1OWPx) + - [Chinese version](http://www.ituring.com.cn/book/1613) + - [Korean version](http://www.acornpub.co.kr/book/javascript-data-structure) Book link - second edition: - [Packt](https://www.packtpub.com/web-development/learning-javascript-data-structures-and-algorithms-second-edition) + - [Amazon](http://amzn.to/1TSkcA1) ### List of Chapters: From 433e4c0644f7e454ce278ac27f61956362da318a Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sun, 6 Mar 2016 15:39:50 -0300 Subject: [PATCH 33/70] chapter 9 - shortest path algorithms --- chapter09/03-ShortestPath.js | 85 +++++++++++++++++++ chapter09/04-UsingShortestPathAlgorithms.html | 11 +++ chapter09/04-UsingShortestPathAlgorithms.js | 43 ++++++++++ 3 files changed, 139 insertions(+) create mode 100644 chapter09/03-ShortestPath.js create mode 100644 chapter09/04-UsingShortestPathAlgorithms.html create mode 100644 chapter09/04-UsingShortestPathAlgorithms.js diff --git a/chapter09/03-ShortestPath.js b/chapter09/03-ShortestPath.js new file mode 100644 index 00000000..0b5517db --- /dev/null +++ b/chapter09/03-ShortestPath.js @@ -0,0 +1,85 @@ +function ShortestPath(graph) { + + this.graph = graph; + + var INF = Number.MAX_SAFE_INTEGER; + + var minDistance = function(dist, visited){ + + var min = INF, + minIndex = -1; + + for (var v = 0; v < dist.length; v++){ + if (visited[v] == false && dist[v] <= min){ + min = dist[v]; + minIndex = v; + } + } + + return minIndex; + }; + + this.dijkstra = function(src){ + + var dist = [], + visited = [], + length = this.graph.length; + + // Initialize all distances as INFINITE (JavaScript max number) and visited[] as false + for (var i = 0; i < length; i++) { + dist[i] = INF; + visited[i] = false; + } + + // Distance of source vertex from itself is always 0 + dist[src] = 0; + + // Find shortest path for all vertices + for (var i = 0; i < length-1; i++){ + + // Pick the minimum distance vertex from the set of vertices + // not yet processed. u is always equal to src in first + // iteration. + var u = minDistance(dist, visited); + + // Mark the picked vertex as processed + visited[u] = true; + + // Update dist value of the adjacent vertices of the + // picked vertex. + for (var v = 0; v < length; v++){ + if (!visited[v] && this.graph[u][v]!=0 && dist[u] != INF && dist[u]+this.graph[u][v] < dist[v]){ + dist[v] = dist[u] + this.graph[u][v]; + } + } + } + + return dist; + }; + + this.floydWarshall = function(){ + + var dist = [], + length = this.graph.length, + i, j, k; + + for (i = 0; i < length; i++){ + dist[i] = []; + for (j = 0; j < length; j++){ + dist[i][j] = this.graph[i][j]; + } + } + + for (k = 0; k < length; k++){ + for (i = 0; i < length; i++){ + for (j = 0; j < length; j++){ + if (dist[i][k] + dist[k][j] < dist[i][j]){ + dist[i][j] = dist[i][k] + dist[k][j]; + } + } + } + } + + return dist; + } +} \ No newline at end of file diff --git a/chapter09/04-UsingShortestPathAlgorithms.html b/chapter09/04-UsingShortestPathAlgorithms.html new file mode 100644 index 00000000..422b9fc4 --- /dev/null +++ b/chapter09/04-UsingShortestPathAlgorithms.html @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/chapter09/04-UsingShortestPathAlgorithms.js b/chapter09/04-UsingShortestPathAlgorithms.js new file mode 100644 index 00000000..6d8d424f --- /dev/null +++ b/chapter09/04-UsingShortestPathAlgorithms.js @@ -0,0 +1,43 @@ +//adjacent matrix +var graph = [[0, 2, 4, 0, 0, 0], + [0, 0, 1, 4, 2, 0], + [0, 0, 0, 0, 3, 0], + [0, 0, 0, 0, 0, 2], + [0, 0, 0, 3, 0, 2], + [0, 0, 0, 0, 0, 0]]; + +var shortestPath = new ShortestPath(graph); + +console.log("********* Dijkstra's Algorithm - Shortest Path ***********"); + +var dist = shortestPath.dijkstra(0); + +for (var i = 0; i < dist.length; i++){ + console.log(i + '\t\t' + dist[i]); +} + +console.log("********* Floyd-Warshall Algorithm - All-Pairs Shortest Path ***********"); + +var INF = Number.MAX_SAFE_INTEGER; +graph = [[0, 2, 4, INF, INF, INF], + [INF, 0, 1, 4, 2, INF], + [INF, INF, 0, INF, 3, INF], + [INF, INF, INF, 0, INF, 2], + [INF, INF, INF, 3, 0, 2], + [INF, INF, INF, INF, INF, 0]]; + +shortestPath = new ShortestPath(graph); + +dist = shortestPath.floydWarshall(); + +var s = ''; +for (var i=0; i Date: Mon, 7 Mar 2016 10:16:09 -0300 Subject: [PATCH 34/70] shortest path algorithm --- chapter09/03-ShortestPath.js | 9 --------- 1 file changed, 9 deletions(-) diff --git a/chapter09/03-ShortestPath.js b/chapter09/03-ShortestPath.js index 0b5517db..cdef7fbb 100644 --- a/chapter09/03-ShortestPath.js +++ b/chapter09/03-ShortestPath.js @@ -25,28 +25,19 @@ function ShortestPath(graph) { visited = [], length = this.graph.length; - // Initialize all distances as INFINITE (JavaScript max number) and visited[] as false for (var i = 0; i < length; i++) { dist[i] = INF; visited[i] = false; } - // Distance of source vertex from itself is always 0 dist[src] = 0; - // Find shortest path for all vertices for (var i = 0; i < length-1; i++){ - // Pick the minimum distance vertex from the set of vertices - // not yet processed. u is always equal to src in first - // iteration. var u = minDistance(dist, visited); - // Mark the picked vertex as processed visited[u] = true; - // Update dist value of the adjacent vertices of the - // picked vertex. for (var v = 0; v < length; v++){ if (!visited[v] && this.graph[u][v]!=0 && dist[u] != INF && dist[u]+this.graph[u][v] < dist[v]){ dist[v] = dist[u] + this.graph[u][v]; From b30cedb70618be090cdf6b51f471b42b4fc515be Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Mon, 7 Mar 2016 10:16:23 -0300 Subject: [PATCH 35/70] using shortest path algorithms --- chapter09/04-UsingShortestPathAlgorithms.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/chapter09/04-UsingShortestPathAlgorithms.js b/chapter09/04-UsingShortestPathAlgorithms.js index 6d8d424f..5bc5ac79 100644 --- a/chapter09/04-UsingShortestPathAlgorithms.js +++ b/chapter09/04-UsingShortestPathAlgorithms.js @@ -1,6 +1,8 @@ //adjacent matrix +var i; + var graph = [[0, 2, 4, 0, 0, 0], - [0, 0, 1, 4, 2, 0], + [0, 0, 2, 4, 2, 0], [0, 0, 0, 0, 3, 0], [0, 0, 0, 0, 0, 2], [0, 0, 0, 3, 0, 2], @@ -12,7 +14,7 @@ console.log("********* Dijkstra's Algorithm - Shortest Path ***********"); var dist = shortestPath.dijkstra(0); -for (var i = 0; i < dist.length; i++){ +for (i = 0; i < dist.length; i++){ console.log(i + '\t\t' + dist[i]); } @@ -20,7 +22,7 @@ console.log("********* Floyd-Warshall Algorithm - All-Pairs Shortest Path ****** var INF = Number.MAX_SAFE_INTEGER; graph = [[0, 2, 4, INF, INF, INF], - [INF, 0, 1, 4, 2, INF], + [INF, 0, 2, 4, 2, INF], [INF, INF, 0, INF, 3, INF], [INF, INF, INF, 0, INF, 2], [INF, INF, INF, 3, 0, 2], @@ -31,7 +33,7 @@ shortestPath = new ShortestPath(graph); dist = shortestPath.floydWarshall(); var s = ''; -for (var i=0; i Date: Mon, 7 Mar 2016 10:16:54 -0300 Subject: [PATCH 36/70] mst algorithms --- chapter09/05-MinimumSpanningTree.js | 113 +++++++++++++++++++++ chapter09/06-UsingMinimumSpanningTree.html | 11 ++ chapter09/06-UsingMinimumSpanningTree.js | 29 ++++++ 3 files changed, 153 insertions(+) create mode 100644 chapter09/05-MinimumSpanningTree.js create mode 100644 chapter09/06-UsingMinimumSpanningTree.html create mode 100644 chapter09/06-UsingMinimumSpanningTree.js diff --git a/chapter09/05-MinimumSpanningTree.js b/chapter09/05-MinimumSpanningTree.js new file mode 100644 index 00000000..d2030144 --- /dev/null +++ b/chapter09/05-MinimumSpanningTree.js @@ -0,0 +1,113 @@ +function MinimumSpanningTree(graph) { + + this.graph = graph; + + var INF = Number.MAX_SAFE_INTEGER; + + var minKey = function (key, visited) { + // Initialize min value + var min = INF, minIndex; + + for (var v = 0; v < this.graph.length; v++){ + if (visited[v] == false && key[v] < min) { + min = key[v]; + minIndex = v; + } + } + + return minIndex; + }; + + this.prim = function() { + var parent = [], + key = [], + visited = [], + length = this.graph.length, + i; + + for (i = 0; i < length; i++){ + key[i] = INF; + visited[i] = false; + } + + key[0] = 0; + parent[0] = -1; + + for (i = 0; i < length-1; i++) { + var u = minKey(key, visited); + visited[u] = true; + + for (var v = 0; v < length; v++){ + if (this.graph[u][v] && visited[v] == false && this.graph[u][v] < key[v]){ + parent[v] = u; + key[v] = this.graph[u][v]; + } + } + } + + return parent; + }; + + var find = function(i, parent){ + while(parent[i]){ + i = parent[i]; + } + return i; + }; + + var union = function(i, j, parent){ + if(i != j) { + parent[j] = i; + return true; + } + return false; + }; + + var initializeCost = function(){ + var cost = [], length = this.graph.length; + for (var i = 0; i < length; i++){ + cost[i] = []; + for (var j = 0; j < length; j++){ + if (this.graph[i][j] == 0){ + cost[i][j] = INF; + } else { + cost[i][j] = this.graph[i][j]; + } + } + } + return cost; + }; + + this.kruskal = function(){ + + var length = this.graph.length, + parent = [], cost, + ne = 0, a, b, u, v, i, j, min; + + cost = initializeCost(); + + while(ne + + + + + + + + + + \ No newline at end of file diff --git a/chapter09/06-UsingMinimumSpanningTree.js b/chapter09/06-UsingMinimumSpanningTree.js new file mode 100644 index 00000000..286f1dff --- /dev/null +++ b/chapter09/06-UsingMinimumSpanningTree.js @@ -0,0 +1,29 @@ +var i; + +var graph = [[0, 2, 4, 0, 0, 0], + [2, 0, 2, 4, 2, 0], + [4, 2, 0, 0, 3, 0], + [0, 4, 0, 0, 3, 2], + [0, 2, 3, 3, 0, 2], + [0, 0, 0, 2, 2, 0]]; + +var mst = new MinimumSpanningTree(graph); + + +console.log("********* Prim's Algorithm - Minimum Spanning Tree ***********"); + +var parent = mst.prim(); + +console.log('Edge Weight'); +for (i = 1; i < graph.length; i++){ + console.log(parent[i] + ' - ' + i + ' ' + graph[i][parent[i]]); +} + +console.log("********* Kruskal Algorithm - Minimum Spanning Tree ***********"); + +parent = mst.kruskal(); + +console.log('Edge Weight'); +for (i = 1; i < graph.length; i++){ + console.log(parent[i] + ' - ' + i + ' ' + graph[i][parent[i]]); +} \ No newline at end of file From 2aa102f70bd1fc1240d60be52be3bbfb58c2895c Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Tue, 8 Mar 2016 12:05:24 -0300 Subject: [PATCH 37/70] readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5d46a31c..48f5d487 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ Book link - second edition: * 06: [Sets](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter06) * 07: [Dictionaries and Hashes](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter07) * 08: [Trees](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter08) -* 09: Graphs +* 09: [Graphs](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter09) * 10: Sorting and searching algorithms * 11: Pattern of algorithms * 12: More about algorithms From 5af6d723ab21f6ab7b47eeeb97e9464403a89f63 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 12 Mar 2016 16:28:55 -0300 Subject: [PATCH 38/70] added bucket and counting sort --- chapter10/01-SortingSearchingAlgorithms.js | 82 +++++++++++++++++++--- 1 file changed, 73 insertions(+), 9 deletions(-) diff --git a/chapter10/01-SortingSearchingAlgorithms.js b/chapter10/01-SortingSearchingAlgorithms.js index b4081024..77a95497 100755 --- a/chapter10/01-SortingSearchingAlgorithms.js +++ b/chapter10/01-SortingSearchingAlgorithms.js @@ -6,10 +6,12 @@ function ArrayList(){ array.push(item); }; - var swap = function(index1, index2){ + var swap = function(array, index1, index2){ var aux = array[index1]; array[index1] = array[index2]; array[index2] = aux; + //ES2015 swap - Firefox only, for other browser, uncomment code above and coment line below + //[array[index1], array[index2]] = [array[index2], array[index1]]; }; this.toString= function(){ @@ -25,7 +27,7 @@ function ArrayList(){ console.log('compare ' + array[j] + ' with ' + array[j+1]); if (array[j] > array[j+1]){ console.log('swap ' + array[j] + ' with ' + array[j+1]); - swap(j, j+1); + swap(array, j, j+1); } } } @@ -84,6 +86,20 @@ function ArrayList(){ } }; + var insertionSort_ = function(array){ + var length = array.length, + j, temp; + for (var i=1; i0 && array[j-1] > temp){ + array[j] = array[j-1]; + j--; + } + array[j] = temp; + } + }; + this.mergeSort = function(){ array = mergeSortRec(array); }; @@ -156,7 +172,7 @@ function ArrayList(){ if (i <= j) { console.log('swap ' + array[i] + ' with ' + array[j]); - swapQuickStort(array, i, j); + swap(array, i, j); i++; j--; } @@ -165,12 +181,6 @@ function ArrayList(){ return i; }; - var swapQuickStort = function(array, index1, index2){ - var aux = array[index1]; - array[index1] = array[index2]; - array[index2] = aux; - }; - var quick = function(array, left, right){ var index; @@ -190,6 +200,60 @@ function ArrayList(){ return array; }; + this.countingSort = function(){ + + var i, + maxValue = this.findMaxValue(), + sortedIndex = 0, + counts = new Array(maxValue + 1); + + for (i = 0; i < array.length; i++) { + if (!counts[array[i]]) { + counts[array[i]] = 0; + } + counts[array[i]]++; + } + + console.log('Frequencies: ' + counts.join()); + + for (i = 0; i < counts.length; i++) { + while (counts[i] > 0) { + array[sortedIndex++] = i; + counts[i]--; + } + } + }; + + this.bucketSort = function(bucketSize){ + + var i, + minValue = this.findMinValue(), + maxValue = this.findMaxValue(), + BUCKET_SIZE = 10; + + bucketSize = bucketSize || BUCKET_SIZE; + var bucketCount = Math.floor((maxValue - minValue) / bucketSize) + 1; + var buckets = new Array(bucketCount); + for (i = 0; i < buckets.length; i++) { + buckets[i] = []; + } + + for (i = 0; i < array.length; i++) { + buckets[Math.floor((array[i] - minValue) / bucketSize)].push(array[i]); + } + + array = []; + for (i = 0; i < buckets.length; i++) { + insertionSort_(buckets[i]); + + console.log('bucket ' + i + ': ' + buckets[i].join()); + + for (var j = 0; j < buckets[i].length; j++) { + array.push(buckets[i][j]); + } + } + }; + this.sequentialSearch = function(item){ for (var i=0; i Date: Sun, 13 Mar 2016 10:59:41 -0300 Subject: [PATCH 39/70] added heap sort --- chapter10/01-SortingSearchingAlgorithms.js | 50 +++++++++++++++++++++- 1 file changed, 48 insertions(+), 2 deletions(-) diff --git a/chapter10/01-SortingSearchingAlgorithms.js b/chapter10/01-SortingSearchingAlgorithms.js index 77a95497..ad23c9d9 100755 --- a/chapter10/01-SortingSearchingAlgorithms.js +++ b/chapter10/01-SortingSearchingAlgorithms.js @@ -200,6 +200,47 @@ function ArrayList(){ return array; }; + this.heapSort = function(){ + var heapSize = array.length; + + buildHeap(array); + + while (heapSize > 1) { + heapSize--; + swap(array, 0, heapSize); + heapify(array, heapSize, 0); + } + }; + + var buildHeap = function(array){ + var heapSize = array.length; + for (var i = Math.floor(array.length / 2); i >= 0; i--) { + heapify(array, heapSize, i); + } + }; + + var heapify = function(array, heapSize, i){ + var left = i * 2 + 1, + right = i * 2 + 2, + largest = i; + + if (left < heapSize && array[left] > array[largest]) { + largest = left; + } + + if (right < heapSize && array[right] > array[largest]) { + largest = right; + } + + console.log('Heap Index = '+ i + ' and Heap Size = ' + heapSize); + + if (largest !== i) { + console.log('swap index ' + i + ' with ' + largest + ' (' + + array[i] + ',' + array[largest] + ')'); + swap(array, i, largest); + heapify(array, heapSize, largest); + } + }; + this.countingSort = function(){ var i, @@ -229,24 +270,29 @@ function ArrayList(){ var i, minValue = this.findMinValue(), maxValue = this.findMaxValue(), - BUCKET_SIZE = 10; + BUCKET_SIZE = 5; + + console.log('minValue ' + minValue); + console.log('maxValue ' + maxValue); bucketSize = bucketSize || BUCKET_SIZE; var bucketCount = Math.floor((maxValue - minValue) / bucketSize) + 1; var buckets = new Array(bucketCount); + console.log('bucketSize = ' + bucketCount); for (i = 0; i < buckets.length; i++) { buckets[i] = []; } for (i = 0; i < array.length; i++) { buckets[Math.floor((array[i] - minValue) / bucketSize)].push(array[i]); + console.log('pushing item ' + array[i] + ' to bucket index ' + Math.floor((array[i] - minValue) / bucketSize)); } array = []; for (i = 0; i < buckets.length; i++) { insertionSort_(buckets[i]); - console.log('bucket ' + i + ': ' + buckets[i].join()); + console.log('bucket sorted ' + i + ': ' + buckets[i].join()); for (var j = 0; j < buckets[i].length; j++) { array.push(buckets[i][j]); From c317e60ed08ad36b046b108155b06917a2b98971 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sun, 13 Mar 2016 10:59:58 -0300 Subject: [PATCH 40/70] added bucket, count, heap sort examples --- chapter10/02-UsingSortingAlgorithms.js | 81 ++++++++++++++++---------- 1 file changed, 50 insertions(+), 31 deletions(-) diff --git a/chapter10/02-UsingSortingAlgorithms.js b/chapter10/02-UsingSortingAlgorithms.js index e09c3e33..3b38c037 100755 --- a/chapter10/02-UsingSortingAlgorithms.js +++ b/chapter10/02-UsingSortingAlgorithms.js @@ -14,77 +14,96 @@ function createRandomNonSortedArray(){ array.insert(3); array.insert(5); array.insert(1); + array.insert(6); array.insert(4); + array.insert(7); array.insert(2); return array; } -console.log('********** Bubble Sort **********'); +function printArray(array){ + console.log(array.toString()); +} -var array = createNonSortedArray(5); +function createNonSortedArrayAndPrint(size){ + var array = createNonSortedArray(size); + printArray(array); + + return array; +} + +console.log('********** Bubble Sort **********'); -console.log(array.toString()); +var array = createNonSortedArrayAndPrint(5); array.bubbleSort(); -console.log(array.toString()); +printArray(array); console.log('********** Modified Bubble Sort **********'); -array = createNonSortedArray(5); - -console.log(array.toString()); +array = createNonSortedArrayAndPrint(5); array.modifiedBubbleSort(); -console.log(array.toString()); +printArray(array); console.log('********** Selection Sort **********'); -array = createNonSortedArray(5); - -console.log(array.toString()); +array = createNonSortedArrayAndPrint(5); array.selectionSort(); -console.log(array.toString()); +printArray(array); console.log('********** Insertion Sort **********'); -array = createRandomNonSortedArray(); - -console.log(array.toString()); +array = createNonSortedArrayAndPrint(); array.insertionSort(); -console.log(array.toString()); +printArray(array); console.log('********** Merge Sort **********'); -array = createNonSortedArray(8); - -console.log(array.toString()); +array = createNonSortedArrayAndPrint(8); array.mergeSort(); -console.log(array.toString()); +printArray(array); console.log('********** Quick Sort **********'); -array = new ArrayList(); - -array.insert(3); -array.insert(5); -array.insert(1); -array.insert(6); -array.insert(4); -array.insert(7); -array.insert(2); +array = createRandomNonSortedArray(); -console.log(array.toString()); +printArray(array); array.quickSort(); -console.log(array.toString()); +printArray(array); + +console.log('********** Heap Sort **********'); +array = createRandomNonSortedArray(); + +printArray(array); + +array.heapSort(); + +printArray(array); + + +console.log('********** Counting Sort **********'); + +array = createNonSortedArrayAndPrint(8); + +array.countingSort(); + +printArray(array); + +console.log('********** Bucket Sort **********'); + +array = createNonSortedArrayAndPrint(8); +array.bucketSort(3); +printArray(array); From 05ca4cb4ec4e5e7e598214f7e28942f6d24ddd7e Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sun, 13 Mar 2016 11:49:51 -0300 Subject: [PATCH 41/70] added radix sort --- chapter10/01-SortingSearchingAlgorithms.js | 51 ++++++++++++++++++++++ chapter10/02-UsingSortingAlgorithms.js | 17 ++++++++ 2 files changed, 68 insertions(+) diff --git a/chapter10/01-SortingSearchingAlgorithms.js b/chapter10/01-SortingSearchingAlgorithms.js index ad23c9d9..9746795e 100755 --- a/chapter10/01-SortingSearchingAlgorithms.js +++ b/chapter10/01-SortingSearchingAlgorithms.js @@ -18,6 +18,10 @@ function ArrayList(){ return array.join(); }; + this.array= function(){ + return array; + }; + this.bubbleSort = function(){ var length = array.length; @@ -300,6 +304,53 @@ function ArrayList(){ } }; + this.radixSort = function(radixBase){ + + var i, + minValue = this.findMinValue(), + maxValue = this.findMaxValue(), + radixBase = radixBase || 10; + + // Perform counting sort for each significant digit), starting at 1 + var significantDigit = 1; + while (((maxValue - minValue) / significantDigit) >= 1) { + console.log('radix sort for digit ' + significantDigit); + array = countingSortForRadix(array, radixBase, significantDigit, minValue); + console.log(array.join()); + significantDigit *= radixBase; + } + }; + + var countingSortForRadix = function(array, radixBase, significantDigit, minValue){ + var i, countsIndex, + counts = new Array(radixBase), + aux = new Array(radixBase); + + for (i = 0; i < radixBase; i++) { + counts[i] = 0; + } + + for (i = 0; i < array.length; i++) { + countsIndex = Math.floor(((array[i] - minValue) / significantDigit) % radixBase); + counts[countsIndex]++; + } + + for (i = 1; i < radixBase; i++) { + counts[i] += counts[i - 1]; + } + + for (i = array.length - 1; i >= 0; i--) { + countsIndex = Math.floor(((array[i] - minValue) / significantDigit) % radixBase); + aux[--counts[countsIndex]] = array[i]; + } + + for (i = 0; i < array.length; i++) { + array[i] = aux[i]; + } + + return array; + }; + this.sequentialSearch = function(item){ for (var i=0; i Date: Tue, 15 Mar 2016 20:16:59 -0300 Subject: [PATCH 42/70] added heap sort algorithm --- chapter10/01-SortingSearchingAlgorithms.js | 7 ++++++- chapter10/02-UsingSortingAlgorithms.js | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/chapter10/01-SortingSearchingAlgorithms.js b/chapter10/01-SortingSearchingAlgorithms.js index 9746795e..916e7403 100755 --- a/chapter10/01-SortingSearchingAlgorithms.js +++ b/chapter10/01-SortingSearchingAlgorithms.js @@ -211,16 +211,20 @@ function ArrayList(){ while (heapSize > 1) { heapSize--; + console.log('swap (' + + array[0] + ',' + array[heapSize] + ')'); swap(array, 0, heapSize); + console.log('heapify ' + array.join()); heapify(array, heapSize, 0); } }; var buildHeap = function(array){ + console.log('building heap'); var heapSize = array.length; for (var i = Math.floor(array.length / 2); i >= 0; i--) { heapify(array, heapSize, i); } + console.log('heap created: ' + array.join()); }; var heapify = function(array, heapSize, i){ @@ -236,11 +240,12 @@ function ArrayList(){ largest = right; } - console.log('Heap Index = '+ i + ' and Heap Size = ' + heapSize); + console.log('Heapify Index = '+ i + ' and Heap Size = ' + heapSize); if (largest !== i) { console.log('swap index ' + i + ' with ' + largest + ' (' + + array[i] + ',' + array[largest] + ')'); swap(array, i, largest); + console.log('heapify ' + array.join()); heapify(array, heapSize, largest); } }; diff --git a/chapter10/02-UsingSortingAlgorithms.js b/chapter10/02-UsingSortingAlgorithms.js index fcdf6dc3..92b63e8f 100755 --- a/chapter10/02-UsingSortingAlgorithms.js +++ b/chapter10/02-UsingSortingAlgorithms.js @@ -59,7 +59,7 @@ printArray(array); console.log('********** Insertion Sort **********'); -array = createNonSortedArrayAndPrint(); +array = createNonSortedArrayAndPrint(5); array.insertionSort(); From 9c9b0e771296ee1076b28ac885bc6d7e5ff373bf Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Tue, 15 Mar 2016 20:17:09 -0300 Subject: [PATCH 43/70] updated read --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 48f5d487..f2762892 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ Book link - second edition: * 07: [Dictionaries and Hashes](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter07) * 08: [Trees](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter08) * 09: [Graphs](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter09) -* 10: Sorting and searching algorithms +* 10: [Sorting and searching algorithms](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter10) * 11: Pattern of algorithms * 12: More about algorithms * 13: Functional programming and data structures From e5e3d664f4795207c4aeaa6db51695e6c2c24559 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 26 Mar 2016 15:39:47 -0300 Subject: [PATCH 44/70] removed unnecessary code --- chapter11/03-MinCoinChangeDP.js | 2 -- chapter11/07-LongestCommonSubsequenceDP.html | 10 ++++++++++ chapter11/08-LongestCommonSubsequenceRecursive.html | 10 ++++++++++ chapter11/09-MatrixChainMultiplicationDP.html | 10 ++++++++++ chapter11/10-MatrixChainMultiplicationRecursive.html | 10 ++++++++++ 5 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 chapter11/07-LongestCommonSubsequenceDP.html create mode 100644 chapter11/08-LongestCommonSubsequenceRecursive.html create mode 100644 chapter11/09-MatrixChainMultiplicationDP.html create mode 100644 chapter11/10-MatrixChainMultiplicationRecursive.html diff --git a/chapter11/03-MinCoinChangeDP.js b/chapter11/03-MinCoinChangeDP.js index 75d0bfd2..90a4a541 100644 --- a/chapter11/03-MinCoinChangeDP.js +++ b/chapter11/03-MinCoinChangeDP.js @@ -1,7 +1,5 @@ function MinCoinChange(coins){ - var coins = coins; - var cache = {}; this.makeChange = function(amount) { diff --git a/chapter11/07-LongestCommonSubsequenceDP.html b/chapter11/07-LongestCommonSubsequenceDP.html new file mode 100644 index 00000000..d538fea6 --- /dev/null +++ b/chapter11/07-LongestCommonSubsequenceDP.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/chapter11/08-LongestCommonSubsequenceRecursive.html b/chapter11/08-LongestCommonSubsequenceRecursive.html new file mode 100644 index 00000000..d538fea6 --- /dev/null +++ b/chapter11/08-LongestCommonSubsequenceRecursive.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/chapter11/09-MatrixChainMultiplicationDP.html b/chapter11/09-MatrixChainMultiplicationDP.html new file mode 100644 index 00000000..d538fea6 --- /dev/null +++ b/chapter11/09-MatrixChainMultiplicationDP.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/chapter11/10-MatrixChainMultiplicationRecursive.html b/chapter11/10-MatrixChainMultiplicationRecursive.html new file mode 100644 index 00000000..d538fea6 --- /dev/null +++ b/chapter11/10-MatrixChainMultiplicationRecursive.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file From e7ebf9c9b8dfbd2b73189423362e70af50eff6c2 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 26 Mar 2016 15:40:07 -0300 Subject: [PATCH 45/70] removed unnecessary code --- chapter11/04-MinCoinChangeGreedy.js | 1 - 1 file changed, 1 deletion(-) diff --git a/chapter11/04-MinCoinChangeGreedy.js b/chapter11/04-MinCoinChangeGreedy.js index a935c16b..3050f7ed 100644 --- a/chapter11/04-MinCoinChangeGreedy.js +++ b/chapter11/04-MinCoinChangeGreedy.js @@ -18,7 +18,6 @@ function MinCoinChange(coins){ }; } - var minCoinChange = new MinCoinChange([1, 5, 10, 25]); console.log(minCoinChange.makeChange(36)); From 5a3807565caba9f2f9445e5feeaa40f8aa3b4ae8 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 26 Mar 2016 15:40:41 -0300 Subject: [PATCH 46/70] updated read --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index f2762892..8b256af7 100644 --- a/README.md +++ b/README.md @@ -30,9 +30,8 @@ Book link - second edition: * 08: [Trees](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter08) * 09: [Graphs](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter09) * 10: [Sorting and searching algorithms](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter10) -* 11: Pattern of algorithms +* 11: [Pattern of algorithms](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter11) * 12: More about algorithms -* 13: Functional programming and data structures ### First Edition source code: From 5261d58c421da24994e99e42843db987d5ae0991 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 26 Mar 2016 15:41:12 -0300 Subject: [PATCH 47/70] knapSack dp --- chapter11/05-KnapsackProblemDP.js | 53 +++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 chapter11/05-KnapsackProblemDP.js diff --git a/chapter11/05-KnapsackProblemDP.js b/chapter11/05-KnapsackProblemDP.js new file mode 100644 index 00000000..fb6adbe7 --- /dev/null +++ b/chapter11/05-KnapsackProblemDP.js @@ -0,0 +1,53 @@ +function knapSack(capacity, weights, values, n) { + + var i, w, a, b, kS = []; + + for (i = 0; i <= n; i++) { + kS[i] = []; + } + + for (i = 0; i <= n; i++){ + for (w = 0; w <= capacity; w++){ + if (i == 0 || w == 0){ + kS[i][w] = 0; + + } else if (weights[i-1] <= w){ + a = values[i-1] + kS[i-1][w-weights[i-1]]; + b = kS[i-1][w]; + kS[i][w] = (a > b) ? a : b; //max(a,b) + console.log(a + ' can be part of the solution'); + } else{ + kS[i][w] = kS[i-1][w]; + } + } + console.log(kS[i].join()); + } + + //extra algorithm to find the items that are part of the solution + findValues(n, capacity, kS, values, weights); + + return kS[n][capacity]; +} + +function findValues(n, capacity, kS, weights, values){ + var i=n, k=capacity; + + console.log('Items that are part of the solution:'); + + while (i>0 && k>0){ + if (kS[i][k] !== kS[i-1][k]){ + console.log('item '+i+' can be part of solution w,v: ' + weights[i-1] + ',' + values[i-1]); + i--; + k = k - kS[i][k]; + } else { + i--; + } + } +} + +var values = [3,4,5], + weights = [2,3,4], + capacity = 5, + n = values.length; + +console.log('Total value that can be carried: ' + knapSack(capacity, weights, values, n)); \ No newline at end of file From fd0f1d3b9fbdd36c9e12c609d8c295c82dd0c64b Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 26 Mar 2016 15:41:23 -0300 Subject: [PATCH 48/70] knapSack recursice --- ....html => 06-KnapSackProblemRecursive.html} | 2 +- chapter11/06-KnapSackProblemRecursive.js | 22 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) rename chapter11/{08-LongestCommonSubsequenceRecursive.html => 06-KnapSackProblemRecursive.html} (68%) create mode 100644 chapter11/06-KnapSackProblemRecursive.js diff --git a/chapter11/08-LongestCommonSubsequenceRecursive.html b/chapter11/06-KnapSackProblemRecursive.html similarity index 68% rename from chapter11/08-LongestCommonSubsequenceRecursive.html rename to chapter11/06-KnapSackProblemRecursive.html index d538fea6..cc000756 100644 --- a/chapter11/08-LongestCommonSubsequenceRecursive.html +++ b/chapter11/06-KnapSackProblemRecursive.html @@ -5,6 +5,6 @@ - + \ No newline at end of file diff --git a/chapter11/06-KnapSackProblemRecursive.js b/chapter11/06-KnapSackProblemRecursive.js new file mode 100644 index 00000000..583092e1 --- /dev/null +++ b/chapter11/06-KnapSackProblemRecursive.js @@ -0,0 +1,22 @@ +function knapSack(capacity, weights, values, n) { + + if (n == 0 || capacity == 0){ + return 0; + } + + if (weights[n-1] > capacity){ + return knapSack(capacity, weights, values, n-1); + + } else { + var a = values[n-1] + knapSack(capacity-weights[n-1], weights, values, n-1), + b = knapSack(capacity, weights, values, n-1); + return (a > b) ? a : b; + } +} + +var values = [3,4,5], + weights = [2,3,4], + capacity = 5, + n = values.length; + +console.log(knapSack(capacity, weights, values, n)); \ No newline at end of file From aef7f9294c7d019fa9ff2752f6f6154f2a514f47 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 26 Mar 2016 15:41:40 -0300 Subject: [PATCH 49/70] knapSack greedy --- ...nDP.html => 07-KnapSackProblemGreedy.html} | 2 +- chapter11/07-KnapSackProblemGreedy.js | 28 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) rename chapter11/{09-MatrixChainMultiplicationDP.html => 07-KnapSackProblemGreedy.html} (69%) create mode 100644 chapter11/07-KnapSackProblemGreedy.js diff --git a/chapter11/09-MatrixChainMultiplicationDP.html b/chapter11/07-KnapSackProblemGreedy.html similarity index 69% rename from chapter11/09-MatrixChainMultiplicationDP.html rename to chapter11/07-KnapSackProblemGreedy.html index d538fea6..227d7b4b 100644 --- a/chapter11/09-MatrixChainMultiplicationDP.html +++ b/chapter11/07-KnapSackProblemGreedy.html @@ -5,6 +5,6 @@ - + \ No newline at end of file diff --git a/chapter11/07-KnapSackProblemGreedy.js b/chapter11/07-KnapSackProblemGreedy.js new file mode 100644 index 00000000..4c12e1a6 --- /dev/null +++ b/chapter11/07-KnapSackProblemGreedy.js @@ -0,0 +1,28 @@ +function knapSack(capacity, values, weights) { + var n = values.length, + load = 0, + i = 0, + val = 0; + + for (i=0; i Date: Sat, 26 Mar 2016 15:41:48 -0300 Subject: [PATCH 50/70] knapSack dp --- ...ongestCommonSubsequenceDP.html => 05-KnapsackProblemDP.html} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename chapter11/{07-LongestCommonSubsequenceDP.html => 05-KnapsackProblemDP.html} (70%) diff --git a/chapter11/07-LongestCommonSubsequenceDP.html b/chapter11/05-KnapsackProblemDP.html similarity index 70% rename from chapter11/07-LongestCommonSubsequenceDP.html rename to chapter11/05-KnapsackProblemDP.html index d538fea6..316f9722 100644 --- a/chapter11/07-LongestCommonSubsequenceDP.html +++ b/chapter11/05-KnapsackProblemDP.html @@ -5,6 +5,6 @@ - + \ No newline at end of file From f8527d259700bc647cb164b66a3afd07da0d8e1d Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 26 Mar 2016 15:41:59 -0300 Subject: [PATCH 51/70] lcs dp --- ...tml => 08-LongestCommonSubsequenceDP.html} | 2 +- chapter11/08-LongestCommonSubsequenceDP.js | 105 ++++++++++++++++++ 2 files changed, 106 insertions(+), 1 deletion(-) rename chapter11/{10-MatrixChainMultiplicationRecursive.html => 08-LongestCommonSubsequenceDP.html} (67%) create mode 100644 chapter11/08-LongestCommonSubsequenceDP.js diff --git a/chapter11/10-MatrixChainMultiplicationRecursive.html b/chapter11/08-LongestCommonSubsequenceDP.html similarity index 67% rename from chapter11/10-MatrixChainMultiplicationRecursive.html rename to chapter11/08-LongestCommonSubsequenceDP.html index d538fea6..dc63ccce 100644 --- a/chapter11/10-MatrixChainMultiplicationRecursive.html +++ b/chapter11/08-LongestCommonSubsequenceDP.html @@ -5,6 +5,6 @@ - + \ No newline at end of file diff --git a/chapter11/08-LongestCommonSubsequenceDP.js b/chapter11/08-LongestCommonSubsequenceDP.js new file mode 100644 index 00000000..b5eaf3f1 --- /dev/null +++ b/chapter11/08-LongestCommonSubsequenceDP.js @@ -0,0 +1,105 @@ +function lcs(wordX, wordY) { + + var m = wordX.length, + n = wordY.length, + l = [], + i, j, a, b; + + for (i = 0; i <= m; ++i) { + l[i] = []; + for (j = 0; j <= n; ++j) { + l[i][j] = 0; + } + } + + for (i=0; i<=m; i++) { + for (j=0; j<=n; j++) { + if (i == 0 || j == 0){ + l[i][j] = 0; + + } else if (wordX[i-1] == wordY[j-1]) { + l[i][j] = l[i-1][j-1] + 1; + + } else { + a = l[i-1][j]; + b = l[i][j-1]; + l[i][j] = (a > b) ? a : b; //max(a,b) + } + } + console.log(l[i].join()); + } + + return l[m][n]; +} + +//complete algorithm that prints the LCS as well + +function lcs2(wordX, wordY) { + + var m = wordX.length, + n = wordY.length, + l = [], + solution = [], + i, j, a, b; + + for (i = 0; i <= m; ++i) { + l[i] = []; + solution[i] = []; + for (j = 0; j <= n; ++j) { + l[i][j] = 0; + solution[i][j] = '0'; + } + } + + for (i=0; i<=m; i++) { + for (j=0; j<=n; j++) { + if (i == 0 || j == 0){ + l[i][j] = 0; + + } else if (wordX[i-1] == wordY[j-1]) { + l[i][j] = l[i-1][j-1] + 1; + solution[i][j] = 'diagonal'; + + } else { + a = l[i-1][j]; + b = l[i][j-1]; + l[i][j] = (a > b) ? a : b; //max(a,b) + + solution[i][j] = (l[i][j] == l[i - 1][j]) ? 'top' : 'left'; + } + } + console.log(l[i].join()); + console.log(solution[i].join()); + } + + printSolution(solution, l, wordX, wordY, m, n); + + return l[m][n]; +} + +function printSolution(solution, l, wordX, wordY, m, n){ + + var a = m, b = n, i, j, + x = solution[a][b], + answer = ''; + + while (x !== '0') { + if (solution[a][b] === 'diagonal') { + answer = wordX[a - 1] + answer; + a--; + b--; + } else if (solution[a][b] === 'left') { + b--; + } else if (solution[a][b] === 'top') { + a--; + } + x = solution[a][b]; + } + + console.log('lcs: '+ answer); +} + +var wordX = 'acbaed', + wordY = 'abcadf'; + +console.log(lcs2(wordX, wordY)); \ No newline at end of file From 39243c9ca92b79f52650bb537a4be3bdd3a5d120 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 26 Mar 2016 15:42:06 -0300 Subject: [PATCH 52/70] lcs recursive --- .../09-LongestCommonSubsequenceRecursive.html | 10 ++++++++++ .../09-LongestCommonSubsequenceRecursive.js | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 chapter11/09-LongestCommonSubsequenceRecursive.html create mode 100644 chapter11/09-LongestCommonSubsequenceRecursive.js diff --git a/chapter11/09-LongestCommonSubsequenceRecursive.html b/chapter11/09-LongestCommonSubsequenceRecursive.html new file mode 100644 index 00000000..59573751 --- /dev/null +++ b/chapter11/09-LongestCommonSubsequenceRecursive.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/chapter11/09-LongestCommonSubsequenceRecursive.js b/chapter11/09-LongestCommonSubsequenceRecursive.js new file mode 100644 index 00000000..1c96fab1 --- /dev/null +++ b/chapter11/09-LongestCommonSubsequenceRecursive.js @@ -0,0 +1,19 @@ +function lcs(wordwordX, wordwordY, m, n) { + + if (m == 0 || n == 0){ + return 0; + } + + if (wordwordX[m-1] == wordY[n-1]){ + return 1 + lcs(wordX, wordY, m-1, n-1); + } else { + var a = lcs(wordX, wordY, m, n-1), + b = lcs(wordX, wordY, m-1, n); + return (a > b) ? a : b; + } +} + +var wordX = 'acbaed', + wordY = 'abcadf'; + +console.log(lcs(wordX, wordY, wordX.length, wordY.length)); \ No newline at end of file From 49c5cc773011d0fac3a572531e9e22a361cf8b2f Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 26 Mar 2016 15:42:22 -0300 Subject: [PATCH 53/70] matrixChainOrder dp --- chapter11/10-MatrixChainMultiplicationDP.html | 10 ++++ chapter11/10-MatrixChainMultiplicationDP.js | 56 +++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 chapter11/10-MatrixChainMultiplicationDP.html create mode 100644 chapter11/10-MatrixChainMultiplicationDP.js diff --git a/chapter11/10-MatrixChainMultiplicationDP.html b/chapter11/10-MatrixChainMultiplicationDP.html new file mode 100644 index 00000000..2108a100 --- /dev/null +++ b/chapter11/10-MatrixChainMultiplicationDP.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/chapter11/10-MatrixChainMultiplicationDP.js b/chapter11/10-MatrixChainMultiplicationDP.js new file mode 100644 index 00000000..e335b3cc --- /dev/null +++ b/chapter11/10-MatrixChainMultiplicationDP.js @@ -0,0 +1,56 @@ +function matrixChainOrder(p, n) { + + var i, j, k, l, q, + m = [], s=[]; + + for (i = 1; i <= n; i++){ + m[i] = []; + m[i][i] = 0; + + } + + for (i = 0; i <= n; i++){ //to help printing the optimal solution + s[i] = []; //auxiliary + for (j=0; j<=n; j++){ + s[i][j] = 0; + } + } + + for (l=2; l Date: Sat, 26 Mar 2016 15:42:27 -0300 Subject: [PATCH 54/70] matrixChainOrder recursive --- ...11-MatrixChainMultiplicationRecursive.html | 10 +++++++ .../11-MatrixChainMultiplicationRecursive.js | 26 +++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 chapter11/11-MatrixChainMultiplicationRecursive.html create mode 100644 chapter11/11-MatrixChainMultiplicationRecursive.js diff --git a/chapter11/11-MatrixChainMultiplicationRecursive.html b/chapter11/11-MatrixChainMultiplicationRecursive.html new file mode 100644 index 00000000..bb627d51 --- /dev/null +++ b/chapter11/11-MatrixChainMultiplicationRecursive.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/chapter11/11-MatrixChainMultiplicationRecursive.js b/chapter11/11-MatrixChainMultiplicationRecursive.js new file mode 100644 index 00000000..0b327524 --- /dev/null +++ b/chapter11/11-MatrixChainMultiplicationRecursive.js @@ -0,0 +1,26 @@ +function matrixChainOrder(p, i, j){ + + if(i == j) { + return 0; + } + + var k, count, + min = Number.MAX_SAFE_INTEGER; + + for (k = i; k Date: Sun, 27 Mar 2016 11:14:06 -0300 Subject: [PATCH 55/70] big-o chart code --- {chapter11 => chapter12}/05-BigONotation.html | 0 {chapter11 => chapter12}/05-BigONotation.js | 0 {chapter11 => chapter12}/bigOChart/chart.js | 0 {chapter11 => chapter12}/bigOChart/index.html | 0 4 files changed, 0 insertions(+), 0 deletions(-) rename {chapter11 => chapter12}/05-BigONotation.html (100%) rename {chapter11 => chapter12}/05-BigONotation.js (100%) rename {chapter11 => chapter12}/bigOChart/chart.js (100%) rename {chapter11 => chapter12}/bigOChart/index.html (100%) diff --git a/chapter11/05-BigONotation.html b/chapter12/05-BigONotation.html similarity index 100% rename from chapter11/05-BigONotation.html rename to chapter12/05-BigONotation.html diff --git a/chapter11/05-BigONotation.js b/chapter12/05-BigONotation.js similarity index 100% rename from chapter11/05-BigONotation.js rename to chapter12/05-BigONotation.js diff --git a/chapter11/bigOChart/chart.js b/chapter12/bigOChart/chart.js similarity index 100% rename from chapter11/bigOChart/chart.js rename to chapter12/bigOChart/chart.js diff --git a/chapter11/bigOChart/index.html b/chapter12/bigOChart/index.html similarity index 100% rename from chapter11/bigOChart/index.html rename to chapter12/bigOChart/index.html From 1e2e6711551971feb7768bd5e03dba8014e144b5 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sun, 27 Mar 2016 11:14:40 -0300 Subject: [PATCH 56/70] updated readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8b256af7..643c6d36 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ Book link - second edition: * 09: [Graphs](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter09) * 10: [Sorting and searching algorithms](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter10) * 11: [Pattern of algorithms](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter11) -* 12: More about algorithms +* 12: [More about algorithms](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter12) ### First Edition source code: From b008a7264913928fa90943647089717d432a8098 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 2 Apr 2016 12:16:27 -0300 Subject: [PATCH 57/70] js functional programming examples --- chapter11/12-IntroFunctionalProgramming.html | 10 ++ chapter11/12-IntroFunctionalProgramming.js | 147 +++++++++++++++++++ 2 files changed, 157 insertions(+) create mode 100644 chapter11/12-IntroFunctionalProgramming.html create mode 100644 chapter11/12-IntroFunctionalProgramming.js diff --git a/chapter11/12-IntroFunctionalProgramming.html b/chapter11/12-IntroFunctionalProgramming.html new file mode 100644 index 00000000..422a711b --- /dev/null +++ b/chapter11/12-IntroFunctionalProgramming.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/chapter11/12-IntroFunctionalProgramming.js b/chapter11/12-IntroFunctionalProgramming.js new file mode 100644 index 00000000..47787255 --- /dev/null +++ b/chapter11/12-IntroFunctionalProgramming.js @@ -0,0 +1,147 @@ +console.log('Using imperative JS'); + +var printArray = function(array){ + for (var i=0; i array[i]){ + minValue = array[i]; + } + } + + return minValue; +}; + +console.log(findMinArray([8,6,4,5,9])); + +console.log('Finding the min value in an array - functional ES2015'); +const min_ = function(array){ + return Math.min(...array) +}; + +//simplifying using arrow functions +const min = arr => Math.min(...arr); + +console.log(min_([8,6,4,5,9])); +console.log(min([8,6,4,5,9])); + +//concat + reduce +console.log('merge arrays - imperative'); + +var mergeArrays_ = function(arrays){ + var count = arrays.length, + newArray = [], + k =0; + for (var i=0; i [].concat(...arrays); +console.log(mergeArrays([1, 2, 3], [4, 5], [6])); + +console.log('sum values of arrays - imperative'); +var sumValues = function(array){ + var total = array[0]; + for (var i=1; i arr.reduce((a, b) => a + b); + +console.log(sum([1, 2, 3, 4, 5])); + +//map +var daysOfWeek = [ + {name: 'Monday', value: 1}, + {name: 'Tuesday', value: 2}, + {name: 'Wednesday', value: 7} +]; + +var daysOfWeekValues_ = []; +for (var i = 0; i < daysOfWeek.length; i++) { + daysOfWeekValues_.push(daysOfWeek[i].value); +} + +//to +var daysOfWeekValues = daysOfWeek.map(function(day) { + return day.value; +}); +console.log(daysOfWeekValues); + + +//filter +var positiveNumbers_ = function(array){ + var positive = []; + for (var i = 0; i < array.length; i++) { + if (array[i] >= 0){ + positive.push(array[i]); + } + } + return positive; +} +console.log(positiveNumbers_([-1,1,2,-2])); + +var positiveNumbers = function(array){ + return array.filter(function(num){ + return num >= 0; + }) +}; +console.log(positiveNumbers([-1,1,2,-2])); \ No newline at end of file From 798050597c4e45b614bea3b9890403f0d957235c Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Mon, 18 Apr 2016 20:47:47 -0300 Subject: [PATCH 58/70] fixed chapter name --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 643c6d36..4e9eca37 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ Book link - second edition: * 09: [Graphs](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter09) * 10: [Sorting and searching algorithms](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter10) * 11: [Pattern of algorithms](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter11) -* 12: [More about algorithms](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter12) +* 12: [Algorithm Complexity](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter12) ### First Edition source code: From 5d9f8c68dca6c43f4c6a25fc769c7e6af15c4511 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Wed, 1 Jun 2016 00:02:58 -0300 Subject: [PATCH 59/70] reviewed code bundle --- chapter04/03-PriorityQueue.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/chapter04/03-PriorityQueue.js b/chapter04/03-PriorityQueue.js index f9071ddc..3b029e4d 100644 --- a/chapter04/03-PriorityQueue.js +++ b/chapter04/03-PriorityQueue.js @@ -50,7 +50,5 @@ let priorityQueue = new PriorityQueue(); priorityQueue.enqueue("John", 2); priorityQueue.enqueue("Jack", 1); priorityQueue.enqueue("Camila", 1); -priorityQueue.enqueue("Maxwell", 2); -priorityQueue.enqueue("Ana", 3); priorityQueue.print(); From b6f84d04665e6f98aed8f1089f3ee6e784aed9b1 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Fri, 10 Jun 2016 15:39:43 -0300 Subject: [PATCH 60/70] Update 14-ES6ParameterHandling.js --- chapter01/14-ES6ParameterHandling.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chapter01/14-ES6ParameterHandling.js b/chapter01/14-ES6ParameterHandling.js index 706c2059..4645f2a7 100644 --- a/chapter01/14-ES6ParameterHandling.js +++ b/chapter01/14-ES6ParameterHandling.js @@ -30,8 +30,8 @@ function restParamaterFunction (x, y, ...a) { console.log(restParamaterFunction(1, 2, "hello", true, 7)); // outputs 9; //code above is the same as ES5: -function restParamaterFunction (x, y) { +function restParamaterFunction2 (x, y) { var a = Array.prototype.slice.call(arguments, 2); return (x + y) * a.length; }; -console.log(restParamaterFunction2(1, 2, "hello", true, 7)); \ No newline at end of file +console.log(restParamaterFunction2(1, 2, "hello", true, 7)); From 2cb57e826889e02d2bd6578255997fa3e75dd8e1 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Fri, 10 Jun 2016 15:46:08 -0300 Subject: [PATCH 61/70] Update 02-UsingDictionaries.js --- chapter07/02-UsingDictionaries.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chapter07/02-UsingDictionaries.js b/chapter07/02-UsingDictionaries.js index 3ec30d4b..dc0bf258 100644 --- a/chapter07/02-UsingDictionaries.js +++ b/chapter07/02-UsingDictionaries.js @@ -11,9 +11,9 @@ console.log(dictionary.keys()); //outputs ["Gandalf", "John", "Tyrion"] console.log(dictionary.values()); //outputs ["gandalf@email.com", "johnsnow@email.com", "tyrion@email.com"] console.log(dictionary.get('Tyrion')); //outputs tyrion@email.com -dictionary.delete(‘John'); +dictionary.delete('John'); console.log(dictionary.keys()); //outputs ["Gandalf", "Tyrion"] console.log(dictionary.values()); //outputs ["gandalf@email.com", "tyrion@email.com"] -console.log(dictionary.getItems()); //Object {Gandalf: "gandalf@email.com", Tyrion: "tyrion@email.com"} \ No newline at end of file +console.log(dictionary.getItems()); //Object {Gandalf: "gandalf@email.com", Tyrion: "tyrion@email.com"} From d0ebbf9b87573ceb29240e177c7f69448aacc5b8 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Thu, 25 Aug 2016 09:18:00 -0300 Subject: [PATCH 62/70] removed print tree function (did not exist) --- chapter08/02-UsingBinarySearchTree.js | 4 ---- 1 file changed, 4 deletions(-) diff --git a/chapter08/02-UsingBinarySearchTree.js b/chapter08/02-UsingBinarySearchTree.js index 41f2c691..eb139837 100644 --- a/chapter08/02-UsingBinarySearchTree.js +++ b/chapter08/02-UsingBinarySearchTree.js @@ -50,7 +50,3 @@ tree.inOrderTraverse(printNode); console.log('********* raw data structure ***********'); console.log(tree.getRoot()); - -console.log('********* printing HTML tree ***********'); -var parent = document.getElementsByTagName('body')[0]; -printHTMLTree(tree.getRoot(), parent, 255); \ No newline at end of file From 78685366d9fa14d5e1d8c84e359f1336782a1330 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Thu, 1 Sep 2016 14:10:05 -0300 Subject: [PATCH 63/70] closes #13 --- chapter07/07-HashCollisionLinearProbing.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/chapter07/07-HashCollisionLinearProbing.js b/chapter07/07-HashCollisionLinearProbing.js index 74fdbac5..38b07c0f 100644 --- a/chapter07/07-HashCollisionLinearProbing.js +++ b/chapter07/07-HashCollisionLinearProbing.js @@ -46,10 +46,10 @@ function HashLinearProbing(){ return table[position].value; } else { var index = ++position; - while (table[index] === undefined || table[index].key !== key){ + while (table[index] !== undefined && (table[index] && table[index].key !== key)){ index++; } - if (table[index].key === key) { + if (table[index] && table[index].key === key) { return table[index].value; } } @@ -82,4 +82,4 @@ function HashLinearProbing(){ } } }; -} \ No newline at end of file +} From 2a89e21fc883821c6da1068c8d6f4b659f9f7fb3 Mon Sep 17 00:00:00 2001 From: Victor Wang <2501211450@qq.com> Date: Sun, 11 Sep 2016 16:19:51 +0800 Subject: [PATCH 64/70] Update 05-CircularLinkedList2.js fix some errors --- chapter05/05-CircularLinkedList2.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/chapter05/05-CircularLinkedList2.js b/chapter05/05-CircularLinkedList2.js index 13f36665..5aab62d0 100644 --- a/chapter05/05-CircularLinkedList2.js +++ b/chapter05/05-CircularLinkedList2.js @@ -133,8 +133,8 @@ let CircularLinkedList2 = (function () { remove(element) { - let index = indexOf(element); - return removeAt(index); + let index = this.indexOf(element); + return this.removeAt(index); } indexOf(element) { @@ -198,4 +198,4 @@ let CircularLinkedList2 = (function () { } } return CircularLinkedList2; -})(); \ No newline at end of file +})(); From 94b2c6826736363a03443aa905ae051dda030169 Mon Sep 17 00:00:00 2001 From: beizhedenglong <2501211450@qq.com> Date: Sun, 11 Sep 2016 23:26:57 +0800 Subject: [PATCH 65/70] fix bug in CircularLinkedList There is a bug in insert function. If you insert an element in an empty list at the first position. It will throw a TypeError: Cannot read property 'next' of null. --- chapter05/05-CircularLinkedList.js | 27 +++++++++++++++++---------- chapter05/05-CircularLinkedList2.js | 21 ++++++++++++--------- 2 files changed, 29 insertions(+), 19 deletions(-) diff --git a/chapter05/05-CircularLinkedList.js b/chapter05/05-CircularLinkedList.js index 5f05e85f..c3151148 100644 --- a/chapter05/05-CircularLinkedList.js +++ b/chapter05/05-CircularLinkedList.js @@ -46,16 +46,22 @@ function CircularLinkedList() { index = 0; if (position === 0){ //add on first position - - node.next = current; - - //update last element - while(current.next !== head){ //last element will be head instead of NULL - current = current.next; + + if(!head){ // if no node in list + head = node; + node.next = head; + }else{ + node.next = current; + + //update last element + while(current.next !== head){ //last element will be head instead of NULL + current = current.next; + } + + head = node; + current.next = head; } - - head = node; - current.next = head; + } else { while (index++ < position){ @@ -180,4 +186,5 @@ function CircularLinkedList() { this.print = function(){ console.log(this.toString()); }; -} \ No newline at end of file +} + diff --git a/chapter05/05-CircularLinkedList2.js b/chapter05/05-CircularLinkedList2.js index 5aab62d0..6f7574ef 100644 --- a/chapter05/05-CircularLinkedList2.js +++ b/chapter05/05-CircularLinkedList2.js @@ -58,15 +58,18 @@ let CircularLinkedList2 = (function () { if (position === 0) { //add on first position - node.next = current; - - //update last element - while (current.next !== this.getHead()) { //last element will be head instead of NULL - current = current.next; - } - - head.set(this, node); - current.next = this.getHead(); + if(!this.getHead()) { // if no node in list + head.set(this, node); + node.next = this.getHead(); + } else { + node.next = current; + //update last element + while(current.next !== this.getHead()) { //last element will be head instead of NULL + current = current.next; + } + head.set(this, node); + current.next = this.getHead(); + } } else { while (index++ < position) { From c2eb4acefba97503766ac59158d299c22a56c5f8 Mon Sep 17 00:00:00 2001 From: TerryX Date: Wed, 2 Nov 2016 23:21:11 +0800 Subject: [PATCH 66/70] Fix aValues being undefined --- chapter02/06-ES6Methods.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapter02/06-ES6Methods.js b/chapter02/06-ES6Methods.js index 60468aa4..bf4eb36a 100644 --- a/chapter02/06-ES6Methods.js +++ b/chapter02/06-ES6Methods.js @@ -40,7 +40,7 @@ console.log(aKeys.next()); // {value: 1, done: false } console.log(aKeys.next()); // {value: 2, done: false } console.log('Array.values'); -//let aValues = numbers.values(); +let aValues = numbers.values(); console.log(aValues.next()); // {value: 1, done: false } done false means iterator has more values console.log(aValues.next()); // {value: 2, done: false } console.log(aValues.next()); // {value: 3, done: false } From a5fc23e474e68f9edbf003271264e447d65310ac Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Mon, 17 Apr 2017 14:26:05 -0300 Subject: [PATCH 67/70] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 4e9eca37..64771d99 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ Source code of **Learning JavaScript Data Structures and Algorithms** book. | 1st edition | 2nd edition | | ------------- |:-------------:| -| ![1st edition](https://d1ldz4te4covpm.cloudfront.net/sites/default/files/imagecache/ppv4_main_book_cover/4874OS_Learning%20JavaScript%20Data%20Structures%20and%20Algorithms.jpg) | ![2nd edition](https://dz13w8afd47il.cloudfront.net/sites/default/files/imagecache/ppv4_main_book_cover/B05348_MockupCover_Normal.jpg) | +| ![1st edition](https://d1ldz4te4covpm.cloudfront.net/sites/default/files/imagecache/ppv4_main_book_cover/4874OS_Learning%20JavaScript%20Data%20Structures%20and%20Algorithms.jpg) | ![2nd edition](https://d255esdrn735hr.cloudfront.net/sites/default/files/imagecache/ppv4_main_book_cover/5493OS_5348_Learning%20JavaScript%20Data%20Structures%20and%20Algorithms,%20Second%20Edition.jpg) | | [Book link](http://amzn.to/1Y1OWPx)| [Book link](http://amzn.to/1TSkcA1)| Book link - first edition: @@ -17,6 +17,7 @@ Book link - first edition: Book link - second edition: - [Packt](https://www.packtpub.com/web-development/learning-javascript-data-structures-and-algorithms-second-edition) - [Amazon](http://amzn.to/1TSkcA1) + - [Brazilian Portuguese version](https://novatec.com.br/livros/estruturas-de-dados-algoritmos-em-javascript/) ### List of Chapters: From c44e74918af79cb45532cc7423bdcb3a853f27fd Mon Sep 17 00:00:00 2001 From: loiane Date: Mon, 21 Aug 2017 09:57:03 -0300 Subject: [PATCH 68/70] fixes #23 --- chapter07/07-HashCollisionLinearProbing.js | 9 +++++++++ chapter07/08-UsingHashCollisionLinearProbing.js | 8 ++++++++ 2 files changed, 17 insertions(+) diff --git a/chapter07/07-HashCollisionLinearProbing.js b/chapter07/07-HashCollisionLinearProbing.js index 38b07c0f..4b1172be 100644 --- a/chapter07/07-HashCollisionLinearProbing.js +++ b/chapter07/07-HashCollisionLinearProbing.js @@ -53,6 +53,15 @@ function HashLinearProbing(){ return table[index].value; } } + } else { //search for possible deleted value + var index = ++position; + while (table[index] == undefined || index == table.length || + (table[index] !== undefined && table[index] && table[index].key !== key)){ + index++; + } + if (table[index] && table[index].key === key) { + return table[index].value; + } } return undefined; }; diff --git a/chapter07/08-UsingHashCollisionLinearProbing.js b/chapter07/08-UsingHashCollisionLinearProbing.js index 902384ee..36a33e61 100644 --- a/chapter07/08-UsingHashCollisionLinearProbing.js +++ b/chapter07/08-UsingHashCollisionLinearProbing.js @@ -26,4 +26,12 @@ console.log('**** Remove **** '); hashLinearProbing.remove('Gandalf'); console.log(hashLinearProbing.get('Gandalf')); +hashLinearProbing.print(); + +console.log('**** Remove Test 2 **** '); +console.log('Removing Jonathan', hashLinearProbing.remove('Jonathan')); +console.log('**** Print **** '); +hashLinearProbing.print(); +console.log('Get Jamie', hashLinearProbing.get('Jamie')); +console.log('**** Print **** '); hashLinearProbing.print(); \ No newline at end of file From 10b24fd4a3ec01aa8db5a5bffb29e55559647dae Mon Sep 17 00:00:00 2001 From: loiane Date: Thu, 7 Sep 2017 09:18:28 -0300 Subject: [PATCH 69/70] gitignore --- .gitignore | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 6fee6d3a..2458e8b0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ .idea/* -*.log \ No newline at end of file +*.log +node_modules +coverage From f06567601501477cb470a8e0b59cfb9f36d8d19d Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Mon, 20 Nov 2017 13:09:10 -0200 Subject: [PATCH 70/70] Update 14-ES6ParameterHandling.js --- chapter01/14-ES6ParameterHandling.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapter01/14-ES6ParameterHandling.js b/chapter01/14-ES6ParameterHandling.js index 4645f2a7..af23585c 100644 --- a/chapter01/14-ES6ParameterHandling.js +++ b/chapter01/14-ES6ParameterHandling.js @@ -14,7 +14,7 @@ function sum2 (x, y, z) { z = 3; return x + y + z; }; -console.log(sum2(4,2)); //outpus 10 +console.log(sum2(4,2)); //outpus 9 //******* EcmaScript 6: spread operator ('...') var params = [3, 4, 5];