From 124f6680db4867abb2e16caa0cad543597ebcbe9 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 27 Feb 2016 15:56:38 -0300 Subject: [PATCH 01/44] 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 02/44] 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 03/44] 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 04/44] 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 05/44] 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 06/44] 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 07/44] 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 08/44] 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 09/44] 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 10/44] 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 11/44] 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 12/44] 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 13/44] 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 14/44] 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 15/44] 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 16/44] 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 17/44] 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 18/44] 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 19/44] 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 20/44] 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 21/44] 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 22/44] 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 23/44] 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 24/44] 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 25/44] 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 26/44] 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 27/44] 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 28/44] 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 29/44] 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 30/44] 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 31/44] 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 32/44] 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 33/44] 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 34/44] 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 35/44] 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 36/44] 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 37/44] 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 38/44] 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 39/44] 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 40/44] 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 41/44] 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 42/44] 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 43/44] 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 44/44] 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];