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 diff --git a/README.md b/README.md index 48f5d487..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: @@ -29,10 +30,9 @@ 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 -* 11: Pattern of algorithms -* 12: More about algorithms -* 13: Functional programming and data structures +* 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: [Algorithm Complexity](https://github.com/loiane/javascript-datastructures-algorithms/tree/second-edition/chapter12) ### First Edition source code: diff --git a/chapter01/14-ES6ParameterHandling.js b/chapter01/14-ES6ParameterHandling.js index 706c2059..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]; @@ -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)); 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 } 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(); 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 13f36665..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) { @@ -133,8 +136,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 +201,4 @@ let CircularLinkedList2 = (function () { } } return CircularLinkedList2; -})(); \ No newline at end of file +})(); 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"} diff --git a/chapter07/07-HashCollisionLinearProbing.js b/chapter07/07-HashCollisionLinearProbing.js index 74fdbac5..4b1172be 100644 --- a/chapter07/07-HashCollisionLinearProbing.js +++ b/chapter07/07-HashCollisionLinearProbing.js @@ -46,13 +46,22 @@ 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; } } + } 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; }; @@ -82,4 +91,4 @@ function HashLinearProbing(){ } } }; -} \ No newline at end of file +} 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 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 diff --git a/chapter10/01-SortingSearchingAlgorithms.js b/chapter10/01-SortingSearchingAlgorithms.js index b4081024..916e7403 100755 --- a/chapter10/01-SortingSearchingAlgorithms.js +++ b/chapter10/01-SortingSearchingAlgorithms.js @@ -6,16 +6,22 @@ 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(){ return array.join(); }; + this.array= function(){ + return array; + }; + this.bubbleSort = function(){ var length = array.length; @@ -25,7 +31,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 +90,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 +176,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 +185,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 +204,158 @@ function ArrayList(){ return array; }; + this.heapSort = function(){ + var heapSize = array.length; + + buildHeap(array); + + 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){ + 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('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); + } + }; + + 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 = 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 sorted ' + i + ': ' + buckets[i].join()); + + for (var j = 0; j < buckets[i].length; j++) { + array.push(buckets[i][j]); + } + } + }; + + 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 + + + + + + + + + \ No newline at end of file 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 diff --git a/chapter11/06-KnapSackProblemRecursive.html b/chapter11/06-KnapSackProblemRecursive.html new file mode 100644 index 00000000..cc000756 --- /dev/null +++ b/chapter11/06-KnapSackProblemRecursive.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ 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 diff --git a/chapter11/07-KnapSackProblemGreedy.html b/chapter11/07-KnapSackProblemGreedy.html new file mode 100644 index 00000000..227d7b4b --- /dev/null +++ b/chapter11/07-KnapSackProblemGreedy.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ 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 + + + + + + + + + \ 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 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 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 + + + + + + + + + \ 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 + + + + + + + + + \ 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 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