Complete "longest common ..." examples (#100)

* no else return

* fix var ref

* fix importing/requiring dependencies

* complete longest common examples
This commit is contained in:
Max Beatty
2019-03-28 14:52:55 -07:00
committed by Aditya Bhargava
parent c23ca90b83
commit 5b675cc2e8
22 changed files with 235 additions and 125 deletions

View File

@@ -3,14 +3,10 @@
* @param {Array} arr Array of numbers
* @return {number} Sum of the numbers
*/
function sumReduce( arr ) {
var result = newArr.reduce( ( curr, prev ) => {
return curr + prev;
} );
return result;
function sumReduce(arr) {
return arr.reduce(function(curr, prev) {
return curr + prev;
});
}
var arr = [1, 2, 3, 4];
console.log( sumReduce( arr ) ); // 10
console.log(sumReduce([1, 2, 3, 4])); // 10

View File

@@ -1,13 +1,13 @@
const arr = [1, 2, 3, 4];
/**
* Sums values in array recursively
* @param {Array} arr Array of numbers
* @return {number} Sum of the numbers
*/
const sumRecursive = ( arr ) => {
if ( arr.length == 1 ) return arr[0];
return arr[0] + sumRecursive( arr.slice( 1 ) );
};
function sumRecursive(arr) {
if (arr.length == 1) {
return arr[0];
}
return arr[0] + sumRecursive(arr.slice(1));
}
console.log( sumRecursive( arr ) ); // 10
console.log(sumRecursive([1, 2, 3, 4])); // 10

View File

@@ -1,18 +1,19 @@
'use strict';
function quicksort(array) {
if (array.length < 2) {
// base case, arrays with 0 or 1 element are already "sorted"
return array;
} else {
// recursive case
let pivot = array[0];
// sub-array of all the elements less than the pivot
let less = array.slice(1).filter(function(el) { return el <= pivot; });
// sub-array of all the elements greater than the pivot
let greater = array.slice(1).filter(function(el) { return el > pivot; });
return quicksort(less).concat([pivot], quicksort(greater));
}
// recursive case
let pivot = array[0];
// sub-array of all the elements less than the pivot
let less = array.slice(1).filter(function(el) {
return el <= pivot;
});
// sub-array of all the elements greater than the pivot
let greater = array.slice(1).filter(function(el) {
return el > pivot;
});
return quicksort(less).concat([pivot], quicksort(greater));
}
console.log(quicksort([10, 5, 2, 3])); // [2, 3, 5, 10]