From 6630498a99e2688052a8d06234888c6037e0e685 Mon Sep 17 00:00:00 2001 From: Niezwan Date: Tue, 2 Oct 2018 10:58:55 +0800 Subject: [PATCH 001/101] Add Selection sort --- sorting/selectionSort.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 sorting/selectionSort.js diff --git a/sorting/selectionSort.js b/sorting/selectionSort.js new file mode 100644 index 0000000..09a8870 --- /dev/null +++ b/sorting/selectionSort.js @@ -0,0 +1,28 @@ +// JavaScript implementation of selection sort +// +// Author: Niezwan Abdul Wahid + +function selectionSort(arr){ + let min, temp; + let len = arr.length; + for(let i = 0; i < len; i++){ + min = i; + for(let j = i+1; j Date: Tue, 2 Oct 2018 00:03:55 -0300 Subject: [PATCH 002/101] Create insertionSort.js --- sorting/insertionSort.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 sorting/insertionSort.js diff --git a/sorting/insertionSort.js b/sorting/insertionSort.js new file mode 100644 index 0000000..84c77f6 --- /dev/null +++ b/sorting/insertionSort.js @@ -0,0 +1,18 @@ +function insertionSort (items) { + for (var i = 0; i < items.length; i++) { + let value = items[i] + // store the current item value so it can be placed right + for (var j = i - 1; j > -1 && items[j] > value; j--) { + // loop through the items in the sorted array (the items from the current to the beginning) + // copy each item to the next one + items[j + 1] = items[j] + } + // the last item we've reached should now hold the value of the currently sorted item + items[j + 1] = value + } + + return list +} + +const list = [54, 26, 93, 17, 77, 31, 44, 55, 20] +console.log(insertionSort(list)) // [ 17, 20, 26, 31, 44, 54, 55, 77, 93 ] From fa86c1629f13808e91266c287fc588e59800b4db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ot=C3=A1vio=20Pace?= Date: Tue, 2 Oct 2018 00:14:08 -0300 Subject: [PATCH 003/101] Add quickSort on sorting folder --- sorting/quickSort.js | 58 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 sorting/quickSort.js diff --git a/sorting/quickSort.js b/sorting/quickSort.js new file mode 100644 index 0000000..7aad746 --- /dev/null +++ b/sorting/quickSort.js @@ -0,0 +1,58 @@ +function quickSort (recievedArray) { + const sortedArray = Object.assign([], recievedArray) + + function partition (array, begin, end) { + const pivot = array[Math.floor((end + begin) / 2)] + let i = begin + let j = end + + while (i <= j) { + while (array[i] < pivot) { + i++ + } + + while (array[j] > pivot) { + j-- + } + + if (i <= j) { + swap(array, i, j) + i++ + j-- + } + } + + return i + } + + function sort (array, begin, end) { + let index + + if (array.length > 1) { + index = partition(array, begin, end) + + if (begin < index - 1) + sort(array, begin, index - 1) + + if (index < end) + sort(array, index, end) + } + + return array + } + + function swap (array, firstIndex, secondIndex) { + const temp = array[firstIndex] + array[firstIndex] = array[secondIndex] + array[secondIndex] = temp + } + + return sort(sortedArray, 0, sortedArray.length - 1) +} + +const array = [3, 2, 9, 7, 24, 11] + +const sortedArray = quickSort(array) + +console.log('array', array) +console.log('sortedArray', sortedArray) From d2ee2a45be1a7f572fbc180d6be175b4ae72cdd3 Mon Sep 17 00:00:00 2001 From: Niezwan Date: Tue, 2 Oct 2018 11:22:10 +0800 Subject: [PATCH 004/101] Add Sequential Search --- searches/sequentialSearch.js | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 searches/sequentialSearch.js diff --git a/searches/sequentialSearch.js b/searches/sequentialSearch.js new file mode 100644 index 0000000..c9bb298 --- /dev/null +++ b/searches/sequentialSearch.js @@ -0,0 +1,20 @@ +// JavaScript implementation of Sequential Search + +// Author: Niezwan Abdul Wahid + +let items = [3,7,33,42,5,66,44,65,20,34] + +function sequentialSearch(item) { + for(let i=0; i < items.length; i++) { + if(items[i] === item) { + console.log( item + " found at index " + i); + return true; + } + } + return false; +} + +let item = sequentialSearch(33); +if(!item) { + console.log('Item is not in array.'); +} \ No newline at end of file From 6095bda2686e73ad8a79644a1ba726f2850824b7 Mon Sep 17 00:00:00 2001 From: Niraj Nandish Date: Tue, 2 Oct 2018 07:26:08 +0400 Subject: [PATCH 005/101] Create fibonnaci.js --- math-algos/fibonnaci.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 math-algos/fibonnaci.js diff --git a/math-algos/fibonnaci.js b/math-algos/fibonnaci.js new file mode 100644 index 0000000..65e343d --- /dev/null +++ b/math-algos/fibonnaci.js @@ -0,0 +1,17 @@ +// FIBONACCI SEQUENCE + +var fibonacci_series = function (n) +{ + if (n===1) + { + return [0, 1]; + } + else + { + var s = fibonacci_series(n - 1); + s.push(s[s.length - 1] + s[s.length - 2]); + return s; + } +}; + + console.log(fibonacci_series(8)); From 930cfeefa828d01b7b3c94fdfbd0f6ab7b9f8c37 Mon Sep 17 00:00:00 2001 From: Nikolas Huebecker Date: Mon, 1 Oct 2018 23:32:44 -0400 Subject: [PATCH 006/101] Create Math Folder and checkPrime.js --- math/checkPrime.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 math/checkPrime.js diff --git a/math/checkPrime.js b/math/checkPrime.js new file mode 100644 index 0000000..bf2f4b8 --- /dev/null +++ b/math/checkPrime.js @@ -0,0 +1,25 @@ +// JavaScript implementation of prime number checking +// +// Author: Nikolas Huebecker + +function isPrime(n){ + var divisor = 2; + + while (n > divisor){ + if(n % divisor == 0){ + return false; + }else { + divisor++; + } + } + return true; +} + +// Test + +console.log("The number 137 is prime:" +console.log(isPrime(137)) + + +console.log("The number 16 is prime:" +console.log(isPrime(16)) From 1201e26253d4b878457d54d7e902341a4dfe0bae Mon Sep 17 00:00:00 2001 From: Dito Date: Tue, 2 Oct 2018 11:34:06 +0800 Subject: [PATCH 007/101] create countingSort --- sorting/countingSort.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 sorting/countingSort.js diff --git a/sorting/countingSort.js b/sorting/countingSort.js new file mode 100644 index 0000000..4e9e187 --- /dev/null +++ b/sorting/countingSort.js @@ -0,0 +1,29 @@ +// JavaScript implementation of counting sort + +function countingSort(arr, min, max) + { + let i, z = 0, count = []; + + for (i = min; i <= max; i++) { + count[i] = 0; + } + + for (i=0; i < arr.length; i++) { + count[arr[i]]++; + } + + for (i = min; i <= max; i++) { + while (count[i]-- > 0) { + arr[z++] = i; + } + } + return arr; +} + +//Test +let array = [2, 0, 3, 5, 4, 1]; +console.log(array.length); +console.log("Original Array"); +console.log(array); +console.log("Sorted Array"); +console.log(countingSort(array, 0, 5)); \ No newline at end of file From d86b41255b4329f041ba0ac6e6229a8e80ea7c3e Mon Sep 17 00:00:00 2001 From: Niezwan Date: Tue, 2 Oct 2018 11:34:08 +0800 Subject: [PATCH 008/101] add Binary Search --- searches/binarySearch.js | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 searches/binarySearch.js diff --git a/searches/binarySearch.js b/searches/binarySearch.js new file mode 100644 index 0000000..21e780b --- /dev/null +++ b/searches/binarySearch.js @@ -0,0 +1,32 @@ +// JavaScript implementation of Binary Search + +// Author: Niezwan Abdul Wahid + +// Binary Search only applicable to a sorted array + +let arrayOfItems = [1, 3, 5, 7, 9, 11, 13, 15, 16, 19, 22]; + +function binarySearch(arrayOfItems, itemToFind) { + let low = 0; + let high = arrayOfItems.length - 1; + let mid, pointer; + + while(low <= high) { + mid = Math.floor((low + high) / 2), + pointer = arrayOfItems[mid]; + + if(pointer === itemToFind) { + console.log('Found ' + pointer + " at index " + mid); + return; + } + if(itemToFind < pointer) { + high = mid - 1; + } else { + low = mid + 1; + } + } + console.log("Item not found"); + return null; +} + +binarySearch(arrayOfItems, 7); \ No newline at end of file From b0ce6ff6cd805b4814d8f1763f937167cb990089 Mon Sep 17 00:00:00 2001 From: Starlynne Date: Mon, 1 Oct 2018 20:34:54 -0700 Subject: [PATCH 009/101] Add A. Kondov's mergeSort JS implementation --- sorting/mergeSort.js | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 sorting/mergeSort.js diff --git a/sorting/mergeSort.js b/sorting/mergeSort.js new file mode 100644 index 0000000..c3d57bc --- /dev/null +++ b/sorting/mergeSort.js @@ -0,0 +1,42 @@ + +// Split the array into halves and merge them recursively +function mergeSort(arr) { + if (arr.length === 1) { + // return once we hit an array with a single item + return arr + } + + const middle = Math.floor(arr.length / 2) // get the middle item of the array rounded down + const left = arr.slice(0, middle) // items on the left side + const right = arr.slice(middle) // items on the right side + + return merge( + mergeSort(left), + mergeSort(right) + ) +} + +// compare the arrays item by item and return the concatenated result +function merge(left, right) { + let result = [] + let indexLeft = 0 + let indexRight = 0 + + while (indexLeft < left.length && indexRight < right.length) { + if (left[indexLeft] < right[indexRight]) { + result.push(left[indexLeft]) + indexLeft++ + } else { + result.push(right[indexRight]) + indexRight++ + } + } + + return result.concat(left.slice(indexLeft)).concat(right.slice(indexRight)) +} + +const list = [2, 5, 1, 3, 7, 2, 3, 8, 6, 3] +console.log(mergeSort(list)) + + +//A. Kondov, Medium \ No newline at end of file From 96dcbc59c6b16567783b46d9c816e9efc006aa6a Mon Sep 17 00:00:00 2001 From: Quentin Freire Novo Date: Mon, 1 Oct 2018 23:35:07 -0400 Subject: [PATCH 010/101] Add HextoRgb and RgbToHex --- sorting/color.js | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 sorting/color.js diff --git a/sorting/color.js b/sorting/color.js new file mode 100644 index 0000000..3b25098 --- /dev/null +++ b/sorting/color.js @@ -0,0 +1,14 @@ +function HexToRGB(hex) +{ + var bigint = parseInt(hex, 16); + var r = (bigint >> 16) & 255; + var g = (bigint >> 8) & 255; + var b = bigint & 255; + + return new RGB(r, g, b); + +} + +function RGBToHex(rgb) { + return '#' + ((1 << 24) + (rgb.r << 16) + (rgb.g << 8) + rgb.b).toString(16).slice(1); + } From eddadd3ba67e3d03d921726ece0c400a2a474401 Mon Sep 17 00:00:00 2001 From: Tiffany White Date: Mon, 1 Oct 2018 23:35:58 -0400 Subject: [PATCH 011/101] Add quicksort implementation --- sorting/quick-sort.js | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 sorting/quick-sort.js diff --git a/sorting/quick-sort.js b/sorting/quick-sort.js new file mode 100644 index 0000000..21dc9f0 --- /dev/null +++ b/sorting/quick-sort.js @@ -0,0 +1,42 @@ +/* Quick Sort: +Pick a pivot at end of array +Put larger values to the right and smaller to the left +Repeat for both sides putting all smaller values to the left and larger to the right */ + +function quickSort(arr, left, right) { + var len = arr.length, + pivot, + partitionIndex; + + if (left < right) { + pivot = right; + partitionIndex = partition(arr, pivot, left, right); + + //sort left and right + quickSort(arr, left, partitionIndex - 1); + quickSort(arr, partitionIndex + 1, right); + } + return arr; +} + +function partition(arr, pivot, left, right) { + var pivotValue = arr[pivot], + partitionIndex = left; + + for (var i = left; i < right; i++) { + if (arr[i] < pivotValue) { + swap(arr, i, partitionIndex); + partitionIndex++; + } + } + swap(arr, right, partitionIndex); + return partitionIndex; +} +function swap(arr, i, j) { + var temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; +} + +quickSort([5, 9, 16, 2, 4, 1, 7], 0, 7); +// [1, 2, 4, 5, 7, 9, 16] From 5292e7463e846e13c04aba7c35d1951d65899ae3 Mon Sep 17 00:00:00 2001 From: Abraham Hernandez Date: Mon, 1 Oct 2018 23:38:01 -0400 Subject: [PATCH 012/101] move to correct folder --- {math-algos => math}/fibonnaci.js | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {math-algos => math}/fibonnaci.js (100%) diff --git a/math-algos/fibonnaci.js b/math/fibonnaci.js similarity index 100% rename from math-algos/fibonnaci.js rename to math/fibonnaci.js From 6fc014972ae2aade276b07236b1def8dba046005 Mon Sep 17 00:00:00 2001 From: Dito Date: Tue, 2 Oct 2018 11:38:03 +0800 Subject: [PATCH 013/101] countingSort --- sorting/countingSort.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/sorting/countingSort.js b/sorting/countingSort.js index 4e9e187..ddc557b 100644 --- a/sorting/countingSort.js +++ b/sorting/countingSort.js @@ -1,4 +1,6 @@ // JavaScript implementation of counting sort +// +// Author: Dito Baskoro function countingSort(arr, min, max) { @@ -26,4 +28,4 @@ console.log(array.length); console.log("Original Array"); console.log(array); console.log("Sorted Array"); -console.log(countingSort(array, 0, 5)); \ No newline at end of file +console.log(countingSort(array, 0, 5)); From 607f661d4d9eeeae0a90c18e413e12833eab2b60 Mon Sep 17 00:00:00 2001 From: Nikolas Huebecker Date: Mon, 1 Oct 2018 23:39:30 -0400 Subject: [PATCH 014/101] Create fibonacci.js --- math/fibonacci.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 math/fibonacci.js diff --git a/math/fibonacci.js b/math/fibonacci.js new file mode 100644 index 0000000..217a0cd --- /dev/null +++ b/math/fibonacci.js @@ -0,0 +1,23 @@ +// JavaScript implementation of Fibonacci item finder +// +// Author: Nikoals Huebecker + +function fibonacci(n){ + var fib = [0, 1]; + + if (n <= 2) return 1; + + for (var i = 2; i <=n; i++ ){ + fib[i] = fib[i-1]+fib[i-2]; + } + + return fib[n]; +} + +// Test + +console.log("The first item of the sequence is:") +console.log(fibonacci(1)) + +console.log("The tweleth item of the sequence is:") +console.log(fibonacci(12)) From d184d3a0fd4763cd07c159ba9f7b729a5e8f868d Mon Sep 17 00:00:00 2001 From: Nikolas Huebecker Date: Mon, 1 Oct 2018 23:43:29 -0400 Subject: [PATCH 015/101] Update fibonacci.js --- math/fibonacci.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/math/fibonacci.js b/math/fibonacci.js index 217a0cd..458673a 100644 --- a/math/fibonacci.js +++ b/math/fibonacci.js @@ -2,6 +2,8 @@ // // Author: Nikoals Huebecker +// Time Complexity O(n) + function fibonacci(n){ var fib = [0, 1]; From 60702828d5ee3ad8798da6ee33508cbae1ac08cf Mon Sep 17 00:00:00 2001 From: Nikolas Huebecker Date: Mon, 1 Oct 2018 23:43:36 -0400 Subject: [PATCH 016/101] Create fibonacci-recursive.js --- math/fibonacci-recursive.js | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 math/fibonacci-recursive.js diff --git a/math/fibonacci-recursive.js b/math/fibonacci-recursive.js new file mode 100644 index 0000000..2cc2ae6 --- /dev/null +++ b/math/fibonacci-recursive.js @@ -0,0 +1,20 @@ +/ JavaScript recursive implementation of Fibonacci item finder +// +// Author: Nikoals Huebecker + +// Time Complexity O(2^n) + +function fibonacci(n){ + if(n<=1) + return n; + else + return fibonacci(n-1) + fibonacci (n-2); +} + +// Test + +console.log("The first item of the sequence is:") +console.log(fibonacci(1)) + +console.log("The tweleth item of the sequence is:") +console.log(fibonacci(12)) From 9bcd8511498a3dcab94085615a6aac20c9a6a442 Mon Sep 17 00:00:00 2001 From: brendanAlbert Date: Mon, 1 Oct 2018 20:44:51 -0700 Subject: [PATCH 017/101] Create binarySearch.js --- searching/binarySearch.js | 57 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 searching/binarySearch.js diff --git a/searching/binarySearch.js b/searching/binarySearch.js new file mode 100644 index 0000000..715fdce --- /dev/null +++ b/searching/binarySearch.js @@ -0,0 +1,57 @@ +/** + JavaScript implementation of the binary search algorithm. + + Author: Brendan Albert + + This is a JavaScript iterative (rather than recursive) implementation of the binary search algorithm. + + The binary search algorithm works by looking at the middle element of a list. + The list must be sorted to work correctly. + This implementation uses ascending order. + + If the value being searched for is not the middle element, then we check + if the value is smaller or larger than the middle element. + + This allows the size of the list being searched to be halved each iteration. + + The big O runtime of this algorithm is log(n). + Log(n) is nice because it means that given a huge list, say of 1 million IDs, + it will take no more than 20 iterations to determine if the ID is present. + + Arguments: value (that we are searching for), list_to_search (the list) + + Return: the value if it is found in the list or -1 if the value is not found. + */ +function binarySearch(value, list_to_search) { + + search_value = -1 + max_index = list_to_search.length - 1 + min_index = 0 + middle_index = Math.floor( (max_index + min_index) / 2) + current_element = list_to_search[middle_index] + + while (max_index >= min_index) { + + if (current_element == value) + return current_element + + else if (value > current_element) + min_index = middle_index + 1 + + else if (value < current_element) + max_index = middle_index - 1 + + middle_index = Math.floor( (min_index + max_index) / 2) + current_element = list_to_search[middle_index] + + } + + return search_value +} + +// Sample lists to test with +id_list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] +odd_list = [1,3,5,7,9,11,13,15,17,19] +short_list = ['allie', 'ben', 'charlie', 'danielle', 'emilio', 'fred', 'gina', 'henry', 'isabella'] + +console.log(binarySearch(3, odd_list)) From bab78d11df8581b56b0441e73a7520f667ec8189 Mon Sep 17 00:00:00 2001 From: Abraham Hernandez Date: Mon, 1 Oct 2018 23:46:18 -0400 Subject: [PATCH 018/101] Revert "Add quicksort implementation" --- sorting/quick-sort.js | 42 ------------------------------------------ 1 file changed, 42 deletions(-) delete mode 100644 sorting/quick-sort.js diff --git a/sorting/quick-sort.js b/sorting/quick-sort.js deleted file mode 100644 index 21dc9f0..0000000 --- a/sorting/quick-sort.js +++ /dev/null @@ -1,42 +0,0 @@ -/* Quick Sort: -Pick a pivot at end of array -Put larger values to the right and smaller to the left -Repeat for both sides putting all smaller values to the left and larger to the right */ - -function quickSort(arr, left, right) { - var len = arr.length, - pivot, - partitionIndex; - - if (left < right) { - pivot = right; - partitionIndex = partition(arr, pivot, left, right); - - //sort left and right - quickSort(arr, left, partitionIndex - 1); - quickSort(arr, partitionIndex + 1, right); - } - return arr; -} - -function partition(arr, pivot, left, right) { - var pivotValue = arr[pivot], - partitionIndex = left; - - for (var i = left; i < right; i++) { - if (arr[i] < pivotValue) { - swap(arr, i, partitionIndex); - partitionIndex++; - } - } - swap(arr, right, partitionIndex); - return partitionIndex; -} -function swap(arr, i, j) { - var temp = arr[i]; - arr[i] = arr[j]; - arr[j] = temp; -} - -quickSort([5, 9, 16, 2, 4, 1, 7], 0, 7); -// [1, 2, 4, 5, 7, 9, 16] From 7f550f6962cbaaff6f4e268bc0f5d8dcc674eb0a Mon Sep 17 00:00:00 2001 From: Dito Date: Tue, 2 Oct 2018 11:49:54 +0800 Subject: [PATCH 019/101] create heapSort --- sorting/heapSort.js | 52 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 sorting/heapSort.js diff --git a/sorting/heapSort.js b/sorting/heapSort.js new file mode 100644 index 0000000..f79a411 --- /dev/null +++ b/sorting/heapSort.js @@ -0,0 +1,52 @@ +// JavaScript implementation of heap sort +// +// Author: Dito Baskoro + +let array_length; +/* to create MAX array */ +function heap_root(input, i) { + let left = 2 * i + 1; + let right = 2 * i + 2; + let max = i; + + if (left < array_length && input[left] > input[max]) { + max = left; + } + + if (right < array_length && input[right] > input[max]) { + max = right; + } + + if (max != i) { + swap(input, i, max); + heap_root(input, max); + } +} + +function swap(input, index_A, index_B) { + let temp = input[index_A]; + + input[index_A] = input[index_B]; + input[index_B] = temp; +} + +function heapSort(input) { + + array_length = input.length; + + for (let i = Math.floor(array_length / 2); i >= 0; i -= 1) { + heap_root(input, i); + } + + for (i = input.length - 1; i > 0; i--) { + swap(input, 0, i); + array_length--; + + + heap_root(input, 0); + } +} + +let arr = [3, 0, 2, 5, -1, 4, 1]; +heapSort(arr); +console.log(arr); \ No newline at end of file From 84ab14918a39f7cce7f55049a04b7f07acaa4158 Mon Sep 17 00:00:00 2001 From: Quentin Freire Novo Date: Mon, 1 Oct 2018 23:50:27 -0400 Subject: [PATCH 020/101] DistanceVectoriel --- sorting/Distance.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 sorting/Distance.js diff --git a/sorting/Distance.js b/sorting/Distance.js new file mode 100644 index 0000000..797710c --- /dev/null +++ b/sorting/Distance.js @@ -0,0 +1,18 @@ +function GetDistanceBetweenPoints(v1, v2) { + let dx = v1.x - v2.x; + let dy = v1.y - v2.y; + let dz = v1.z - v2.z; + + return Math.sqrt(dx * dx + dy * dy + dz * dz); +} +function GetDistanceBetweenPointsXZ(v1, v2) { + let v13f = new Vector3f(v1.x, 0.0, v1.z); + let v14f = new Vector3f(v2.x, 0.0, v2.z); + return GetDistanceBetweenPoints(v13f, v14f); +} + +function GetDistanceBetweenPointsXY(v1, v2) { + let v13f = new Vector3f(v1.x, v1.y, 0.0); + let v14f = new Vector3f(v2.x, v2.y, 0.0); + return GetDistanceBetweenPoints(v13f, v14f); +} From d7489547713ba7bd877d636c3fab9bd99234898a Mon Sep 17 00:00:00 2001 From: Dito Date: Tue, 2 Oct 2018 11:52:17 +0800 Subject: [PATCH 021/101] add test --- sorting/heapSort.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sorting/heapSort.js b/sorting/heapSort.js index f79a411..002f4ad 100644 --- a/sorting/heapSort.js +++ b/sorting/heapSort.js @@ -47,6 +47,6 @@ function heapSort(input) { } } -let arr = [3, 0, 2, 5, -1, 4, 1]; +const arr = [3, 0, 2, 5, -1, 4, 1, -2]; heapSort(arr); -console.log(arr); \ No newline at end of file +console.log(arr); From 77d2516cc6591297e1ec6721bb5f9f1f73a891fb Mon Sep 17 00:00:00 2001 From: Niezwan Date: Tue, 2 Oct 2018 11:52:35 +0800 Subject: [PATCH 022/101] Add factorial --- math/factorial.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 math/factorial.js diff --git a/math/factorial.js b/math/factorial.js new file mode 100644 index 0000000..03820a6 --- /dev/null +++ b/math/factorial.js @@ -0,0 +1,15 @@ +// JavaScript implementation of Factorial + +// Author: Niezwan Abdul Wahid + +function factorial(number) { + let val = 1; + + for (let i = 2; i <= number; i += 1) { + val *= i; + } + + return val; +} + +//factorial(13) === 6 227 020 800 \ No newline at end of file From 9a08234af479b3b37a98f36174e4206ba75b331d Mon Sep 17 00:00:00 2001 From: Tiffany White Date: Mon, 1 Oct 2018 23:55:16 -0400 Subject: [PATCH 023/101] Add Dijkstra's algorithm --- others/dijkstras-algorithm.js | 99 +++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 others/dijkstras-algorithm.js diff --git a/others/dijkstras-algorithm.js b/others/dijkstras-algorithm.js new file mode 100644 index 0000000..46d2308 --- /dev/null +++ b/others/dijkstras-algorithm.js @@ -0,0 +1,99 @@ +// One of the algorithms I was to use in my Microsoft interview was Dijkstra's algorithm. Here is a basic implementation. +function PriorityQueue() { + this._nodes = []; + + this.enqueue = function(priority, key) { + this._nodes.push({key: key, priority: priority }); + this.sort(); + }; + this.dequeue = function() { + return this._nodes.shift().key; + }; + this.sort = function() { + this._nodes.sort(function (a, b) { + return a.priority - b.priority; + }); + }; + this.isEmpty = function() { + return !this._nodes.length; + }; +} + +/** + * Pathfinding starts here + */ +function Graph(){ + var INFINITY = 1/0; + this.vertices = {}; + + this.addVertex = function(name, edges){ + this.vertices[name] = edges; + }; + + this.shortestPath = function(start, finish) { + var nodes = new PriorityQueue(), + distances = {}, + previous = {}, + path = [], + smallest, vertex, neighbor, alt; + + for (vertex in this.vertices) { + if (vertex === start) { + distances[vertex] = 0; + nodes.enqueue(0, vertex); + } + else { + distances[vertex] = INFINITY; + nodes.enqueue(INFINITY, vertex); + } + + previous[vertex] = null; + } + + while (!nodes.isEmpty()) { + smallest = nodes.dequeue(); + + if (smallest === finish) { + path = []; + + while (previous[smallest]) { + path.push(smallest); + smallest = previous[smallest]; + } + + break; + } + + if (!smallest || distances[smallest] === INFINITY){ + continue; + } + + for (neighbor in this.vertices[smallest]) { + alt = distances[smallest] + this.vertices[smallest][neighbor]; + + if (alt < distances[neighbor]) { + distances[neighbor] = alt; + previous[neighbor] = smallest; + + nodes.enqueue(alt, neighbor); + } + } + } + + return path; + }; +} + +var g = new Graph(); + +g.addVertex('A', {B: 7, C: 8}); +g.addVertex('B', {A: 7, F: 2}); +g.addVertex('C', {A: 8, F: 6, G: 4}); +g.addVertex('D', {F: 8}); +g.addVertex('E', {H: 1}); +g.addVertex('F', {B: 2, C: 6, D: 8, G: 9, H: 3}); +g.addVertex('G', {C: 4, F: 9}); +g.addVertex('H', {E: 1, F: 3}); + +// Log test, with the addition of reversing the path and prepending the first node so it's more readable +console.log(g.shortestPath('A', 'H').concat(['A']).reverse()); From aa61a107e4b724ca214595d4cacb7b5e2cfa0fff Mon Sep 17 00:00:00 2001 From: Niezwan Date: Tue, 2 Oct 2018 11:58:25 +0800 Subject: [PATCH 024/101] Degree Radian Conversion --- math/degreeRadianConversion.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 math/degreeRadianConversion.js diff --git a/math/degreeRadianConversion.js b/math/degreeRadianConversion.js new file mode 100644 index 0000000..8356f6d --- /dev/null +++ b/math/degreeRadianConversion.js @@ -0,0 +1,16 @@ +// JavaScript implementation of Degree-Radian Conversion + +// Author: Niezwan Abdul Wahid + +function degreeToRadian(degree) { + return degree * (Math.PI / 180); +} + +function radianToDegree(radian) { + return radian * (180 / Math.PI); +} + + +//degreeToRadian(180) === 3.1415926 + +//radianToDegree(3.1415) === 179.994 \ No newline at end of file From c2acc64dd65cbd48f04d447f6c914605922f254e Mon Sep 17 00:00:00 2001 From: Dito Date: Tue, 2 Oct 2018 12:00:42 +0800 Subject: [PATCH 025/101] create gnomeSort --- sorting/gnomeSort.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 sorting/gnomeSort.js diff --git a/sorting/gnomeSort.js b/sorting/gnomeSort.js new file mode 100644 index 0000000..4bf15af --- /dev/null +++ b/sorting/gnomeSort.js @@ -0,0 +1,27 @@ +// JavaScript implementation of gnome sort +// +// Author: Dito Baskoro + +function gnomeSort(arr) +{ + function moveBack(i) + { + for( ; i > 0 && arr[i-1] > arr[i]; i--) + { + let t = arr[i]; + arr[i] = arr[i-1]; + arr[i-1] = t; + } + } + for (let i = 1; i < arr.length; i++) + { + if (arr[i-1] > arr[i]) moveBack(i); + } + return arr; +} + +const array = [3, 0, 2, 5, -1, 4, 1, -2]; +console.log("Original Array"); +console.log(array); +console.log("Sorted Array"); +console.log(gnomeSort(array)); From 962ddf37c5e30105958bf5387cdc8cebec6abd48 Mon Sep 17 00:00:00 2001 From: Dito Date: Tue, 2 Oct 2018 12:06:46 +0800 Subject: [PATCH 026/101] create flashSort --- sorting/flashSort.js | 83 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 sorting/flashSort.js diff --git a/sorting/flashSort.js b/sorting/flashSort.js new file mode 100644 index 0000000..a16027b --- /dev/null +++ b/sorting/flashSort.js @@ -0,0 +1,83 @@ +// JavaScript implementation of flash sort +// Flashsort is a distribution sorting algorithm showing linear computational complexity O(n) +// +// Author: Dito Baskoro + +function flash_sort(arr) + { + let max = 0, min = arr[0]; + let n = arr.length; + let m = ~~(0.45 * n); + let l = new Array(m); + + for (let i = 1; i < n; ++i) { + if (arr[i] < min) { + min = arr[i]; + } + if (arr[i] > arr[max]) { + max = i; + } + } + + if (min === arr[max]) { + return arr; + } + + let c1 = (m - 1) / (arr[max] - min); + + + for (let k = 0; k < m; k++) { + l[k] = 0; + } + for (let j = 0; j < n; ++j) { + k = ~~(c1 * (arr[j] - min)); + ++l[k]; + } + + for (let p = 1; p < m; ++p) { + l[p] = l[p] + l[p - 1]; + } + + let hold = arr[max]; + arr[max] = arr[0]; + arr[0] = hold; + + //permutation + let move = 0, t, flash; + j = 0; + k = m - 1; + + while (move < (n - 1)) { + while (j > (l[k] - 1)) { + ++j; + k = ~~(c1 * (arr[j] - min)); + } + if (k < 0) break; + flash = arr[j]; + while (j !== l[k]) { + k = ~~(c1 * (flash - min)); + hold = arr[t = --l[k]]; + arr[t] = flash; + flash = hold; + ++move; + } + } + + //insertion + for (j = 1; j < n; j++) { + hold = arr[j]; + i = j - 1; + while (i >= 0 && arr[i] > hold) { + arr[i + 1] = arr[i--]; + } + arr[i + 1] = hold; + } + return arr; +} + +//test +const array = [3, 0, 2, 5, -1, 4, 1, -2]; +console.log("Original Array"); +console.log(array); +console.log("Sorted Array"); +console.log(flash_sort(array, 0, 5)); From 85c109ac49e012fa2a328661bae5fc5d2c16e2fd Mon Sep 17 00:00:00 2001 From: Abraham Hernandez Date: Tue, 2 Oct 2018 00:30:10 -0400 Subject: [PATCH 027/101] Rename others/dijkstras-algorithm.js to graphs/dijkstra.js moved to correct folder --- others/dijkstras-algorithm.js => graphs/dijkstra.js | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename others/dijkstras-algorithm.js => graphs/dijkstra.js (100%) diff --git a/others/dijkstras-algorithm.js b/graphs/dijkstra.js similarity index 100% rename from others/dijkstras-algorithm.js rename to graphs/dijkstra.js From aed19088d6c6c02e92c13e417919d99e69123124 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Jos=C3=A9?= Date: Mon, 1 Oct 2018 23:31:57 -0500 Subject: [PATCH 028/101] Sum of n natural numbers --- math/naturalNumbersSum | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 math/naturalNumbersSum diff --git a/math/naturalNumbersSum b/math/naturalNumbersSum new file mode 100644 index 0000000..1cab9d1 --- /dev/null +++ b/math/naturalNumbersSum @@ -0,0 +1,7 @@ +// Change this as the limit of numbers to be added +// const lastNumber = 4 // 1+2+3+4 +const lastNumber = 5 // 1+2+3+4+4 + + +let sum = lastNumber*(1+lastNumber)*0.5 +console.log(sum) From edeb408c6ba0530f94f11318f1d1403bcd30238c Mon Sep 17 00:00:00 2001 From: Gaston Che Date: Tue, 2 Oct 2018 05:32:59 +0100 Subject: [PATCH 029/101] [sorting] added algorithim for bogo search --- .gitignore | 1 + sorting/BogoSort.js | 47 +++++++++++++++++++++++++++++++++++++++++++++ sorting/README.md | 27 ++++++++++++++++++++++++++ 3 files changed, 75 insertions(+) create mode 100644 .gitignore create mode 100644 sorting/BogoSort.js create mode 100644 sorting/README.md diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ba698c7 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.vscode/launch.json diff --git a/sorting/BogoSort.js b/sorting/BogoSort.js new file mode 100644 index 0000000..1fb43e0 --- /dev/null +++ b/sorting/BogoSort.js @@ -0,0 +1,47 @@ +/* +* In computer science, bogosort is a particularly ineffective sorting algorithm based on the generate and test paradigm. The algorithm successively generates permutations of its input until it finds one that is sorted. It is not useful for sorting, but may be used for educational purposes, to contrast it with other more realistic algorithms. +*/ + +function Bogosort(arr){ + var isSorted = function(arr){ + for(var i = 1; i < arr.length; i++){ + if (arr[i-1] > arr[i]) { + return false; + } + } + return true; + }; + + function shuffle(arr){ + var count = arr.length, temp, index; + + while(count > 0){ + index = Math.floor(Math.random() * count); + count--; + + temp = arr[count]; + arr[count] = arr[index]; + arr[index] = temp; + } + + return arr; + } + + function sort(arr){ + var sorted = false; + while(!sorted){ + arr = shuffle(arr); + sorted = isSorted(arr); + } + return arr; + } + + return sort(arr); +} + + +var array = [3, 0, 2, 5, -1, 4, 1]; +console.log("Original Array Elements"); +console.log(array); +console.log("Sorted Array Elements"); +console.log(Bogosort(array)); \ No newline at end of file diff --git a/sorting/README.md b/sorting/README.md new file mode 100644 index 0000000..0a7a239 --- /dev/null +++ b/sorting/README.md @@ -0,0 +1,27 @@ +
+ +
+
+ +
+
+

Sorting ▲lgorithms implemented in Javascript

+
+ +## Contents + +- [Bogo Search]() + In computer science, bogosort is a particularly ineffective sorting algorithm based on the generate and test paradigm. The algorithm successively generates permutations of its input until it finds one that is sorted. It is not useful for sorting, but may be used for educational purposes, to contrast it with other more realistic algorithms. + + + +## License + +This work is licensed under a [MIT License](https://github.com/abranhe/algorithms/blob/master/LICENSE) + +[![MIT IMG][mit-license]]((https://github.com/abranhe/algorithms/blob/master/LICENSE)) + +To the extent possible under law, [Carlos Abraham](https://go.abranhe.com/github) has waived all copyright and related or neighboring rights to this work. + + +[mit-license]: https://cdn.abraham.gq/projects/algorithms/mit-license.png From dde576efd6bb5c4ee1f3eb5ce8beb3e34a63a71c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Jos=C3=A9?= Date: Mon, 1 Oct 2018 23:34:59 -0500 Subject: [PATCH 030/101] Rename naturalNumbersSum to naturalNumbersSum.js --- math/{naturalNumbersSum => naturalNumbersSum.js} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename math/{naturalNumbersSum => naturalNumbersSum.js} (100%) diff --git a/math/naturalNumbersSum b/math/naturalNumbersSum.js similarity index 100% rename from math/naturalNumbersSum rename to math/naturalNumbersSum.js From 8572ffa13cc8e23319bfa7e27b878459e04b634b Mon Sep 17 00:00:00 2001 From: Gaston Che Date: Tue, 2 Oct 2018 05:49:57 +0100 Subject: [PATCH 031/101] Added gnome sort --- sorting/README.md | 28 ++++++++++++++++++++++++++++ sorting/gnomesort.js | 27 +++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 sorting/README.md create mode 100644 sorting/gnomesort.js diff --git a/sorting/README.md b/sorting/README.md new file mode 100644 index 0000000..b5e612c --- /dev/null +++ b/sorting/README.md @@ -0,0 +1,28 @@ +
+ +
+
+ +
+
+

Sorting ▲lgorithms implemented in Javascript

+
+ +## Contents + +- [Gnome Sort]() + Gnome sort is a sorting algorithm originally proposed by Dr. Hamid Sarbazi-Azad (Professor of Computer Engineering at Sharif University of Technology) in 2000 and called "stupid sort"[1] (not to be confused with bogosort), and then later on described by Dick Grune and named "gnome sort". + The algorithm always finds the first place where two adjacent elements are in the wrong order, and swaps them. It takes advantage of the fact that performing a swap can introduce a new out-of-order adjacent pair only next to the two swapped elements.. + + + +## License + +This work is licensed under a [MIT License](https://github.com/abranhe/algorithms/blob/master/LICENSE) + +[![MIT IMG][mit-license]]((https://github.com/abranhe/algorithms/blob/master/LICENSE)) + +To the extent possible under law, [Carlos Abraham](https://go.abranhe.com/github) has waived all copyright and related or neighboring rights to this work. + + +[mit-license]: https://cdn.abraham.gq/projects/algorithms/mit-license.png diff --git a/sorting/gnomesort.js b/sorting/gnomesort.js new file mode 100644 index 0000000..8a2909f --- /dev/null +++ b/sorting/gnomesort.js @@ -0,0 +1,27 @@ +/* +* Gnome sort is a sorting algorithm originally proposed by Dr. Hamid Sarbazi-Azad (Professor of Computer Engineering at Sharif University of Technology) in 2000 and called "stupid sort"[1] (not to be confused with bogosort), and then later on described by Dick Grune and named "gnome sort". The algorithm always finds the first place where two adjacent elements are in the wrong order, and swaps them. It takes advantage of the fact that performing a swap can introduce a new out-of-order adjacent pair only next to the two swapped elements. +*/ + +function gnomeSort(arr) +{ + function moveBack(i) + { + for( ; i > 0 && arr[i-1] > arr[i]; i--) + { + var t = arr[i]; + arr[i] = arr[i-1]; + arr[i-1] = t; + } + } + for (var i = 1; i < arr.length; i++) + { + if (arr[i-1] > arr[i]) moveBack(i); + } + return arr; +} + +var arra = [3, 0, 2, 5, -1, 4, 1]; +console.log("Original Array Elements"); +console.log(arra); +console.log("Sorted Array Elements"); +console.log(gnomeSort(arra)); From c5ec915a7feaea9f4a1073a15c934fa87573c881 Mon Sep 17 00:00:00 2001 From: Abraham Hernandez Date: Tue, 2 Oct 2018 00:59:54 -0400 Subject: [PATCH 032/101] Delete .gitignore --- .gitignore | 1 - 1 file changed, 1 deletion(-) delete mode 100644 .gitignore diff --git a/.gitignore b/.gitignore deleted file mode 100644 index ba698c7..0000000 --- a/.gitignore +++ /dev/null @@ -1 +0,0 @@ -.vscode/launch.json From 0d8da48926f11dc4ead57e0dccde72736e79b0bf Mon Sep 17 00:00:00 2001 From: Abraham Hernandez Date: Tue, 2 Oct 2018 01:01:21 -0400 Subject: [PATCH 033/101] Delete README.md Added description on -> @allalgorithms/algorithms --- sorting/README.md | 27 --------------------------- 1 file changed, 27 deletions(-) delete mode 100644 sorting/README.md diff --git a/sorting/README.md b/sorting/README.md deleted file mode 100644 index 0a7a239..0000000 --- a/sorting/README.md +++ /dev/null @@ -1,27 +0,0 @@ -
- -
-
- -
-
-

Sorting ▲lgorithms implemented in Javascript

-
- -## Contents - -- [Bogo Search]() - In computer science, bogosort is a particularly ineffective sorting algorithm based on the generate and test paradigm. The algorithm successively generates permutations of its input until it finds one that is sorted. It is not useful for sorting, but may be used for educational purposes, to contrast it with other more realistic algorithms. - - - -## License - -This work is licensed under a [MIT License](https://github.com/abranhe/algorithms/blob/master/LICENSE) - -[![MIT IMG][mit-license]]((https://github.com/abranhe/algorithms/blob/master/LICENSE)) - -To the extent possible under law, [Carlos Abraham](https://go.abranhe.com/github) has waived all copyright and related or neighboring rights to this work. - - -[mit-license]: https://cdn.abraham.gq/projects/algorithms/mit-license.png From 1e759d5444de0978ec0c1daddcf49cec2b1f2104 Mon Sep 17 00:00:00 2001 From: Dito Date: Tue, 2 Oct 2018 13:18:10 +0800 Subject: [PATCH 034/101] create pancakeSort --- sorting/pancakeSort.js | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 sorting/pancakeSort.js diff --git a/sorting/pancakeSort.js b/sorting/pancakeSort.js new file mode 100644 index 0000000..8adee30 --- /dev/null +++ b/sorting/pancakeSort.js @@ -0,0 +1,39 @@ +// JavaScript implementation of pancake sort + +function pancake_sort(arr) { + for (let i = arr.length - 1; i >= 1; i--) { + // find the index of the largest element not yet sorted + let max_idx = 0; + let max = arr[0]; + for (let j = 1; j <= i; j++) { + if (arr[j] > max) { + max = arr[j]; + max_idx = j; + } + } + + if (max_idx == i) + continue; // element already in place + + let new_slice; + + // flip arr max element to index 0 + if (max_idx > 0) { + new_slice = arr.slice(0, max_idx+1).reverse(); + for ( j = 0; j <= max_idx; j++) + arr[j] = new_slice[j]; + } + + // then flip the max element to its place + new_slice = arr.slice(0, i+1).reverse(); + for ( j = 0; j <= i; j++) + arr[j] = new_slice[j]; + } + return arr; +} + +const array = [3, 0, 2, 5, -1, 4, 1]; +console.log("Original Array"); +console.log(array); +console.log("Sorted Array"); +console.log(pancake_sort(array, 0, 5)); From 2e9bc33792971acfffe265d4d925657f1086a7a9 Mon Sep 17 00:00:00 2001 From: Dito Date: Tue, 2 Oct 2018 13:25:01 +0800 Subject: [PATCH 035/101] create greatestCommonDivisor --- math/greatestCommonDivisor.js | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 math/greatestCommonDivisor.js diff --git a/math/greatestCommonDivisor.js b/math/greatestCommonDivisor.js new file mode 100644 index 0000000..62a85c6 --- /dev/null +++ b/math/greatestCommonDivisor.js @@ -0,0 +1,11 @@ +// JavaScript implementation of greatest common divisor of two positive number + +let gcd = function(a, b) { + if (!b) { + return a; + } + + return gcd(b, a % b); +}; + +console.log(gcd(2154, 458)); \ No newline at end of file From 3eabb477fe5ca8348367d159716e2a60dcdb834a Mon Sep 17 00:00:00 2001 From: Ionut Alixandroae Date: Tue, 2 Oct 2018 08:55:47 +0300 Subject: [PATCH 036/101] Create shellSort.js --- sorting/shellSort.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 sorting/shellSort.js diff --git a/sorting/shellSort.js b/sorting/shellSort.js new file mode 100644 index 0000000..17beecd --- /dev/null +++ b/sorting/shellSort.js @@ -0,0 +1,13 @@ +function shellsort(array) { + for(var g = 0; g < gaps.length; g++) { + var gap = gaps[g]; + for(var i = gap; i < array.length; i++) { + var temp = array[i]; + for(var j = i; j >= gap && array[j - gap] > temp; j -= gap) { + array[j] = array[j - gap]; + } + array[j] = temp; + } + } + return array; +} From af79dc483addd8601c2befd729148e4c5a6c0cd4 Mon Sep 17 00:00:00 2001 From: Ionut Alixandroae Date: Tue, 2 Oct 2018 09:02:52 +0300 Subject: [PATCH 037/101] Create checkPrime.js --- other/checkPrime.js | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 other/checkPrime.js diff --git a/other/checkPrime.js b/other/checkPrime.js new file mode 100644 index 0000000..ce5d74b --- /dev/null +++ b/other/checkPrime.js @@ -0,0 +1,12 @@ +function isPrime(n){ + var divisor = 2; + + while (n > divisor){ + if(n % divisor == 0){ + return false; + } + else + divisor++; + } + return true; +} From 27d14ef1859fd38aa79417af6327efaae413c99f Mon Sep 17 00:00:00 2001 From: Ionut Alixandroae Date: Tue, 2 Oct 2018 09:03:40 +0300 Subject: [PATCH 038/101] Update checkPrime.js --- other/checkPrime.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/other/checkPrime.js b/other/checkPrime.js index ce5d74b..3d5c2a2 100644 --- a/other/checkPrime.js +++ b/other/checkPrime.js @@ -10,3 +10,6 @@ function isPrime(n){ } return true; } + +// isPrime(137); true +// isPrime(237); false From 188d25152f3af41dfd33e2f77b2c357a73255c2a Mon Sep 17 00:00:00 2001 From: Ionut Alixandroae Date: Tue, 2 Oct 2018 09:04:11 +0300 Subject: [PATCH 039/101] Create primeFactors.js --- other/primeFactors.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 other/primeFactors.js diff --git a/other/primeFactors.js b/other/primeFactors.js new file mode 100644 index 0000000..ccf6f08 --- /dev/null +++ b/other/primeFactors.js @@ -0,0 +1,17 @@ +function primeFactors(n){ + var factors = [], + divisor = 2; + + while(n>2){ + if(n % divisor == 0){ + factors.push(divisor); + n= n/ divisor; + } + else{ + divisor++; + } + } + return factors; +} + +// primeFactors(69); [3, 23] From bdc904f52a1934e6af7f26410d65db4c32c1f2a4 Mon Sep 17 00:00:00 2001 From: Ferdhika Yudira Date: Tue, 2 Oct 2018 14:07:32 +0700 Subject: [PATCH 040/101] Add quadrant algo --- math/quadrant.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 math/quadrant.js diff --git a/math/quadrant.js b/math/quadrant.js new file mode 100644 index 0000000..020fa29 --- /dev/null +++ b/math/quadrant.js @@ -0,0 +1,21 @@ +// Author: Ferdhika Yudira +// Quadrant detector + +var quadrant = function (x, y){ + var quadrant = 4; + + if(x > 0 && y > 0){ + quadrant = 1; + }else if(x < 0 && y > 0){ + quadrant = 2; + }else if(x < 0 && y < 0){ + quadrant = 3; + } + + return quadrant; +} + +// test +console.log(quadrant(-5, 2)); +console.log(quadrant(5, 2)); +console.log(quadrant(-5, -2)); \ No newline at end of file From fbec5a6e5dd9275c09ec92a4b1dda0a030b35109 Mon Sep 17 00:00:00 2001 From: Ferdhika Yudira Date: Tue, 2 Oct 2018 14:13:52 +0700 Subject: [PATCH 041/101] Add palindrome algo --- strings/palindrome.js | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 strings/palindrome.js diff --git a/strings/palindrome.js b/strings/palindrome.js new file mode 100644 index 0000000..7b50aa9 --- /dev/null +++ b/strings/palindrome.js @@ -0,0 +1,31 @@ +// Author: Ferdhika Yudira +// Palindrome + +var isPalindrome = function (text){ + text = text.split(''); + index=0; + palindrom=true; + + pTeks=text.length; + + i=0; + while((i Date: Tue, 2 Oct 2018 10:07:25 +0100 Subject: [PATCH 042/101] added evenNumber to math.js --- math/evenNumbers.js | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 math/evenNumbers.js diff --git a/math/evenNumbers.js b/math/evenNumbers.js new file mode 100644 index 0000000..ec5bf6d --- /dev/null +++ b/math/evenNumbers.js @@ -0,0 +1,7 @@ +// Check For Even Numbers +// Author: Abejide Femi + +function evenNumber(arr) { + return arr.filter(a => a % 2 === 0); +} +console.log([1,2,5,6,8,12]) // returns [2,6,8,12] \ No newline at end of file From 4a17a23cc583a112a497df3cb8777351eccaa320 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Karabu=C5=82a-Stysiak?= Date: Tue, 2 Oct 2018 13:56:53 +0200 Subject: [PATCH 043/101] Add DFS and BFS algorithms --- graphs/bfs.js | 44 ++++++++++++++++++++++++++++++++++++++++++++ graphs/dfs.js | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 graphs/bfs.js create mode 100644 graphs/dfs.js diff --git a/graphs/bfs.js b/graphs/bfs.js new file mode 100644 index 0000000..96f6348 --- /dev/null +++ b/graphs/bfs.js @@ -0,0 +1,44 @@ +/* + A non-recursive implementation of bfs with worst-case space complexity O(|E|) +*/ + +function Vertex (name, neighbours) { + this.name = name; + this.neighbours = neighbours; +} + +function bfs (root) { + var visited = {} + var stack = [] + + stack.push(root) + while(!!stack.length) { + var vertex = stack.shift() + + if (!visited[vertex.name]) { + visited[vertex.name] = true + console.log('Visiting vertex ', vertex.name) + + var len = vertex.neighbours.length + for (var index = 0; index < len; index++) { + stack.push(vertex.neighbours[index]) + } + } + } +} + +var root = new Vertex('root', [ + new Vertex('child 1', [ + new Vertex('grandchild 1', []), new Vertex('grandchild 2', []) + ]), + new Vertex('child 2', [ + new Vertex('grandchild 3', []), + ]), + new Vertex('child 3', [ + new Vertex('grandchild 4', [ + new Vertex('grandgrandchild 1', []) + ]), + ]), +]) + +bfs(root) diff --git a/graphs/dfs.js b/graphs/dfs.js new file mode 100644 index 0000000..bcbfe8e --- /dev/null +++ b/graphs/dfs.js @@ -0,0 +1,46 @@ +/* + A non-recursive implementation of DFS with worst-case space complexity O(|E|) + + according to wiki pseudocode https://en.wikipedia.org/wiki/Depth-first_search +*/ + +function Vertex (name, neighbours) { + this.name = name; + this.neighbours = neighbours; +} + +function dfs (root) { + var visited = {} + var stack = [] + + stack.push(root) + while(!!stack.length) { + var vertex = stack.pop() + + if (!visited[vertex.name]) { + visited[vertex.name] = true + console.log('Visiting vertex ', vertex.name) + + var len = vertex.neighbours.length + for (var index = 0; index < len; index++) { + stack.push(vertex.neighbours[index]) + } + } + } +} + +var root = new Vertex('root', [ + new Vertex('child 1', [ + new Vertex('grandchild 1', []), new Vertex('grandchild 2', []) + ]), + new Vertex('child 2', [ + new Vertex('grandchild 3', []), + ]), + new Vertex('child 3', [ + new Vertex('grandchild 4', [ + new Vertex('grandgrandchild 1', []) + ]), + ]), +]) + +dfs(root) From b205c6678d1c5e03515211e9bb32898cdf0c0407 Mon Sep 17 00:00:00 2001 From: Ajit Singh Date: Tue, 2 Oct 2018 18:34:54 +0530 Subject: [PATCH 044/101] add gcd and spiralmatrix --- math/gcd.js | 13 +++++++++++++ math/spiralMatrix.js | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 math/gcd.js create mode 100644 math/spiralMatrix.js diff --git a/math/gcd.js b/math/gcd.js new file mode 100644 index 0000000..f7f4889 --- /dev/null +++ b/math/gcd.js @@ -0,0 +1,13 @@ +// GCD - greatest common divisor or HCF - highest common factor + +function gcd (small, large) { + if (small === 0) { return large } else { return gcd(large % small, small) } +} + +const gcdList = [[6, 9], [6, 12], [12, 18], [7, 14], [7, 13]] + +for (const set of gcdList) { + const small = set[0] + const large = set[1] + console.log(`GCD for ${small} and ${large} is ${gcd(small, large)}`) +} diff --git a/math/spiralMatrix.js b/math/spiralMatrix.js new file mode 100644 index 0000000..761c1f8 --- /dev/null +++ b/math/spiralMatrix.js @@ -0,0 +1,39 @@ +function getSpiralMatrix (n) { + const matrix = [] + for (let i = 0; i < n; ++i) { matrix.push([]) } + let counter = 1 + let startRow = 0 + let endRow = n - 1 + let startCol = 0 + let endCol = n - 1 + + while (startCol <= endCol && startRow <= endRow) { + for (let i = startCol; i <= endCol; ++i) { + matrix[startRow][i] = counter + counter++ + } + startRow++ + + for (let i = startRow; i <= endRow; ++i) { + matrix[i][endCol] = counter + counter++ + } + endCol-- + + for (let i = endCol; i >= startCol; --i) { + matrix[endRow][i] = counter + counter++ + } + endRow-- + + for (let i = endRow; i >= startRow; --i) { + matrix[i][startCol] = counter + counter++ + } + startCol++ + } + return matrix +} + +const matrix = getSpiralMatrix(3) +console.log(matrix) From c67793ac1019d16ea5bc8a56b876fb8c7553635f Mon Sep 17 00:00:00 2001 From: Shriharsha KL Date: Tue, 2 Oct 2018 19:29:32 +0530 Subject: [PATCH 045/101] Add checkPalindrome.js --- strings/checkPalindrome.js | 42 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 strings/checkPalindrome.js diff --git a/strings/checkPalindrome.js b/strings/checkPalindrome.js new file mode 100644 index 0000000..42fd27c --- /dev/null +++ b/strings/checkPalindrome.js @@ -0,0 +1,42 @@ +// JavaScript implementation of palindrome check +// +// Author: Shriharsha KL + +/** + * @description Check if the input is a palindrome + * + * @param {string|number} input + * @returns {boolean} is input a palindrome? + */ +function checkPalindrome(input) { + // Only strings and numbers can be palindrome + if (typeof input !== 'string' && typeof input !== 'number') { + return null; + } + + // Convert given number to string + if (typeof input === 'number') { + input = String(input); + } + + return input === input.split('').reverse().join(''); +} + +// Test +let input = 'ABCDCBA'; +console.log(checkPalindrome(input)); // true + +input = 12321; +console.log(checkPalindrome(input)); // true + +input = 123.321; +console.log(checkPalindrome(input)); // true + +input = 'ABCD'; +console.log(checkPalindrome(input)); // false + +input = 123.4; +console.log(checkPalindrome(input)); // false + +input = {}; +console.log(checkPalindrome(input)) // null From 2725988c4f149a83b041e3793d60bd9b6ac0f17b Mon Sep 17 00:00:00 2001 From: Shriharsha KL Date: Tue, 2 Oct 2018 19:47:59 +0530 Subject: [PATCH 046/101] Add computeNCR.js --- math/computeNCR.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 math/computeNCR.js diff --git a/math/computeNCR.js b/math/computeNCR.js new file mode 100644 index 0000000..0d3c7f1 --- /dev/null +++ b/math/computeNCR.js @@ -0,0 +1,17 @@ +// JavaScript implementation of nCr computation +// +// Author: Shriharsha KL + +function fact(n) { + if (n === 0) + return 1; + + return n * fact(n - 1); +} + +function nCr(n, r) { + return fact(n) / (fact(r) * fact(n - r)); +} + +// Test +console.log(nCr(10, 2)) \ No newline at end of file From afb9803f427ff319d02645be6fef7a134f4d925e Mon Sep 17 00:00:00 2001 From: PerfectOrphan31 Date: Tue, 2 Oct 2018 10:17:05 -0700 Subject: [PATCH 047/101] Added recursive variant of factorial and added temperature conversions. --- math/factorial-recursive.js | 15 +++++++++++++++ math/tempConversion.js | 27 +++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 math/factorial-recursive.js create mode 100644 math/tempConversion.js diff --git a/math/factorial-recursive.js b/math/factorial-recursive.js new file mode 100644 index 0000000..8f7a73b --- /dev/null +++ b/math/factorial-recursive.js @@ -0,0 +1,15 @@ +// JavaScript implementation of recursive factorial + +// Author: Jay McDoniel + +function factorial(number) { + let retNum = number ? number : 1; + if (number >= 2) { + retNum *= factorial(number - 1); + } + return retNum; +} + +for (let i = 0; i < 20; i++) { + console.log(factorial(i)); +} \ No newline at end of file diff --git a/math/tempConversion.js b/math/tempConversion.js new file mode 100644 index 0000000..f5e9da8 --- /dev/null +++ b/math/tempConversion.js @@ -0,0 +1,27 @@ +// JavaScript Temperature Conversion + +// Author: Jay McDoniel + +function FtoC (fTemp) { + return (fTemp - 32) * (5 / 9); +} + +function FtoK (fTemp) { + return (fTemp - 32) * (5 / 9) + 273; +} + +function CtoF (cTemp) { + return cTemp * 9 / 5 + 32; +} + +function CtoK (cTemp) { + return cTemp + 273; +} + +function KtoF (kTemp) { + return (kTemp - 273) * 9 / 5 + 32; +} + +function KtoC (kTemp) { + return kTemp - 273; +} \ No newline at end of file From 80aa694197bd1ea3f3110a747dc3debcded35787 Mon Sep 17 00:00:00 2001 From: Muhammad Irsyad Date: Wed, 3 Oct 2018 00:53:33 +0700 Subject: [PATCH 048/101] Add integer reversal algorithm --- strings/integerReversal.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 strings/integerReversal.js diff --git a/strings/integerReversal.js b/strings/integerReversal.js new file mode 100644 index 0000000..f4ce808 --- /dev/null +++ b/strings/integerReversal.js @@ -0,0 +1,19 @@ +// JS algorithm of Integer Reversal +// Author: Irsyad + +// Sample input and output +// reverse(81) will produce 18 +// reverse(-67) will produce -76 +// reverse(-500) will produce -5 + +const reverse = integer => + parseInt(integer + .toString() + .split("") + .reverse() + .join("") + ) * Math.sign(integer); + +// Test +console.log(reverse(4729)); +console.log(reverse(-270)); \ No newline at end of file From 481ad62b518ba1d37b76e0f06ae7e5dfeff6c630 Mon Sep 17 00:00:00 2001 From: Niezwan Date: Tue, 2 Oct 2018 13:29:30 +0800 Subject: [PATCH 049/101] ROT 13 implementation --- ciphers/rot13.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 ciphers/rot13.js diff --git a/ciphers/rot13.js b/ciphers/rot13.js new file mode 100644 index 0000000..30a9b22 --- /dev/null +++ b/ciphers/rot13.js @@ -0,0 +1,18 @@ +// JavaScript implementation of ROT13 +// +// Author: NIEZWAN ABDUL WAHID + +function rot13(str) { + var string = []; + + for (var i = 0; i < str.length; i++) { + if ((str.charCodeAt(i) > 77 && str.charCodeAt(i) <= 90) || (str.charCodeAt(i) > 109 && str.charCodeAt(i) <= 122)) { + string.push(String.fromCharCode(str.charCodeAt(i) - 13)); + } else { + string.push(String.fromCharCode(str.charCodeAt(i) + 13)); + } + } + return string.join(""); +} + +// rot13("hello") == "uryyb" \ No newline at end of file From 9fb0ddd09e2989269f2d3da159ff30fdf755e2ef Mon Sep 17 00:00:00 2001 From: borgatajunky Date: Tue, 2 Oct 2018 01:27:25 -0400 Subject: [PATCH 050/101] Add stings and pigLatin.js to repo --- strings/pigLatin.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 strings/pigLatin.js diff --git a/strings/pigLatin.js b/strings/pigLatin.js new file mode 100644 index 0000000..b2a9e14 --- /dev/null +++ b/strings/pigLatin.js @@ -0,0 +1,17 @@ +const pigLatin = str => { + const vows = ['a', 'e', 'i', 'o', 'u'], + res = str.split('') + + if(vows.includes(str.charAt(0))) { + return str += 'way' + } else { + for(let i = 0; i < str.length; i++) { + if(!vows.includes(str[i])) { + res.push(res.shift()) + } else { + res.push('ay') + return res.join('') + } + } + } +} \ No newline at end of file From 2789ecf661a6847727ab6862573921a2fe2c8b90 Mon Sep 17 00:00:00 2001 From: Paralect Dev Date: Tue, 2 Oct 2018 09:22:51 +0300 Subject: [PATCH 051/101] [Graphs] Breadth-first search --- graphs/breadth-first-search.js | 93 ++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 graphs/breadth-first-search.js diff --git a/graphs/breadth-first-search.js b/graphs/breadth-first-search.js new file mode 100644 index 0000000..e1cbe9b --- /dev/null +++ b/graphs/breadth-first-search.js @@ -0,0 +1,93 @@ +// Breadth-first Search +// author: Pavel Kalugin + +class Graph { + constructor(n) { + // the number of vertexes + this.n = n; + + // adjacency list representation + this.adjList = Array.from(Array(n), () => []); + } + + addDirectedEdge(from, to) { + this.adjList[from].push(to); + } + + addEdge(v, w) { + this.adjList[v].push(w); + this.adjList[w].push(v); + } + + // s - the number of the starting vertex + // to - the number of the end vertex + breadthFirstSearch(s) { + if (s < 0 || s >= this.n) { + throw Error('Wrong starting vertex'); + } + + let queue = []; + let visited = new Array(this.n); + let path = new Array(this.n); + let time = new Array(this.n).fill(-1); + + // The first iteration + queue.push(s); + visited[s] = true; + path[s] = -1; + time[s] = 0; + + while (queue.length > 0) { + let v = queue.shift(); + + for (let to of this.adjList[v]) { + if (!visited[to]) { + queue.push(to); + visited[to] = true; + path[to] = v; + time[to] = time[v] + 1; + } + } + } + + return { visited, path, time }; + } + + // Array of distances to vertexes from the starting one + BFS(s) { + return this.breadthFirstSearch(s).time; + } + + findPathToVertex(s, to) { + let { visited, path } = this.breadthFirstSearch(s); + + if (!visited[to]) { + return 'No path'; + } + + let realPath = []; + + for (let v = to; v !== -1; v = path[v]) { + realPath.unshift(v); + } + + return realPath.reduce((out, i) => `${out} ${i}`, `Path from ${s} to ${to}:`); + } +} + +function test() { + let g = new Graph(5); + + g.addDirectedEdge(0, 1); + g.addDirectedEdge(1, 2); + g.addDirectedEdge(2, 3); + g.addDirectedEdge(3, 3); + g.addDirectedEdge(4, 2) + g.addEdge(2, 0); + + + console.log(g.BFS(2)); + console.log(g.findPathToVertex(4, 1)); +} + +test(); From 7f58d295df307e9c94c371e8ab819f71216ea68c Mon Sep 17 00:00:00 2001 From: Melky Date: Tue, 2 Oct 2018 16:45:58 -0700 Subject: [PATCH 052/101] Add Shell Sorting --- sorting/ShellSort.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 sorting/ShellSort.js diff --git a/sorting/ShellSort.js b/sorting/ShellSort.js new file mode 100644 index 0000000..61df2d9 --- /dev/null +++ b/sorting/ShellSort.js @@ -0,0 +1,29 @@ +/* "Shell sort or Shell's method, is an in-place comparison sort. +It can be seen as either a generalization of sorting by exchange (bubble sort) or sorting by insertion (insertion sort). +The method starts by sorting pairs of elements far apart from each other, then progressively reducing the gap between elements to be compared. +Starting with far apart elements can move some out-of-place elements into position faster than a simple nearest neighbor exchange." */ + +function shellSort(arr) { + var increment = arr.length / 2; + while (increment > 0) { + for (i = increment; i < arr.length; i++) { + var j = i; + var temp = arr[i]; + + while (j >= increment && arr[j-increment] > temp) { + arr[j] = arr[j-increment]; + j = j - increment; + } + + arr[j] = temp; + } + + if (increment == 2) { + increment = 1; + } else { + increment = parseInt(increment*5 / 11); + } + } + return arr; +} + From dbb7064d873fca5a3c084d45602709fc70d5e265 Mon Sep 17 00:00:00 2001 From: Sheary Tan Date: Wed, 3 Oct 2018 08:50:58 +0800 Subject: [PATCH 053/101] linked-list added --- .../singly-link-list/singlyLinkList.js | 239 ++++++++++++++++++ 1 file changed, 239 insertions(+) create mode 100644 linked-list/singly-link-list/singlyLinkList.js diff --git a/linked-list/singly-link-list/singlyLinkList.js b/linked-list/singly-link-list/singlyLinkList.js new file mode 100644 index 0000000..1b3d5f0 --- /dev/null +++ b/linked-list/singly-link-list/singlyLinkList.js @@ -0,0 +1,239 @@ +// Implementation of single link list +// Author: Sheary Tan + +class Node { + constructor(val) { + this.val = val; + this.next = null; + } +} + +class SinglyList { + constructor() { + // Initializing... + // There is nothing at the beginning so + // the head & the tail should be empty, + // and the length should be zero too + this.head = null; + this.tail = null; + this.length = 0; + } + + // 1st method: push (push the val into the end of the list) + push(val) { + // Firstly, we have to accept a new value + var newNode = new Node(val); + // If there is no head, means there is nothing on the list, + // set the head & tail pointers to this value. + if(!this.head) { + this.head = newNode; + this.tail = newNode; + } else { + // If there is value existed, assign the newNode to the next value + // of the current existing value + this.tail.next = newNode; + // Update the tail to it! + this.tail = newNode; + } + // Increment the length and return the newly created link-list + this.length++; + return this; + } + + // 2nd method: pop (remove the last item) + pop() { + // If there is nothing on the list, return undefined + if (!this.head) return undefined; + // Loop through to find the last item + var current = this.head; + var newTail = current; + while(current.next) { + newTail = current; + current = current.next + } + // Set the found tail to tail + this.tail = newTail; + // The next one will be null since we + // would like to remove it + this.tail.next = null; + // Decrease the length + this.length--; + // If there is nothing left after removing + // set the head and tail to be null + if(this.length === 0) { + this.head = null; + this.tail = null; + } + return current; + } + + // 3rd method: shift (remove the first item) + shift() { + // If there is no nothing on the list, return undefined + if(!this.head) return undefined; + // Store the current head in a new variable + var currentHead = this.head; + // Shift the head to the next value of the currentHead + this.head = currentHead.next; + // Decrement the length since we have removed the head + this.length--; + if(this.length === 0) { + this.head = null; + this.tail = null; + } + return currentHead; + } + + // 4th method: unshift (add item to the beginning ) + unshift(val) { + // Initialize the value to a new node; + var newNode = new Node(val); + // If there is nothing on the list, set the head and tail + // point to that new node + if(!this.head) { + this.head = newNode; + this.tail = newNode; + } else { + // In order to set the head value points to the head, + // we have to set the current head to the next item of newNode + newNode.next = this.head; + // and now we can assign the head to newNode! + this.head = newNode + } + // Increment the length after adding the new head + this.length++; + return this; + } + + // 5th method: get + get(i) { + // get accepts an index in and find the specific value + // If i is less than zero, or greater and equal to the length + // of the current link list, return null; + if(i < 0 || i >= this.length) return null; + // Use the counter to find the value + var counter = 0; + var current = this.head; + while(counter !== i) { + current = current.next; + counter++ + } + // Found it and return + return current + } + + // 6th method: set + // Use the given index to find the target value and change it with the new + // given value + set(i, val) { + var targetNode = this.get(i); + if(targetNode) { + targetNode.val = val; + return true; + } + return false; + } + + // 8th method: remove (from any index) + remove(i) { + // Check if there's anything on the list + if(i < 0 || i >= this.length) return undefined; + if(i === 0) return this.shift(); + if(i === this.length - 1) return this.pop(); + // Get the previous item of the target + var previousTarget = this.get(i - 1); + // Since we've got the previous item of the target, + // we now can remove the target by setting the next item of previousTarget + // to the next item of "removed" + var removed = previousTarget.next; + previousTarget.next = removed.next + // Decrease the length + this.length--; + return removed; + } + + // 9th method: reverse + reverse() { + // Firstly we have to set the head to the tail, + // and the tail to the head + var target = this.head; + this.head = this.tail; + this.tail = target; + // Now we have to re-arrange those next & previous + // items of the list + var next; + var prev = null; + // Loop through every single item on the list + for(let i = 0; i < this.length; i++) { + // This part is a bit confusing, let's take an example + // Example = [1, 2, 3, 4, 5], T = target, P = previous, N = next + next = target.next; + // Firstly, the target is 1 + // [1, 2, 3, 4, 5] + // T + // And target.next is 2 + // [1, 2, 3, 4, 5] + // T N + target.next = prev; + // Remember our target is 1 & prev is null? Now it said the next item of + // 1 is null, + // 1 -> null + prev = target; + // Now we're setting the "prev = null" to the target value + // which now equals to "prev = 1" + // [1, 2, 3, 4, 5] + // P N + target = next; + // And lastly we set the "next" value to be T + // [1, 2, 3, 4, 5] + // P T + + + // So the cycle repeats again, now let's go through 1 more cycle + // [1, 2, 3, 4, 5] + // P T + // next = target.next + // [1, 2, 3, 4, 5] + // P T N + // target.next = prev + // Remember we have the list (1 -> null)? + // now target.next = prev means the next item of 2 is 1 + // 2 -> 1 -> null + // prev = target + // Now 2 is prev + // [1, 2, 3, 4, 5] + // P N + // target = next + // And 3 is now the target + // [1, 2, 3, 4, 5] + // P T + // And the cycle repeats again until the target reach the end of the list... + } + return this; + } + + // 10th method: insert + insert(i, val) { + // Check the requirements + if(i < 0 || i >= this.length) return false; + if(i === this.length) return !!this.push(val); + if(i === 0) return !!this.unshift(val); + + // Initialize a new node + var newNode = new Node(val); + // Get the previous node of newNode + var prevNode = this.get(i - 1); + // Remember we haven't insert the newNode into the list! + // And also store the next item of prevNode in a temporary variable + // because we are going to set it to the next item of newNode later + var temp = prevNode.next; + // Now we can set the next item of prevNode to newNode + prevNode.next = newNode; + // Then the next item of newNode will be the temporary item we store + newNode.next = temp; + // Increment the length + this.length++; + return true; + } + +} \ No newline at end of file From f6329c6c44edcaedeff88f17ffcb700c43d0188e Mon Sep 17 00:00:00 2001 From: Valentina Date: Wed, 3 Oct 2018 07:03:59 +0200 Subject: [PATCH 054/101] added smallest common multiple to math folder --- math/smallest-common-multiple.js | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 math/smallest-common-multiple.js diff --git a/math/smallest-common-multiple.js b/math/smallest-common-multiple.js new file mode 100644 index 0000000..32411a0 --- /dev/null +++ b/math/smallest-common-multiple.js @@ -0,0 +1,32 @@ +// Find the smallest common multiple of the given parameters that can be evenly divided by both, as well as +// by all numbers in the range between these parameters. +// The range is an array of two numbers, not necessarily be in numerical order. + +function smallestCommons(arr) { + arr.sort(function(a, b) { //sorting given numbers + return b - a; + }); + + var num = []; + for (var i = arr[0]; i >= arr[1]; i--) { //create array of all nums + num.push(i); + } + + var quot = 0; //variables for the quotient that can access them outside the loop + var loop = 1; + var n; + // Run code while n is not the same as the array length. + do { + quot = num[0] * loop * num[1]; + for (n = 2; n < num.length; n++) { + if (quot % num[n] !== 0) { + break; + } + } + loop++; + } while (n !== num.length); + + return quot; +} + +smallestCommons([1,5]); \ No newline at end of file From 7132c4abe33c991554c94e8ab74a6669247635fa Mon Sep 17 00:00:00 2001 From: Valentina Date: Wed, 3 Oct 2018 07:04:55 +0200 Subject: [PATCH 055/101] commentary additions --- math/smallest-common-multiple.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/math/smallest-common-multiple.js b/math/smallest-common-multiple.js index 32411a0..7bcbaa6 100644 --- a/math/smallest-common-multiple.js +++ b/math/smallest-common-multiple.js @@ -29,4 +29,4 @@ function smallestCommons(arr) { return quot; } -smallestCommons([1,5]); \ No newline at end of file +smallestCommons([1,5]); //Example of given numbers From 9e120cd091c6dca0e66cc7c27a1c50e67bc3d725 Mon Sep 17 00:00:00 2001 From: Abraham Hernandez Date: Wed, 3 Oct 2018 01:17:22 -0400 Subject: [PATCH 056/101] Update and rename other/checkPrime.js to others/checkPrime.js --- {other => others}/checkPrime.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) rename {other => others}/checkPrime.js (74%) diff --git a/other/checkPrime.js b/others/checkPrime.js similarity index 74% rename from other/checkPrime.js rename to others/checkPrime.js index 3d5c2a2..d3a7bad 100644 --- a/other/checkPrime.js +++ b/others/checkPrime.js @@ -11,5 +11,7 @@ function isPrime(n){ return true; } -// isPrime(137); true -// isPrime(237); false +isPrime(137); +// -> 'true' +isPrime(237); +// -> 'false' From 183c08e5ba104346e68554a890ffaaf6976d8b9a Mon Sep 17 00:00:00 2001 From: Abraham Hernandez Date: Wed, 3 Oct 2018 01:18:42 -0400 Subject: [PATCH 057/101] move to correct folder --- {other => others}/primeFactors.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) rename {other => others}/primeFactors.js (87%) diff --git a/other/primeFactors.js b/others/primeFactors.js similarity index 87% rename from other/primeFactors.js rename to others/primeFactors.js index ccf6f08..386b5f2 100644 --- a/other/primeFactors.js +++ b/others/primeFactors.js @@ -14,4 +14,5 @@ function primeFactors(n){ return factors; } -// primeFactors(69); [3, 23] +primeFactors(69); +// -> [3, 23] From bd3d03ee097016c6e284f38cdd2327e96f3339fd Mon Sep 17 00:00:00 2001 From: Abraham Hernandez Date: Wed, 3 Oct 2018 01:25:59 -0400 Subject: [PATCH 058/101] Temperature conversion isn't an algorithm --- math/tempConversion.js | 27 --------------------------- 1 file changed, 27 deletions(-) delete mode 100644 math/tempConversion.js diff --git a/math/tempConversion.js b/math/tempConversion.js deleted file mode 100644 index f5e9da8..0000000 --- a/math/tempConversion.js +++ /dev/null @@ -1,27 +0,0 @@ -// JavaScript Temperature Conversion - -// Author: Jay McDoniel - -function FtoC (fTemp) { - return (fTemp - 32) * (5 / 9); -} - -function FtoK (fTemp) { - return (fTemp - 32) * (5 / 9) + 273; -} - -function CtoF (cTemp) { - return cTemp * 9 / 5 + 32; -} - -function CtoK (cTemp) { - return cTemp + 273; -} - -function KtoF (kTemp) { - return (kTemp - 273) * 9 / 5 + 32; -} - -function KtoC (kTemp) { - return kTemp - 273; -} \ No newline at end of file From e74a304d6651079f637e4d5f59e7a59d83e50725 Mon Sep 17 00:00:00 2001 From: Abraham Hernandez Date: Wed, 3 Oct 2018 01:34:47 -0400 Subject: [PATCH 059/101] move to dynamic programming folder --- .../singlyLinkedList.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename linked-list/singly-link-list/singlyLinkList.js => dynamic-programming/singlyLinkedList.js (99%) diff --git a/linked-list/singly-link-list/singlyLinkList.js b/dynamic-programming/singlyLinkedList.js similarity index 99% rename from linked-list/singly-link-list/singlyLinkList.js rename to dynamic-programming/singlyLinkedList.js index 1b3d5f0..06eb92b 100644 --- a/linked-list/singly-link-list/singlyLinkList.js +++ b/dynamic-programming/singlyLinkedList.js @@ -236,4 +236,4 @@ class SinglyList { return true; } -} \ No newline at end of file +} From 0ef26bd0c0a76b3f28c5c05aa38ce27ad3cf18a8 Mon Sep 17 00:00:00 2001 From: Abraham Hernandez Date: Wed, 3 Oct 2018 18:54:16 -0400 Subject: [PATCH 060/101] fix links on readme --- README.md => readme.md | 37 ++++++++++++++++++++++++------------- 1 file changed, 24 insertions(+), 13 deletions(-) rename README.md => readme.md (68%) diff --git a/README.md b/readme.md similarity index 68% rename from README.md rename to readme.md index 731a705..3452f10 100644 --- a/README.md +++ b/readme.md @@ -2,6 +2,8 @@

+
+


@@ -16,19 +18,21 @@ ## Contents -- [Arithmetic Analysis]() -- [File Transfer Protocol]() -- [Graphs]() -- [Math]() -- [Neutral Network]() -- [Ciphers]() -- [Data Structures]() -- [Dynamic Programming]() -- [Hashes]() -- [Searches]() -- [Sorting]() -- [Strings]() -- [Traversals]() +- [Arithmetic Analysis](arithmetic-analysis) +- [File Transfer Protocol](file-transfer-protocol) +- [Greedy Algorithms](greedy-algorithms) +- [Graphs](graphs) +- [Math](math) +- [Neutral Network](neutral-network) +- [Ciphers](ciphers) +- [Data Structures](data-structures) +- [Dynamic Programming](dynamic-programming) +- [Hashes](hashes) +- [Searches](searches) +- [Sorting](sorting) +- [Strings](strings) +- [Traversals](traversals) +- [Others](others) ## License @@ -40,3 +44,10 @@ To the extent possible under law, [Carlos Abraham](https://go.abranhe.com/github [mit-license]: https://cdn.abraham.gq/projects/algorithms/mit-license.png + +
+ + + +
+
From 064a2e73c2f0f095efe52b40f695e7f589ac85c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Karabu=C5=82a-Stysiak?= Date: Wed, 3 Oct 2018 17:34:11 +0200 Subject: [PATCH 061/101] Add Collatz conjecture --- math/Collatz.js | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 math/Collatz.js diff --git a/math/Collatz.js b/math/Collatz.js new file mode 100644 index 0000000..3af2161 --- /dev/null +++ b/math/Collatz.js @@ -0,0 +1,31 @@ +/* Collatz conjecture */ + +function collatz(n) { + var numbers = [] + + while (n > 1) { + numbers.push(n) + if (n % 2 === 0) { + n = n / 2; + } else { + n = (3 * n) + 1; + } + } + numbers.push(n) + return numbers +} + +console.log( + 'Collatz conjecture for n = 11', + collatz(11) +) + +console.log( + 'Collatz conjecture for n = 27', + collatz(27) +) + +console.log( + 'Collatz conjecture for n = 51', + collatz(51) +) \ No newline at end of file From 6c995c107a5fcad23c78b19671d90749e0bb459b Mon Sep 17 00:00:00 2001 From: Abraham Hernandez Date: Wed, 3 Oct 2018 23:58:18 -0400 Subject: [PATCH 062/101] fixed capitalization --- math/{Collatz.js => collatz.js} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename math/{Collatz.js => collatz.js} (99%) diff --git a/math/Collatz.js b/math/collatz.js similarity index 99% rename from math/Collatz.js rename to math/collatz.js index 3af2161..aebbe70 100644 --- a/math/Collatz.js +++ b/math/collatz.js @@ -28,4 +28,4 @@ console.log( console.log( 'Collatz conjecture for n = 51', collatz(51) -) \ No newline at end of file +) From bd2163090cfc49e71d052326595056cd88d3d40b Mon Sep 17 00:00:00 2001 From: Worm4047 Date: Thu, 4 Oct 2018 08:52:40 +0530 Subject: [PATCH 063/101] Added algorithm for findind missing number in an array of integers --- strings/missingNumber.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 strings/missingNumber.js diff --git a/strings/missingNumber.js b/strings/missingNumber.js new file mode 100644 index 0000000..d47cedc --- /dev/null +++ b/strings/missingNumber.js @@ -0,0 +1,13 @@ +function missingNumber(arr){ + var n = arr.length+1, + sum = 0, + expectedSum = n* (n+1)/2; + + for(var i = 0, len = arr.length; i < len; i++){ + sum += arr[i]; + } + + return expectedSum - sum; +} + +missingNumber([5, 2, 6, 1, 3]); From ed0d9e576bfe154b31fd9a824c3082c05245b1df Mon Sep 17 00:00:00 2001 From: Worm4047 Date: Thu, 4 Oct 2018 08:55:20 +0530 Subject: [PATCH 064/101] Added algorithm for finding sum of two largest elements of an array --- strings/largestSumOfTwo.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 strings/largestSumOfTwo.js diff --git a/strings/largestSumOfTwo.js b/strings/largestSumOfTwo.js new file mode 100644 index 0000000..a55f2ab --- /dev/null +++ b/strings/largestSumOfTwo.js @@ -0,0 +1,29 @@ +function topSum(arr){ + + var biggest = arr[0], + second = arr[1], + len = arr.length, + i = 2; + + if (len<2) return null; + + if (biggest biggest){ + second = biggest; + biggest = arr[i]; + } + else if (arr[i]>second){ + second = arr[i]; + } + + } + return biggest + second; +} + +topSum([5, 2, 6, 1, 3]); \ No newline at end of file From e3dc3965d921775b3db1820ad651771832b3ccf5 Mon Sep 17 00:00:00 2001 From: Muhammad Owais Petiwala Date: Fri, 5 Oct 2018 11:36:42 +0800 Subject: [PATCH 065/101] add clock --- angle-clock/clock.js | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 angle-clock/clock.js diff --git a/angle-clock/clock.js b/angle-clock/clock.js new file mode 100644 index 0000000..7ca33be --- /dev/null +++ b/angle-clock/clock.js @@ -0,0 +1,44 @@ +function calculateTime(hour, angle){ + var time; + + if( hour > 12){ + hour = hour -12; + } + + if(angle == 0){ + if(hour < 13){ + var mint = hour*5; + }else{ + var mint = (hour-12)*5; + } + }else{ + var mint = angle/6; + } + + if((hour*5)+Math.round(mint) < 60){ + var f_mint = (hour*5)+Math.round(mint); + }else{ + var f_mint = ((hour*5)+Math.round(mint))-60; + } + + if(f_mint >= 55){ + f_mint += 5; + }else if(f_mint >= 44){ + f_mint += 4 + }else if(f_mint >= 31){ + f_mint += 3 + }else if(f_mint >= 20){ + f_mint += 2 + }else if(f_mint >= 8){ + f_mint++ + } + + if(angle >= 180){ + time = hour + ' : ' + f_mint; + }else{ + time = hour + ' : ' + f_mint; + } + + console.log(time); +} +calculateTime(3, 179); \ No newline at end of file From 8c56f252df9bf15a0dbf1e1ef7c46c9f6b1a0c1e Mon Sep 17 00:00:00 2001 From: Abraham Hernandez Date: Fri, 5 Oct 2018 12:45:17 -0400 Subject: [PATCH 066/101] fix image --- readme.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/readme.md b/readme.md index 3452f10..489d13f 100644 --- a/readme.md +++ b/readme.md @@ -4,7 +4,7 @@


- +

All ▲lgorithms implemented in Javascript

@@ -18,8 +18,6 @@ ## Contents -- [Arithmetic Analysis](arithmetic-analysis) -- [File Transfer Protocol](file-transfer-protocol) - [Greedy Algorithms](greedy-algorithms) - [Graphs](graphs) - [Math](math) From dab8bb705704155cd318f58662d61a39972dc212 Mon Sep 17 00:00:00 2001 From: Anoop Chauhan Date: Sat, 6 Oct 2018 21:18:32 +0530 Subject: [PATCH 067/101] Big O Notaion --- bigonotaion/bigonotaion.js | 56 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 bigonotaion/bigonotaion.js diff --git a/bigonotaion/bigonotaion.js b/bigonotaion/bigonotaion.js new file mode 100644 index 0000000..54f495c --- /dev/null +++ b/bigonotaion/bigonotaion.js @@ -0,0 +1,56 @@ +// Constant runtime - Big O Notation: "O (1)" +function log(array) { + console.log(array[0]); + console.log(array[1]); +} + +log([1, 2, 3, 4]); +log([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); + + +// Linear runtime - Big O Notation: "O (n)" +function logAll(array) { + for (var i = 0; i < array.length; i++) { + console.log(array[i]); + } +} + +logAll([1, 2, 3, 4, 5]); +logAll([1, 2, 3, 4, 5, 6]); +logAll([1, 2, 3, 4, 5, 6, 7]); + + +// Exponential runtime - Big O Notation: "O (n^2)" +function addAndLog(array) { + for (var i = 0; i < array.length; i++) { + for (var j = 0; j < array.length; j++) { + console.log(array[i] + array[j]); + } + } +} + +addAndLog(['A', 'B', 'C']); // 9 pairs logged out +addAndLog(['A', 'B', 'C', 'D']); // 16 pairs logged out +addAndLog(['A', 'B', 'C', 'D', 'E']); // 25 pairs logged out + + +// Logarithmic runtime - Big O Notation: O (log n) +function binarySearch(array, key) { + var low = 0; + var high = array.length - 1; + var mid; + var element; + + while (low <= high) { + mid = Math.floor((low + high) / 2, 10); + element = array[mid]; + if (element < key) { + low = mid + 1; + } else if (element > key) { + high = mid - 1; + } else { + return mid; + } + } + return -1; +} From 57bb46673399389917a281a060fb28aae1de0e56 Mon Sep 17 00:00:00 2001 From: Anoop Chauhan Date: Sat, 6 Oct 2018 21:20:55 +0530 Subject: [PATCH 068/101] Added Linked List concept * Add to head * Add to tail * Remove from head * Remove from tail * Search in linked list * Find index of element in linked list --- dynamic-programming/linkedList.js | 111 ++++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 dynamic-programming/linkedList.js diff --git a/dynamic-programming/linkedList.js b/dynamic-programming/linkedList.js new file mode 100644 index 0000000..4df144c --- /dev/null +++ b/dynamic-programming/linkedList.js @@ -0,0 +1,111 @@ +// LinkedList and Node function Constructor +function LinkedList() { + this.head = null; + this.tail = null; +}; + +function Node(value, next, prev) { + this.value = value; + this.next = next; + this.prev = prev; +}; + +// Add to head + +LinkedList.prototype.addHead = function(value) { + var newNode = new Node(value, this.head, null); + if(this.head) { + this.head.prev = newNode; + } else { + this.tail = newNode; + } + this.head = newNode; +}; + +var LL = new LinkedList(); +LL.addHead(100); +LL.addHead(200); +LL.addHead(300); +LL.addHead(200); +console.log(LL); + +// Add to tail +LinkedList.prototype.addTail = function(value) { + var newNode = new Node(value, null, this.tail); + if(this.tail) { + this.tail.next = newNode; + }else { + this.head = newNode; + } + this.tail = newNode; +}; + +LL.addTail(100); +LL.addTail(200); +LL.addTail(300); +console.log(LL); +console.log(ll.head.value); + +// Remove from head +LinkedList.prototype.removeHead = function(){ + if(this.head == null) { + return null; + } + else { + var val = this.head.value; + this.head = this.head.next; + } + if(!this.head) this.tail = null; + return val; +}; + +var ll = new LinkedList(); +console.log(LL.removeHead()); +console.log(LL); + +// Remove from tail +LinkedList.prototype.removeTail = function() { + if(!this.tail) return null; + var val = this.tail.value; + this.tail = this.tail.prev; + if(this.tail) this.tail.next = null; + else this.head = null; + return val; +} + +console.log(LL.removeTail()); +console.log(LL.removeTail()); +console.log(LL.removeTail()); +console.log(LL); + +// search in LinkedList +LinkedList.prototype.search = function(searchValue) { + if(!this.head) return null; + var currentNode = this.head; + while(currentNode){ + if(currentNode.value === searchValue) return currentNode.value; + currentNode = currentNode.next; + } + return null; +} + +console.log(LL.search(100)); + +// find indexOf element in LinkedList +LinkedList.prototype.indexOf = function(value) { + if(!this.head) return null; + var currentNode = this.head; + var counter = 0; + var indexArr = new Array; + while(currentNode){ + if(currentNode.value === value){ + indexArr.push(counter); + } + counter++; + currentNode = currentNode.next; + } + return indexArr; +} + +console.log(LL.indexOf(200)); + From e2834ba859615904b5c8fad75c802608f6fa425e Mon Sep 17 00:00:00 2001 From: milind1983 <44187874+milind1983@users.noreply.github.com> Date: Tue, 16 Oct 2018 11:12:56 +0530 Subject: [PATCH 069/101] Useful function for cookies in JS Cookies store, read, and delete operation using JQuery. --- dynamic-programming/cookies_function.js | 47 +++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 dynamic-programming/cookies_function.js diff --git a/dynamic-programming/cookies_function.js b/dynamic-programming/cookies_function.js new file mode 100644 index 0000000..efe3133 --- /dev/null +++ b/dynamic-programming/cookies_function.js @@ -0,0 +1,47 @@ +# Useful Functions to create , read and delete the cookies. + +(function( $ ) { + "use strict"; + +function createCookie(name, value, days) { + + var expires; + + if (days) { + var date = new Date(); + date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); + expires = "; expires=" + date.toGMTString(); + } else { + expires = ""; + } + document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/"; +} + +// How to Create Cookies? +createCookie('el_data', 'Prajakta'); + + +function readCookie(name) { + var nameEQ = encodeURIComponent(name) + "="; + var ca = document.cookie.split(';'); + for (var i = 0; i < ca.length; i++) { + var c = ca[i]; + while (c.charAt(0) === ' ') + c = c.substring(1, c.length); + if (c.indexOf(nameEQ) === 0) + return decodeURIComponent(c.substring(nameEQ.length, c.length)); + } + return null; +} + +// How to read cookies? +var name = readCookie('el_data'); + +function eraseCookie(name) { + createCookie(name, "", -1); +} + +// How to delete cookies? +eraseCookie('el_data'); + +})( jQuery ); From 8d0eb4ca4da05981341687a2897a9af7087a42a1 Mon Sep 17 00:00:00 2001 From: RashikAnsar Date: Mon, 22 Oct 2018 21:21:04 +0530 Subject: [PATCH 070/101] Added Radix Sort --- sorting/radixSort.js | 52 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 sorting/radixSort.js diff --git a/sorting/radixSort.js b/sorting/radixSort.js new file mode 100644 index 0000000..cd01fe7 --- /dev/null +++ b/sorting/radixSort.js @@ -0,0 +1,52 @@ +/** + * Gives the number at specified digits place + * @param {number} num + * @param {number} place + */ +function getDigit(num, place) { + return Math.floor(Math.abs(num) / Math.pow(10, place)) % 10; +} + +/** + * Calculate the number of digits in a given number + * @param {number} num + */ +function digits(num) { + if (num !== 0) { + return Math.floor(Math.log10(Math.abs(num))) + 1; + } + return 1; +} + +/** + * Find the maxDigits element in the given array + * @param {number[]} arr + */ +function maxDigits(arr) { + let max = 0; + for (let i = 0; i < arr.length; i++) { + max = Math.max(max, digits(arr[i])); + } + return max; +} + +/** + * Its default base10 digit sorting + * @param {number[]} arr + */ +function radixSort(arr) { + let max = maxDigits(arr); + for (let i = 0; i < max; i++) { + let buckets = Array.from({ length: 10 }, () => []); + for (let j = 0; j < arr.length; j++) { + let digitsValue = getDigit(arr[j], i); + buckets[digitsValue].push(arr[j]); + } + arr = [].concat(...buckets); + } + return arr; +} + +let a = [234, 364, 12, 64, 21315, 75, 23425]; +let b = radixSort(a); +console.log(b); From a067ed58e3e33f3f34826293a7b1d903ac923df7 Mon Sep 17 00:00:00 2001 From: RashikAnsar Date: Mon, 22 Oct 2018 21:31:28 +0530 Subject: [PATCH 071/101] Added linear search --- searching/linearSearch.js | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 searching/linearSearch.js diff --git a/searching/linearSearch.js b/searching/linearSearch.js new file mode 100644 index 0000000..25d2b73 --- /dev/null +++ b/searching/linearSearch.js @@ -0,0 +1,26 @@ +/** + * + * @author Rashik Ansar + * + * @param {number[]} arr Array of numbers to search + * @param {number} val Value to search in the given array + * @return {number[] | -1 } return array of indices at which the given value present or -1 + */ +function linearSearch(arr, val) { + let indices = []; + for (let i in arr) { + if (arr[i] === val) { + indices.push(i); + } + } + if (indices.length) return indices; + + return -1; +} + +let a = [1, 2, 3, 1, 1, 525, 5884, 545, 6854, 3, 1, 4]; + +let x = linearSearch(a, 1); +console.log(x); +let y = linearSearch(a, 545); +console.log(y); From a296657aa01939fc9c87e684d5949e376d86c2c0 Mon Sep 17 00:00:00 2001 From: RashikAnsar Date: Mon, 22 Oct 2018 21:36:39 +0530 Subject: [PATCH 072/101] Added naive pattern search --- searching/naivePatternSearching.js | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 searching/naivePatternSearching.js diff --git a/searching/naivePatternSearching.js b/searching/naivePatternSearching.js new file mode 100644 index 0000000..f23eb80 --- /dev/null +++ b/searching/naivePatternSearching.js @@ -0,0 +1,26 @@ +/** + * @author Rashik Ansar + * + * @param {string} txt The text in which pattern has to be searched + * @param {string} pat Pattern to search in string + * @returns {number} The total count of given pattern occurence/s in the text + */ +function naiveSearch(txt, pat) { + let count = 0; + for (let i = 0; i < txt.length; i++) { + for (let j = 0; j < pat.length; j++) { + if (pat[j] !== txt[i + j]) { + break; + } + if (j === pat.length - 1) { + count++; + } + } + } + return count; +} + +let x = naiveSearch('aaabbcbaabcabcaaabcaccaabcaade', 'abc'); +console.log(x); //4 +let y = naiveSearch('meow', 'ow'); +console.log(y); //1 From 9a113ec9fb10d56adf6f4e8dcef5257dd56da68b Mon Sep 17 00:00:00 2001 From: RashikAnsar Date: Mon, 22 Oct 2018 21:46:54 +0530 Subject: [PATCH 073/101] Added Stack --- data-structures/stack.js | 72 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 data-structures/stack.js diff --git a/data-structures/stack.js b/data-structures/stack.js new file mode 100644 index 0000000..d74fe16 --- /dev/null +++ b/data-structures/stack.js @@ -0,0 +1,72 @@ +/** + * @author Rashik Ansar + * + * Implemtaion of Stack data structure + * Stack follows LIFO (Last In First Out) priniciple + * For Insertion and Deletion its complexity is O(1) + * For Accessing and Searching its complexity is O(n) + */ + +class Stack { + /** + * initialize stack instances with null + */ + constructor() { + this.first = null; + this.last = null; + this.size = 0; + } + + /** + * Adding data to Top of the stack + * @param {*} data + * @returns {Stack} + */ + push(data) { + let newNode = new Node(data); + if (!this.first) { + this.first = newNode; + this.last = newNode; + } else { + let temp = this.first; + this.first = newNode; + this.first.next = temp; + } + this.size++; + return this; + } + + /** + * Removing data frpm Top of the stack + * @returns {Node.data} The data that is removing from the stack + */ + pop() { + if (!this.first) { + throw Error('UNDERFLOW :::: Stack is empty, there is nothing to remove'); + } + let current = this.first; + if (this.first === this.last) { + this.last = null; + } + this.first = current.next; + this.size--; + return current.data; + } + + /** + * @returns {Node.data} Top most element of the stack + */ + peek() { + if (!this.first) { + throw Error('Stack is empty'); + } + return this.first.data; + } +} + +class Node { + constructor(data) { + this.data = data; + this.next = null; + } +} From d8ceb1154ba1143233bc29877e9c1c83d8ef66ea Mon Sep 17 00:00:00 2001 From: RashikAnsar Date: Wed, 24 Oct 2018 10:10:14 +0530 Subject: [PATCH 074/101] Added Singly linked list --- data-structures/singlyLinkedList.js | 233 ++++++++++++++++++++++++++++ 1 file changed, 233 insertions(+) create mode 100644 data-structures/singlyLinkedList.js diff --git a/data-structures/singlyLinkedList.js b/data-structures/singlyLinkedList.js new file mode 100644 index 0000000..72b091e --- /dev/null +++ b/data-structures/singlyLinkedList.js @@ -0,0 +1,233 @@ +/** + * @author Rashik Ansar + * + * Implementation of singly linked list + * Singly linked list is a linear data strucutre + */ + +class Node { + constructor(data) { + this.data = data; + this.next = null; + } +} + +class SinglyLinkedList { + constructor() { + this.head = null; + this.tail = null; + this.length = 0; + } + + /** + * Adding new node as a tail of the linked list + * @param {any} data This dataue is added at the end of list + * @returns {SinglyLinkedList} LinkedList after adding new node as tail + */ + push(data) { + let temp = new Node(data); + if (!this.head) { + this.head = temp; + this.tail = this.head; // temp + } else { + this.tail.next = temp; + this.tail = temp; + } + this.length++; + return this; + } + + /** + * Adding new node as a head of the linked list + * @param {any} data This dataue is added at the beginning of the list + * @returns {SinglyLinkedList} LinkedList after adding a new node as head + */ + unshift(data) { + let temp = new Node(data); + if (!this.head) { + this.head = temp; + this.tail = this.head; + } else { + temp.next = this.head; + this.head = temp; + } + this.length++; + return this; + } + + /** + * Adding a node to the linkedList at specified position + * @param {number} index Position at which new node to insert + * @param {any} data dataue in the new node + * @returns {SinglyLinkedList} LinkedList after inserting a new node + */ + insert(index, data) { + if (index < 0 || index > this.length) { + throw Error('Given index is out of range'); + } + if (index === this.length) { + return this.push(data); + } + if (index === 0) { + return this.unshift(data); + } + let insertNode = new Node(data); + let previous = this.get(index - 1); + let temp = previous.next; + previous.next = insertNode; + insertNode.next = temp; + this.length++; + return this; + } + + /** + * Removes the node at the end of linked list(tail of linked list) + * @returns {Node} the node which is going to pop + */ + pop() { + if (!this.head) { + throw Error( + 'UNDERFLOW :::: LinkedList is empty, there is nothing to remove' + ); + } + let current = this.head; + let temp = current; + while (current.next) { + temp = current; + current = current.next; + } + this.tail = temp; + this.tail.next = null; + this.length--; + this.emptyListCheck(); + return current; + } + + /** + * Removes the node from the beginnig of linked list(head of linked list) + * @returns {Node} the node which is going to shift + */ + shift() { + if (!this.head) { + throw Error( + 'UNDERFLOW :::: LinkedList is empty, there is nothing to remove' + ); + } + let current = this.head; + this.head = current.next; + this.length--; + this.emptyListCheck(); + return current; + } + + /** + * Removes a node from the linkedList at specified position + * @param {number} index + * @returns {Node} Node which is removed from LinkedList + */ + remove(index) { + if (index < 0 || index > this.length) { + throw Error('Given index is out of range'); + } + if (index === this.length - 1) { + return this.pop(); + } + if (index === 0) { + return this.shift(); + } + let previous = this.get(index - 1); + let temp = previous.next; + previous.next = temp.next; + this.length--; + return temp; + } + + /** + * Retrieve the node at specified index + * @param {number} index Index of the node + * @returns {Node} LinkedList Node at specified index + */ + get(index) { + if (index < 0 || index >= this.length) { + throw Error('Given index is out of range'); + } + let counter = 0; + let current = this.head; + while (counter !== index) { + current = current.next; + counter++; + } + return current; + } + + /** + * Change the data of node at specified index + * @param {number} index Index of the node + * @param {any} data data replaces the current data at given index + * @returns {SinglyLinkedList} LinkedList + */ + set(index, data) { + // Here error checking will be done by the get method itself + // No need to specify explicitly + let existedNode = this.get(index); + if (existedNode) { + existedNode.data = data; + return this; + } + } + + /** + * Reversing the Linked list + * @returns {SinglyLinkedList} LinkedList + */ + reverse() { + let temp = this.head; + this.head = this.tail; + this.tail = temp; + + let previous = null; + let after = null; + while (temp) { + after = temp.next; + temp.next = previous; + previous = temp; + temp = after; + } + return this; + } + + /** + * Traversing or Printing the Linked list + */ + traverse() { + let current = this.head; + while (current) { + console.log(current.data); + current = current.next; + } + } + + /** + * @returns {[]} Linkedlist data as elements in Array + */ + listAsArray() { + let arr = []; + let current = this.head; + while (current) { + arr.push(current.data); + current = current.next; + } + return arr; + } + + /** + * Utility Function (PRIVATE FUNCTION) + * if the length is zero then assign null to both head and tail + */ + emptyListCheck() { + if (this.length === 0) { + this.head = null; + this.tail = null; + } + } +} From 1f9b7ea1e1c83dd1324d74b2edab218eb7863dcc Mon Sep 17 00:00:00 2001 From: RashikAnsar Date: Wed, 24 Oct 2018 10:14:17 +0530 Subject: [PATCH 075/101] Added Doubly linked list --- data-structures/doublyLinkedList.js | 226 ++++++++++++++++++++++++++++ 1 file changed, 226 insertions(+) create mode 100644 data-structures/doublyLinkedList.js diff --git a/data-structures/doublyLinkedList.js b/data-structures/doublyLinkedList.js new file mode 100644 index 0000000..59cbd19 --- /dev/null +++ b/data-structures/doublyLinkedList.js @@ -0,0 +1,226 @@ +/** + * @author Rashik Ansar + * + * Implementation of doubly linked list + * Doubly linked list is a linear data structure + */ + +class Node { + constructor(data) { + this.data = data; + this.next = null; + this.prev = null; + } +} + +class DoublyLinkedList { + constructor() { + this.head = null; + this.tail = null; + this.length = 0; + } + + /** + * Adding new node as a tail of the linked list + * @param {any} data This dataue is added at the end of list + * @returns {DoublyLinkedList} LinkedList after adding new node as tail + */ + push(data) { + let temp = new Node(data); + if (!this.head) { + this.head = temp; + this.tail = temp; + } else { + this.tail.next = temp; + temp.prev = this.tail; + this.tail = temp; + } + this.length++; + return this; + } + + /** + * Adding new node as a head of the linked list + * @param {any} data This dataue is added at the beginning of the list + * @returns {DoublyLinkedList} LinkedList after adding a new node as head + */ + unshift(data) { + let current = new Node(data); + if (!this.head) { + this.head = current; + this.tail = current; + } else { + this.head.prev = current; + current.next = this.head; + this.head = current; + } + this.length++; + return this; + } + + /** + * Adding a node to the linkedList at specified position + * @param {number} index Position at which new node to insert + * @param {any} data dataue in the new node + * @returns {DoublyLinkedList} LinkedList after inserting a new node + */ + insert(index, data) { + if (index < 0 || index > this.length) { + throw Error('Given index is out of range'); + } + if (index === this.length) { + return this.push(data); + } + if (index === 0) { + return this.unshift(data); + } + let insertNode = new Node(data); + let previous = this.get(index - 1); + let temp = previous.next; + previous.next = insertNode; + insertNode.prev = previous; + insertNode.next = temp; + temp.prev = insertNode; + this.length++; + return this; + } + + /** + * Removes the node at the end of linked list(tail of linked list) + * @returns {Node} the node which is going to pop + */ + pop() { + if (!this.head) { + throw Error( + 'UNDERFLOW :::: LinkedList is empty, there is nothing to remove' + ); + } + let temp = this.tail; + if (this.length === 1) { + this.head = null; + this.tail = null; + } else { + this.tail = temp.prev; + this.tail.next = null; + temp.prev = null; + } + this.length--; + return temp; + } + + /** + * Removes the node from the beginnig of linked list(head of linked list) + * @returns {Node} the node which is going to shift + */ + shift() { + if (!this.head) { + throw Error( + 'UNDERFLOW :::: LinkedList is empty, there is nothing to remove' + ); + } + let current = this.head; + if (this.length === 1) { + this.head = null; + this.tail = null; + } else { + this.head = current.next; + this.head.prev = null; + current.next = null; + } + this.length--; + return current; + } + + /** + * Removes a node from the linkedList at specified position + * @param {number} index + * @returns {Node} Node which is removed from LinkedList + */ + remove(index) { + if (index < 0 || index > this.length) { + throw Error('Given index is out of range'); + } + if (index === this.length - 1) { + return this.pop(); + } + if (index === 0) { + return this.shift(); + } + let removeNode = this.get(index); + let before = removeNode.prev; + let after = removeNode.next; + before.next = after; + after.prev = before; + removeNode.next = null; + removeNode.prev = null; + this.length--; + return removeNode; + } + + /** + * Retrieve the node at specified index + * @param {number} index Index of the node + * @returns {Node} LinkedList Node at specified index + */ + get(index) { + if (index < 0 || index >= this.length) { + throw Error('Given index is out of range'); + } + let current; + if (index <= this.length / 2) { + let counter = 0; + current = this.head; + while (counter !== index) { + current = current.next; + counter++; + } + } else { + let counter = this.length - 1; + current = this.tail; + while (counter !== index) { + current = current.prev; + counter--; + } + } + return current; + } + + /** + * Change the data of node at specified index + * @param {number} index Index of the node + * @param {any} data data replaces the current data at given index + * @returns {DoublyLinkedList} LinkedList + */ + set(index, data) { + let existedNode = this.get(index); + if (existedNode) { + existedNode.data = data; + return this; + } + } + + /** + * Traversing or Printing the Linked list + */ + traverse() { + let current = this.head; + console.log(this.length); + while (current) { + console.log(current.data); + current = current.next; + } + } + + /** + * @returns {[]} Linkedlist data as elements in Array + */ + listAsArray() { + let arr = []; + let current = this.head; + while (current) { + arr.push(current.data); + current = current.next; + } + return arr; + } +} From 0d604bc7096b92184e58ffb5a906b2fe5362dbdb Mon Sep 17 00:00:00 2001 From: RashikAnsar Date: Wed, 24 Oct 2018 10:27:19 +0530 Subject: [PATCH 076/101] Added Queue --- data-structures/queue.js | 68 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 data-structures/queue.js diff --git a/data-structures/queue.js b/data-structures/queue.js new file mode 100644 index 0000000..098ad47 --- /dev/null +++ b/data-structures/queue.js @@ -0,0 +1,68 @@ +/** + * @author Rashik Ansar + * + * Implementation of Queue Data structure + * Queue follows FIFO (First In First Out) Principle + */ + +class Node { + constructor(data) { + this.data = data; + this.next = null; + } +} + +class Queue { + constructor() { + this.first = null; + this.last = null; + this.size = 0; + } + + /** + * Adding data to the end of queue + * @param {*} data Data to add in the queue + * @returns {Queue} Returns the queue after adding new data + */ + enqueue(data) { + let newNode = new Node(data); + if (!this.first) { + this.first = newNode; + this.last = newNode; + } else { + this.last.next = newNode; + this.last = newNode; + } + this.size++; + return this; + } + + /** + * Removing data from the beginning of the queue + * @returns Data that is removing from queue + */ + dequeue() { + if (!this.first) { + throw Error( + 'UNDERFLOW::: The queue is empty, there is nothing to remove' + ); + } + let temp = this.first; + if (this.first === this.last) { + this.last = null; + } + this.first = this.first.next; + this.size--; + return temp.data; + } + + /** + * @returns First element in the queue + */ + peek() { + if (!this.first) { + throw Error('Stack is empty'); + } + return this.first.data; + } +} From d1e07a7c85098cd838f47f2f93637a377ca9ed4f Mon Sep 17 00:00:00 2001 From: Abraham Hernandez Date: Wed, 24 Oct 2018 17:16:02 -0400 Subject: [PATCH 077/101] move big o notation to others --- {bigonotaion => others}/bigonotaion.js | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {bigonotaion => others}/bigonotaion.js (100%) diff --git a/bigonotaion/bigonotaion.js b/others/bigonotaion.js similarity index 100% rename from bigonotaion/bigonotaion.js rename to others/bigonotaion.js From da56f1ad4ac9779cac8e00ee3a61b1badcf9d8d0 Mon Sep 17 00:00:00 2001 From: RashikAnsar Date: Thu, 25 Oct 2018 09:23:01 +0530 Subject: [PATCH 078/101] Added priority queue --- data-structures/priorityQueue.js | 117 +++++++++++++++++++++++++++++++ 1 file changed, 117 insertions(+) create mode 100644 data-structures/priorityQueue.js diff --git a/data-structures/priorityQueue.js b/data-structures/priorityQueue.js new file mode 100644 index 0000000..1eb68ca --- /dev/null +++ b/data-structures/priorityQueue.js @@ -0,0 +1,117 @@ +/** + * @author Rashik Ansar + * + * Implemntaion of priority queue + * Lower the priority value higher its priority + * under the hood its implementing minBinaryHeap + */ +class PriorityQueue { + constructor() { + this.values = []; + } + + /** + * Adding data to the queue + * @param {*} data Data to add into queue + * @param {*} priority Priority of the data + * @returns {PriorityQueue} + */ + enqueue(data, priority) { + let temp = new Node(data, priority); + this.values.push(temp); + this.bubbleUp(); + return this; + } + + /** + * removing a node from the queue + * @returns {Node} + */ + dequeue() { + const min = this.values[0]; + const end = this.values.pop(); + if (this.values.length > 0) { + this.values[0] = end; + this.sinkDown(); + } + return min; + } + + /** + * enqueue helper function + */ + bubbleUp() { + let index = this.values.length - 1; + const element = this.values[index]; + while (index > 0) { + let parentIndex = Math.floor((index - 1) / 2); + let parent = this.values[parentIndex]; + // if (element.priority <= parent.priority) break; //maxBinaryHeap condition + if (element.priority >= parent.priority) break; //minBinaryHeap condition + this.values[parentIndex] = element; + this.values[index] = parent; + index = parentIndex; + } + } + + /** + * dequeue helper function + */ + sinkDown() { + let index = 0; + const length = this.values.length; + const element = this.values[index]; + while (true) { + let leftChildIndex = 2 * index + 1; + let rightChildIndex = 2 * index + 2; + let leftChild; + let rightChild; + let swap = null; + + if (leftChildIndex < length) { + leftChild = this.values[leftChildIndex]; + // Change below comparision operators to make maxBinaryHeap + if (leftChild.priority < element.priority) { + swap = leftChildIndex; + } + } + + if (rightChildIndex < length) { + rightChild = this.values[rightChildIndex]; + // Change below comparision operators to make maxBinaryHeap + if ( + (!swap && rightChild.priority < element.priority) || + (swap && rightChild.priority < leftChild.priority) + ) { + swap = rightChildIndex; + } + } + + if (!swap) break; + + this.values[index] = this.values[swap]; + this.values[swap] = element; + index = swap; + } + } +} + +class Node { + constructor(data, priority) { + this.data = data; + this.priority = priority; + } +} + +let a = new PriorityQueue(); +a.enqueue('Common Cold', 10); +a.enqueue('Gunshot wound', 2); +a.enqueue('Fever', 8); + +console.log(a); +a.dequeue(); +console.log(a); +a.dequeue(); +console.log(a); +a.dequeue(); +console.log(a); From 4b252c078c1277daf5aa1178a275eccce64fabe7 Mon Sep 17 00:00:00 2001 From: RashikAnsar Date: Thu, 25 Oct 2018 09:32:57 +0530 Subject: [PATCH 079/101] Added Hash Table --- data-structures/hashTable.js | 76 ++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 data-structures/hashTable.js diff --git a/data-structures/hashTable.js b/data-structures/hashTable.js new file mode 100644 index 0000000..603c9d2 --- /dev/null +++ b/data-structures/hashTable.js @@ -0,0 +1,76 @@ +/** + * @author Rashik Ansar + * + * Implementation of Hash Table + */ + +class HashTable { + constructor(size = 47) { + this.keyMap = new Array(size); + } + + /** + * Hash Function + * Private method to generate hash of the given data + * @param {*} key data to hash + */ + _hash(key) { + let total = 0; + const RANDOM_PRIME = 31; + for (let i = 0; i < Math.min(key.length, 100); i++) { + let char = key[i]; + let value = char.charCodeAt(0) - 96; + total = (total * RANDOM_PRIME + value) % this.keyMap.length; + } + return total; + } + + set(key, value) { + let index = this._hash(key); + if (!this.keyMap[index]) { + this.keyMap[index] = []; + } + this.keyMap[index].push([key, value]); + return this; + } + + get(key) { + let index = this._hash(key); + if (this.keyMap[index]) { + for (let i = 0; i < this.keyMap[index].length; i++) { + if (this.keyMap[index][i][0] === key) { + return this.keyMap[index][i]; + } + } + } + return undefined; + } + + values() { + let valArray = []; + for (let i = 0; i < this.keyMap.length; i++) { + if (this.keyMap[i]) { + for (let j = 0; j < this.keyMap[i].length; j++) { + if (!valArray.includes(this.keyMap[i][j][1])) { + valArray.push(this.keyMap[i][j][1]); + } + } + } + } + return valArray; + } + + keys() { + let keysArray = []; + for (let i = 0; i < this.keyMap.length; i++) { + if (this.keyMap[i]) { + for (let j = 0; j < this.keyMap[i].length; j++) { + if (!keysArray.includes(this.keyMap[i][j][0])) { + keysArray.push(this.keyMap[i][j][0]); + } + } + } + } + return keysArray; + } +} From e26303831cf91844fe463e60913a8205ed561166 Mon Sep 17 00:00:00 2001 From: RashikAnsar Date: Thu, 25 Oct 2018 09:38:07 +0530 Subject: [PATCH 080/101] Added unweighted graph --- graphs/unweightedGraph.js | 154 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 154 insertions(+) create mode 100644 graphs/unweightedGraph.js diff --git a/graphs/unweightedGraph.js b/graphs/unweightedGraph.js new file mode 100644 index 0000000..7d48e5a --- /dev/null +++ b/graphs/unweightedGraph.js @@ -0,0 +1,154 @@ +/** + * @author Rashik Ansar + * Implemtaion of graph with the help of Adjacency List + * Its Unweighted graph implemetation + */ + +class Graph { + constructor() { + this.adjacencyList = {}; + } + + /** + * Adding a vertex to the graph + * @param {*} vertex The data of the vertex to add into graph + * @returns {Graph} + */ + addVertex(vertex) { + if (this.adjacencyList[vertex]) { + throw Error(`${vertex} already exist in graph... `); + } else { + this.adjacencyList[vertex] = []; + } + // return this; + } + + /** + * Removing a vertex from the graph + * @param {*} vertex The data of the vertex to remove from graph + */ + removeVertex(vertex) { + if (this.adjacencyList[vertex]) { + while (this.adjacencyList[vertex].length) { + const itemInArray = this.adjacencyList[vertex].pop(); + this.removeEdge(vertex, itemInArray); + } + delete this.adjacencyList[vertex]; + // return this; // Added for testing before traversal methods + } else { + throw Error(`${vertex} doesn't exist...`); + } + } + + /** + * Adding an edge between two vertices in the graph + * @param {*} vertex1 + * @param {*} vertex2 + */ + addEdge(vertex1, vertex2) { + if (this.adjacencyList[vertex1] && this.adjacencyList[vertex2]) { + this.adjacencyList[vertex1].push(vertex2); + this.adjacencyList[vertex2].push(vertex1); + // return this; + } else { + throw Error('Given vertex/vertices might not exist in graph...'); + } + } + + /** + * Removing an existing edge between two vertices in the graph + * @param {*} vertex1 + * @param {*} vertex2 + */ + removeEdge(vertex1, vertex2) { + if (this.adjacencyList[vertex1] && this.adjacencyList[vertex2]) { + this.adjacencyList[vertex1] = this.adjacencyList[vertex1].filter( + i => i !== vertex2 + ); + this.adjacencyList[vertex2] = this.adjacencyList[vertex2].filter( + i => i !== vertex1 + ); + // return this; + } else { + throw Error('Given vertex/vertices might not exist in graph...'); + } + } + + /** + * Travesal of the graph by breadth-first approach + * @param {*} start Starting vertex for traversal + * @returns {[]} + */ + breadthFirstTraversal(start) { + const queue = []; + const result = []; + const visited = {}; + let current; + queue.push(start); + visited[start] = true; + + while (queue.length) { + current = queue.shift(); + result.push(current); + this.adjacencyList[current].forEach(x => { + if (!visited[x]) { + visited[x] = true; + queue.push(x); + } + }); + } + return result; + } + + /** + * Depth First Traversal (recursive approach) + * + * @param {*} start Starting vertex for traversal + * @returns {[]} + */ + DFTrecursuive(start) { + const visited = {}; + const result = []; + const adjacencyList = this.adjacencyList; + function dfs(vertex) { + if (!vertex) { + throw Error('Incorrect starting vertex!'); + } + visited[vertex] = true; + result.push(vertex); + adjacencyList[vertex].forEach(x => { + if (!visited[x]) { + return dfs(x); + } + }); + } + dfs(start); + return result; + } + /** + * Depth First Traversal (Iterative approach) + * + * @param {*} start Starting vertex for traversal + * @returns {[]} + */ + DFTiterative(start) { + const stack = []; + const visited = {}; + const result = []; + let current; + + stack.push(start); + visited[start] = true; + while (stack.length) { + current = stack.pop(); + result.push(current); + this.adjacencyList[current].forEach(x => { + if (!visited[x]) { + visited[x] = true; + stack.push(x); + } + }); + } + return result; + } +} From 30e2c33ebd4eed7d69e69a6d1fa9d3e862adfeb9 Mon Sep 17 00:00:00 2001 From: AddeNordh Date: Mon, 29 Oct 2018 15:51:38 +0100 Subject: [PATCH 081/101] added random number generator for js --- math/randomNumber.js | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 math/randomNumber.js diff --git a/math/randomNumber.js b/math/randomNumber.js new file mode 100644 index 0000000..4490bfb --- /dev/null +++ b/math/randomNumber.js @@ -0,0 +1,11 @@ +const randomNumber = ({ min, max, integer }) => { + + const number = Math.random() * (max - min) + min; + + if (integer) { + return Math.round(number); + } + + return number; + +} From 239b9c2ca896c8b7629b2ad714987276f81bc301 Mon Sep 17 00:00:00 2001 From: renanpvaz Date: Tue, 30 Oct 2018 22:57:11 -0300 Subject: [PATCH 082/101] Add gulag sort --- sorting/gulagSort.js | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 sorting/gulagSort.js diff --git a/sorting/gulagSort.js b/sorting/gulagSort.js new file mode 100644 index 0000000..71b9895 --- /dev/null +++ b/sorting/gulagSort.js @@ -0,0 +1,9 @@ +const gulagSort = ls => { + if (!ls.length) return [] + + const [x, y, ...xs] = ls + + return y == null ? + [x] : x < y ? + [x, ...gulagSort([y, ...xs])] : gulagSort([y, ...xs]) +} From 7edc54dea6bb2dece9a6ddb3e04371da304d9424 Mon Sep 17 00:00:00 2001 From: LuizGuerra Date: Wed, 31 Oct 2018 18:21:42 -0300 Subject: [PATCH 083/101] Added methods to stack --- data-structures/stack.js | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/data-structures/stack.js b/data-structures/stack.js index d74fe16..22377be 100644 --- a/data-structures/stack.js +++ b/data-structures/stack.js @@ -1,5 +1,6 @@ /** - * @author Rashik Ansar + * @author Rashik Ansar and Luiz Guerra + * * * Implemtaion of Stack data structure * Stack follows LIFO (Last In First Out) priniciple @@ -62,6 +63,42 @@ class Stack { } return this.first.data; } + + /** + * @returns size of the Stack + */ + size() { + return this.size; + } + + /** + * @returns if Stack is empty + */ + isEmpty() { + return this.size == 0; + } + + /** + * clears the Stack + */ + clear() { + this.first = null; + this.last = null; + this.size = 0; + } + + /** + * @returns the Stack + */ + toString() { + let str = ""; + let aux = this.first; + for (let i = 0; i < this.count; i++) + str += aux.element + " "; + aux = aux.next; + return str; + } + } class Node { From c4960022000b8c20d98d8c48a9421c805f8f71a2 Mon Sep 17 00:00:00 2001 From: Abraham Hernandez Date: Thu, 6 Dec 2018 10:01:55 -0500 Subject: [PATCH 084/101] Update readme.md --- readme.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/readme.md b/readme.md index 489d13f..4deee00 100644 --- a/readme.md +++ b/readme.md @@ -10,9 +10,9 @@

All ▲lgorithms implemented in Javascript

- - - + + + @@ -41,7 +41,7 @@ This work is licensed under a [MIT License](https://github.com/abranhe/algorithm To the extent possible under law, [Carlos Abraham](https://go.abranhe.com/github) has waived all copyright and related or neighboring rights to this work. -[mit-license]: https://cdn.abraham.gq/projects/algorithms/mit-license.png +[mit-license]: https://cdn.abranhe.com/projects/algorithms/mit-license.png
From fcb87362455989cf4006faae553c1a67e931e288 Mon Sep 17 00:00:00 2001 From: Aditya Kharote Date: Tue, 1 Oct 2019 22:52:09 +0530 Subject: [PATCH 085/101] Create anagram.js --- strings/anagram.js | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 strings/anagram.js diff --git a/strings/anagram.js b/strings/anagram.js new file mode 100644 index 0000000..cc13916 --- /dev/null +++ b/strings/anagram.js @@ -0,0 +1,9 @@ +//Check if 2 words are anagrams of each other. +var o1 = "arms"; +var o2 = "mars" +//Remove +var n1 = o1.replace(/\W+/g,'').toLowerCase().split("").sort().join(""); +var n2 = o2.replace(/\W+/g,'').toLowerCase().split("").sort().join(""); +var isAnagram = n1==n2; +if(isAnagram) console.log("The two words are anagrams"); +else console.log("The two words are not anagrams"); From da0f3d5a71434971a730a62adc1497fe70eb90b3 Mon Sep 17 00:00:00 2001 From: Aditya Kharote Date: Tue, 1 Oct 2019 22:54:21 +0530 Subject: [PATCH 086/101] Fixed incomplete sentence :P --- strings/anagram.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/strings/anagram.js b/strings/anagram.js index cc13916..c5c1085 100644 --- a/strings/anagram.js +++ b/strings/anagram.js @@ -1,7 +1,7 @@ //Check if 2 words are anagrams of each other. var o1 = "arms"; var o2 = "mars" -//Remove +//Remove non-letter characters, and sort the letters in alphabetical order. var n1 = o1.replace(/\W+/g,'').toLowerCase().split("").sort().join(""); var n2 = o2.replace(/\W+/g,'').toLowerCase().split("").sort().join(""); var isAnagram = n1==n2; From c7b90316efe746d3d0046d590958b74bee4e6506 Mon Sep 17 00:00:00 2001 From: Abraham Hernandez Date: Fri, 2 Oct 2020 02:09:53 -0400 Subject: [PATCH 087/101] refactofing! --- .github/code-of-conduct.md | 40 ++ .github/contributing.md | 3 + .github/issue-template.md | 1 + .github/pull-request-template.md | 6 + {ciphers => algorithms/ciphers}/rot13.js | 0 .../data-structures}/doublyLinkedList.js | 0 .../data-structures}/hashTable.js | 0 .../data-structures}/priorityQueue.js | 0 .../data-structures}/queue.js | 0 .../data-structures}/singlyLinkedList.js | 0 .../data-structures}/stack.js | 0 .../dynamic-programming}/linkedList.js | 0 .../dynamic-programming}/singlyLinkedList.js | 0 {graphs => algorithms/graphs}/bfs.js | 0 .../graphs}/breadth-first-search.js | 0 {graphs => algorithms/graphs}/dfs.js | 0 {graphs => algorithms/graphs}/dijkstra.js | 0 .../graphs}/unweightedGraph.js | 0 {math => algorithms/math}/checkPrime.js | 0 {math => algorithms/math}/collatz.js | 0 {math => algorithms/math}/computeNCR.js | 0 .../math}/degreeRadianConversion.js | 0 .../math}/factorial-recursive.js | 0 {math => algorithms/math}/factorial.js | 0 .../math}/fibonacci-recursive.js | 0 {math => algorithms/math}/fibonacci.js | 0 {math => algorithms/math}/fibonnaci.js | 0 {math => algorithms/math}/gcd.js | 0 .../math}/greatestCommonDivisor.js | 0 .../math}/naturalNumbersSum.js | 0 {math => algorithms/math}/quadrant.js | 0 .../math}/smallest-common-multiple.js | 0 {math => algorithms/math}/spiralMatrix.js | 0 {others => algorithms/others}/bigonotaion.js | 0 {others => algorithms/others}/checkPrime.js | 0 {others => algorithms/others}/primeFactors.js | 0 .../searches}/binarySearch.js | 0 .../searches}/sequentialSearch.js | 0 .../searching}/binarySearch.js | 0 .../searching}/linearSearch.js | 0 .../searching}/naivePatternSearching.js | 0 {sorting => algorithms/sorting}/BogoSort.js | 0 {sorting => algorithms/sorting}/bubbleSort.js | 0 .../sorting}/countingSort.js | 0 {sorting => algorithms/sorting}/flashSort.js | 0 {sorting => algorithms/sorting}/gnomeSort.js | 0 {sorting => algorithms/sorting}/gulagSort.js | 0 {sorting => algorithms/sorting}/heapSort.js | 0 .../sorting}/insertionSort.js | 0 {sorting => algorithms/sorting}/mergeSort.js | 0 .../sorting}/pancakeSort.js | 0 {sorting => algorithms/sorting}/quickSort.js | 0 {sorting => algorithms/sorting}/radixSort.js | 0 .../sorting}/selectionSort.js | 0 {sorting => algorithms/sorting}/shellSort.js | 0 .../strings}/checkPalindrome.js | 0 .../strings}/integerReversal.js | 0 .../strings}/largestSumOfTwo.js | 0 .../strings}/missingNumber.js | 0 {strings => algorithms/strings}/palindrome.js | 0 {strings => algorithms/strings}/pigLatin.js | 0 license | 22 + readme.md | 429 ++++++++++++++++-- sorting/ShellSort.js | 29 -- src/.gitkeep | 0 65 files changed, 469 insertions(+), 61 deletions(-) create mode 100644 .github/code-of-conduct.md create mode 100644 .github/contributing.md create mode 100644 .github/issue-template.md create mode 100644 .github/pull-request-template.md rename {ciphers => algorithms/ciphers}/rot13.js (100%) rename {data-structures => algorithms/data-structures}/doublyLinkedList.js (100%) rename {data-structures => algorithms/data-structures}/hashTable.js (100%) rename {data-structures => algorithms/data-structures}/priorityQueue.js (100%) rename {data-structures => algorithms/data-structures}/queue.js (100%) rename {data-structures => algorithms/data-structures}/singlyLinkedList.js (100%) rename {data-structures => algorithms/data-structures}/stack.js (100%) rename {dynamic-programming => algorithms/dynamic-programming}/linkedList.js (100%) rename {dynamic-programming => algorithms/dynamic-programming}/singlyLinkedList.js (100%) rename {graphs => algorithms/graphs}/bfs.js (100%) rename {graphs => algorithms/graphs}/breadth-first-search.js (100%) rename {graphs => algorithms/graphs}/dfs.js (100%) rename {graphs => algorithms/graphs}/dijkstra.js (100%) rename {graphs => algorithms/graphs}/unweightedGraph.js (100%) rename {math => algorithms/math}/checkPrime.js (100%) rename {math => algorithms/math}/collatz.js (100%) rename {math => algorithms/math}/computeNCR.js (100%) rename {math => algorithms/math}/degreeRadianConversion.js (100%) rename {math => algorithms/math}/factorial-recursive.js (100%) rename {math => algorithms/math}/factorial.js (100%) rename {math => algorithms/math}/fibonacci-recursive.js (100%) rename {math => algorithms/math}/fibonacci.js (100%) rename {math => algorithms/math}/fibonnaci.js (100%) rename {math => algorithms/math}/gcd.js (100%) rename {math => algorithms/math}/greatestCommonDivisor.js (100%) rename {math => algorithms/math}/naturalNumbersSum.js (100%) rename {math => algorithms/math}/quadrant.js (100%) rename {math => algorithms/math}/smallest-common-multiple.js (100%) rename {math => algorithms/math}/spiralMatrix.js (100%) rename {others => algorithms/others}/bigonotaion.js (100%) rename {others => algorithms/others}/checkPrime.js (100%) rename {others => algorithms/others}/primeFactors.js (100%) rename {searches => algorithms/searches}/binarySearch.js (100%) rename {searches => algorithms/searches}/sequentialSearch.js (100%) rename {searching => algorithms/searching}/binarySearch.js (100%) rename {searching => algorithms/searching}/linearSearch.js (100%) rename {searching => algorithms/searching}/naivePatternSearching.js (100%) rename {sorting => algorithms/sorting}/BogoSort.js (100%) rename {sorting => algorithms/sorting}/bubbleSort.js (100%) rename {sorting => algorithms/sorting}/countingSort.js (100%) rename {sorting => algorithms/sorting}/flashSort.js (100%) rename {sorting => algorithms/sorting}/gnomeSort.js (100%) rename {sorting => algorithms/sorting}/gulagSort.js (100%) rename {sorting => algorithms/sorting}/heapSort.js (100%) rename {sorting => algorithms/sorting}/insertionSort.js (100%) rename {sorting => algorithms/sorting}/mergeSort.js (100%) rename {sorting => algorithms/sorting}/pancakeSort.js (100%) rename {sorting => algorithms/sorting}/quickSort.js (100%) rename {sorting => algorithms/sorting}/radixSort.js (100%) rename {sorting => algorithms/sorting}/selectionSort.js (100%) rename {sorting => algorithms/sorting}/shellSort.js (100%) rename {strings => algorithms/strings}/checkPalindrome.js (100%) rename {strings => algorithms/strings}/integerReversal.js (100%) rename {strings => algorithms/strings}/largestSumOfTwo.js (100%) rename {strings => algorithms/strings}/missingNumber.js (100%) rename {strings => algorithms/strings}/palindrome.js (100%) rename {strings => algorithms/strings}/pigLatin.js (100%) create mode 100644 license delete mode 100644 sorting/ShellSort.js create mode 100644 src/.gitkeep diff --git a/.github/code-of-conduct.md b/.github/code-of-conduct.md new file mode 100644 index 0000000..f809c8b --- /dev/null +++ b/.github/code-of-conduct.md @@ -0,0 +1,40 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/.github/contributing.md b/.github/contributing.md new file mode 100644 index 0000000..01f6600 --- /dev/null +++ b/.github/contributing.md @@ -0,0 +1,3 @@ +## Contributing + +> Please note that this project is released with a [Contributor Code of Conduct](code-of-conduct.md). By participating in this project you agree to abide by its terms. \ No newline at end of file diff --git a/.github/issue-template.md b/.github/issue-template.md new file mode 100644 index 0000000..99764fe --- /dev/null +++ b/.github/issue-template.md @@ -0,0 +1 @@ +I am creating an issue because... diff --git a/.github/pull-request-template.md b/.github/pull-request-template.md new file mode 100644 index 0000000..3bc0935 --- /dev/null +++ b/.github/pull-request-template.md @@ -0,0 +1,6 @@ +I am creating a pull request for... + +- [ ] New algorithm +- [ ] Update to an algorithm +- [ ] Fix an error +- [ ] Other - *Describe below* \ No newline at end of file diff --git a/ciphers/rot13.js b/algorithms/ciphers/rot13.js similarity index 100% rename from ciphers/rot13.js rename to algorithms/ciphers/rot13.js diff --git a/data-structures/doublyLinkedList.js b/algorithms/data-structures/doublyLinkedList.js similarity index 100% rename from data-structures/doublyLinkedList.js rename to algorithms/data-structures/doublyLinkedList.js diff --git a/data-structures/hashTable.js b/algorithms/data-structures/hashTable.js similarity index 100% rename from data-structures/hashTable.js rename to algorithms/data-structures/hashTable.js diff --git a/data-structures/priorityQueue.js b/algorithms/data-structures/priorityQueue.js similarity index 100% rename from data-structures/priorityQueue.js rename to algorithms/data-structures/priorityQueue.js diff --git a/data-structures/queue.js b/algorithms/data-structures/queue.js similarity index 100% rename from data-structures/queue.js rename to algorithms/data-structures/queue.js diff --git a/data-structures/singlyLinkedList.js b/algorithms/data-structures/singlyLinkedList.js similarity index 100% rename from data-structures/singlyLinkedList.js rename to algorithms/data-structures/singlyLinkedList.js diff --git a/data-structures/stack.js b/algorithms/data-structures/stack.js similarity index 100% rename from data-structures/stack.js rename to algorithms/data-structures/stack.js diff --git a/dynamic-programming/linkedList.js b/algorithms/dynamic-programming/linkedList.js similarity index 100% rename from dynamic-programming/linkedList.js rename to algorithms/dynamic-programming/linkedList.js diff --git a/dynamic-programming/singlyLinkedList.js b/algorithms/dynamic-programming/singlyLinkedList.js similarity index 100% rename from dynamic-programming/singlyLinkedList.js rename to algorithms/dynamic-programming/singlyLinkedList.js diff --git a/graphs/bfs.js b/algorithms/graphs/bfs.js similarity index 100% rename from graphs/bfs.js rename to algorithms/graphs/bfs.js diff --git a/graphs/breadth-first-search.js b/algorithms/graphs/breadth-first-search.js similarity index 100% rename from graphs/breadth-first-search.js rename to algorithms/graphs/breadth-first-search.js diff --git a/graphs/dfs.js b/algorithms/graphs/dfs.js similarity index 100% rename from graphs/dfs.js rename to algorithms/graphs/dfs.js diff --git a/graphs/dijkstra.js b/algorithms/graphs/dijkstra.js similarity index 100% rename from graphs/dijkstra.js rename to algorithms/graphs/dijkstra.js diff --git a/graphs/unweightedGraph.js b/algorithms/graphs/unweightedGraph.js similarity index 100% rename from graphs/unweightedGraph.js rename to algorithms/graphs/unweightedGraph.js diff --git a/math/checkPrime.js b/algorithms/math/checkPrime.js similarity index 100% rename from math/checkPrime.js rename to algorithms/math/checkPrime.js diff --git a/math/collatz.js b/algorithms/math/collatz.js similarity index 100% rename from math/collatz.js rename to algorithms/math/collatz.js diff --git a/math/computeNCR.js b/algorithms/math/computeNCR.js similarity index 100% rename from math/computeNCR.js rename to algorithms/math/computeNCR.js diff --git a/math/degreeRadianConversion.js b/algorithms/math/degreeRadianConversion.js similarity index 100% rename from math/degreeRadianConversion.js rename to algorithms/math/degreeRadianConversion.js diff --git a/math/factorial-recursive.js b/algorithms/math/factorial-recursive.js similarity index 100% rename from math/factorial-recursive.js rename to algorithms/math/factorial-recursive.js diff --git a/math/factorial.js b/algorithms/math/factorial.js similarity index 100% rename from math/factorial.js rename to algorithms/math/factorial.js diff --git a/math/fibonacci-recursive.js b/algorithms/math/fibonacci-recursive.js similarity index 100% rename from math/fibonacci-recursive.js rename to algorithms/math/fibonacci-recursive.js diff --git a/math/fibonacci.js b/algorithms/math/fibonacci.js similarity index 100% rename from math/fibonacci.js rename to algorithms/math/fibonacci.js diff --git a/math/fibonnaci.js b/algorithms/math/fibonnaci.js similarity index 100% rename from math/fibonnaci.js rename to algorithms/math/fibonnaci.js diff --git a/math/gcd.js b/algorithms/math/gcd.js similarity index 100% rename from math/gcd.js rename to algorithms/math/gcd.js diff --git a/math/greatestCommonDivisor.js b/algorithms/math/greatestCommonDivisor.js similarity index 100% rename from math/greatestCommonDivisor.js rename to algorithms/math/greatestCommonDivisor.js diff --git a/math/naturalNumbersSum.js b/algorithms/math/naturalNumbersSum.js similarity index 100% rename from math/naturalNumbersSum.js rename to algorithms/math/naturalNumbersSum.js diff --git a/math/quadrant.js b/algorithms/math/quadrant.js similarity index 100% rename from math/quadrant.js rename to algorithms/math/quadrant.js diff --git a/math/smallest-common-multiple.js b/algorithms/math/smallest-common-multiple.js similarity index 100% rename from math/smallest-common-multiple.js rename to algorithms/math/smallest-common-multiple.js diff --git a/math/spiralMatrix.js b/algorithms/math/spiralMatrix.js similarity index 100% rename from math/spiralMatrix.js rename to algorithms/math/spiralMatrix.js diff --git a/others/bigonotaion.js b/algorithms/others/bigonotaion.js similarity index 100% rename from others/bigonotaion.js rename to algorithms/others/bigonotaion.js diff --git a/others/checkPrime.js b/algorithms/others/checkPrime.js similarity index 100% rename from others/checkPrime.js rename to algorithms/others/checkPrime.js diff --git a/others/primeFactors.js b/algorithms/others/primeFactors.js similarity index 100% rename from others/primeFactors.js rename to algorithms/others/primeFactors.js diff --git a/searches/binarySearch.js b/algorithms/searches/binarySearch.js similarity index 100% rename from searches/binarySearch.js rename to algorithms/searches/binarySearch.js diff --git a/searches/sequentialSearch.js b/algorithms/searches/sequentialSearch.js similarity index 100% rename from searches/sequentialSearch.js rename to algorithms/searches/sequentialSearch.js diff --git a/searching/binarySearch.js b/algorithms/searching/binarySearch.js similarity index 100% rename from searching/binarySearch.js rename to algorithms/searching/binarySearch.js diff --git a/searching/linearSearch.js b/algorithms/searching/linearSearch.js similarity index 100% rename from searching/linearSearch.js rename to algorithms/searching/linearSearch.js diff --git a/searching/naivePatternSearching.js b/algorithms/searching/naivePatternSearching.js similarity index 100% rename from searching/naivePatternSearching.js rename to algorithms/searching/naivePatternSearching.js diff --git a/sorting/BogoSort.js b/algorithms/sorting/BogoSort.js similarity index 100% rename from sorting/BogoSort.js rename to algorithms/sorting/BogoSort.js diff --git a/sorting/bubbleSort.js b/algorithms/sorting/bubbleSort.js similarity index 100% rename from sorting/bubbleSort.js rename to algorithms/sorting/bubbleSort.js diff --git a/sorting/countingSort.js b/algorithms/sorting/countingSort.js similarity index 100% rename from sorting/countingSort.js rename to algorithms/sorting/countingSort.js diff --git a/sorting/flashSort.js b/algorithms/sorting/flashSort.js similarity index 100% rename from sorting/flashSort.js rename to algorithms/sorting/flashSort.js diff --git a/sorting/gnomeSort.js b/algorithms/sorting/gnomeSort.js similarity index 100% rename from sorting/gnomeSort.js rename to algorithms/sorting/gnomeSort.js diff --git a/sorting/gulagSort.js b/algorithms/sorting/gulagSort.js similarity index 100% rename from sorting/gulagSort.js rename to algorithms/sorting/gulagSort.js diff --git a/sorting/heapSort.js b/algorithms/sorting/heapSort.js similarity index 100% rename from sorting/heapSort.js rename to algorithms/sorting/heapSort.js diff --git a/sorting/insertionSort.js b/algorithms/sorting/insertionSort.js similarity index 100% rename from sorting/insertionSort.js rename to algorithms/sorting/insertionSort.js diff --git a/sorting/mergeSort.js b/algorithms/sorting/mergeSort.js similarity index 100% rename from sorting/mergeSort.js rename to algorithms/sorting/mergeSort.js diff --git a/sorting/pancakeSort.js b/algorithms/sorting/pancakeSort.js similarity index 100% rename from sorting/pancakeSort.js rename to algorithms/sorting/pancakeSort.js diff --git a/sorting/quickSort.js b/algorithms/sorting/quickSort.js similarity index 100% rename from sorting/quickSort.js rename to algorithms/sorting/quickSort.js diff --git a/sorting/radixSort.js b/algorithms/sorting/radixSort.js similarity index 100% rename from sorting/radixSort.js rename to algorithms/sorting/radixSort.js diff --git a/sorting/selectionSort.js b/algorithms/sorting/selectionSort.js similarity index 100% rename from sorting/selectionSort.js rename to algorithms/sorting/selectionSort.js diff --git a/sorting/shellSort.js b/algorithms/sorting/shellSort.js similarity index 100% rename from sorting/shellSort.js rename to algorithms/sorting/shellSort.js diff --git a/strings/checkPalindrome.js b/algorithms/strings/checkPalindrome.js similarity index 100% rename from strings/checkPalindrome.js rename to algorithms/strings/checkPalindrome.js diff --git a/strings/integerReversal.js b/algorithms/strings/integerReversal.js similarity index 100% rename from strings/integerReversal.js rename to algorithms/strings/integerReversal.js diff --git a/strings/largestSumOfTwo.js b/algorithms/strings/largestSumOfTwo.js similarity index 100% rename from strings/largestSumOfTwo.js rename to algorithms/strings/largestSumOfTwo.js diff --git a/strings/missingNumber.js b/algorithms/strings/missingNumber.js similarity index 100% rename from strings/missingNumber.js rename to algorithms/strings/missingNumber.js diff --git a/strings/palindrome.js b/algorithms/strings/palindrome.js similarity index 100% rename from strings/palindrome.js rename to algorithms/strings/palindrome.js diff --git a/strings/pigLatin.js b/algorithms/strings/pigLatin.js similarity index 100% rename from strings/pigLatin.js rename to algorithms/strings/pigLatin.js diff --git a/license b/license new file mode 100644 index 0000000..559a12b --- /dev/null +++ b/license @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2018 All Algorithms and its contributors (allalgorithms.com) +Copyright (c) 2018 Carlos Abraham (abranhe.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/readme.md b/readme.md index 4deee00..dd64172 100644 --- a/readme.md +++ b/readme.md @@ -1,51 +1,416 @@ -
- +We are accepting all pull requests. [Read More](https://github.com/AllAlgorithms/algorithms/issues/40) + +




- -
+ Algorithms Logo +
+

-

All ▲lgorithms implemented in Javascript

-
- - - - - +
+
+
+ +

+ What is an algorithm?    + Contributing    + Stickers & T-Shirts +

+ + +

+ + Twitter +    + + Instagram +    + + Github +    +

+ +
+

+ Huge collection of All ▲lgorithms implemented in multiple languages +

+
+ + + + + +
-## Contents - -- [Greedy Algorithms](greedy-algorithms) -- [Graphs](graphs) -- [Math](math) -- [Neutral Network](neutral-network) -- [Ciphers](ciphers) -- [Data Structures](data-structures) -- [Dynamic Programming](dynamic-programming) -- [Hashes](hashes) -- [Searches](searches) -- [Sorting](sorting) -- [Strings](strings) -- [Traversals](traversals) -- [Others](others) +## See -## License +- [What is an algorithm](#what-is-an-algorithm) +- [Contributing](https://github.com/AllAlgorithms/algorithms/blob/master/.github/contributing.md) +- [Code of Conduct](https://github.com/AllAlgorithms/algorithms/blob/master/.github/code-of-conduct.md) +- [Stickers and T-Shirts](https://www.redbubble.com/people/abranhe/works/34285088) +- [Twitter](https://twitter.com/AllAlgorithms) +- [Instagram](https://instagram.com/AllAlgorithms) +- [Algorithms Categories](#categories) +- [Maintainers](#maintainers) +- [License](#license) + + +## What is an algorithm? + +Informally, an algorithm is any well-defined computational procedure that takes +some value, or set of values, as input and produces some value, or set of values, as +output. An algorithm is thus a sequence of computational steps that transform the +input into the output. + +An algorithm should have three important characteristics to be considered valid: + +- **It should be finite**: If your algorithm never ends trying to solve the problem +it was designed to solve then it is useless +- **It should have well defined instructions**: Each step of the algorithm has to +be precisely defined; the instructions should be unambiguously specified for each case. +- **It should be effective**: The algorithm should solve the problem it was designed +to solve. And it should be possible to demonstrate that the algorithm converges with +just a paper and pencil. + +## Categories + +> Structure of The All ▲lgoritms project + +- [Artificial Intelligence](#artificial-intelligence) +- [Backtracking](#backtracking) +- [Bit Manipulation](#bit-manipulation) +- [Cellular Automaton](#cellular-automaton) +- [Ciphers](#ciphers) +- [Computational Geometry](#computational-geometry) +- [Cryptography](#cryptography) +- [Data Structures](#data-structures) +- [Divide and conquer](#divide-and-conquer) +- [Dynamic Programming](#dynamic-programming) +- [Gaming Theory](#gaming-theory) +- [Graphs](#graphs) +- [Greedy Algorithms](#greedy-algorithms) +- [Math](#math) +- [Networking](#networking) +- [Numerical Analysis](#numerical-analysis) +- [Operating system](#operating-system) +- [Randomized Algorithms](#randomized-algorithms) +- [Searches](#searches) +- [Selections Algorithms](#selections-algorithms) +- [Sorting](#sorting) +- [Strings](#strings) +- [Online Challenges](#online-challenges) +- [Others](#others) + +## [Artificial Intelligence](artificial-intelligence) + +- [Density-based spatial clustering of applications with noise (DBSCAN Clustering)](https://allalgorithms.com/docs/dbscan) +- [Interactive Self-Organizing Data Analysis Technique yAy! (ISODATA Clustering)](https://allalgorithms.com/docs/isodata) +- [Linear Regression](https://allalgorithms.com/docs/linear-regression) +- [Logistic Regression](https://allalgorithms.com/docs/logistic-regression) +- [Neutral Style Transfer](https://allalgorithms.com/docs/neutral-style-transfer) +- [SATisfiable (SAT)](https://allalgorithms.com/docs/sat) +- [Travelling salesman problem (TSP)](https://allalgorithms.com/docs/tsp) +- [A* (A Star)](https://allalgorithms.com/docs/a-star) +- [Artificial Neutral Network](https://allalgorithms.com/docs/artificial-neutral-network) +- [Convolutional Neutral Network](https://allalgorithms.com/docs/convolutional-neutral-network) +- [Decision Tree](https://allalgorithms.com/docs/decision-tree) +- [Factorization Machines](https://allalgorithms.com/docs/factorization-machines) +- [Gaussian Mixture Model](https://allalgorithms.com/docs/gaussian-mixtrue-model) +- [Gradient Boosting Trees](https://allalgorithms.com/docs/gradient-boostring-trees) +- [Hierachical Clustering](https://allalgorithms.com/docs/hierachical-clustering) +- [Image Processing](https://allalgorithms.com/docs/image-processing) +- [K Nearest Neighbors](https://allalgorithms.com/docs/k-nearest-neighbors) +- [K Means](https://allalgorithms.com/docs/k-means) +- [Minimax](https://allalgorithms.com/docs/minimax) +- [Native Bayes](https://allalgorithms.com/docs/native-bayes) +- [Nearest Sequence Memory](https://allalgorithms.com/docs/nearest-sequence-memory) +- [Neutral Network](https://allalgorithms.com/docs/neutral-network) +- [Perceptron](https://allalgorithms.com/docs/perceptron) +- [Principal Component Analysis](https://allalgorithms.com/docs/principal-component-analysis) +- [Q Learing](https://allalgorithms.com/docs/q-learning) +- [Random Forests](https://allalgorithms.com/docs/random-forest) +- [Restricted Boltzman Machine](https://allalgorithms.com/docs/restricted-boltzman-machine) + +## [Backtracking](backtracking) + +- [Algorithm X](backtracking/algorithm-x) +- [Crossword Puzzle](backtracking/crossword-Puzzle) +- [Knight Tour](backtracking/knight-tour) +- [M Coloring Problem](backtracking/m-coloring-problem) +- [N Queen](backtracking/n-queen) +- [Number of ways in Maze](backtracking/number-of-ways-in-maze) +- [Partitions of set](backtracking/partitions-of-set) +- [Permutation of Strings](backtracking/permutation-of-strings) +- [Powerset](backtracking/powerset) +- [Rat in maze](backtracking/rat-in-maze) +- [Subset Sum](backtracking/subset-sum) +- [Sudoku Solve](backtracking/sudoku-solve) + +## [Bit Manipulation](bit-manipulation) + +- [Addition using bits](bit-manipulation/adding-using-bits) +- [Bit divisor](bit-manipulation/bit-divisor) +- [Byte swapper](bit-manipulation/byte-swapper) +- [Convert numbers to binary](bit-manipulation/convert-numbers-to-binary) +- [Count set bits](bit-manipulation/count-set-bits) +- [Flip bits](bit-manipulation/flip-bits) +- [Hamming distance](bit-manipulation/hamming-distace) +- [Invert bit](bit-manipulation/invert-bit) +- [Lonely integer](bit-manipulation/lonely-integer) +- [Magic Number](bit-manipulation/magic-number) +- [Maximum XOR Value](bit-manipulation/maximun-xor-value) +- [Power of 2](bit-manipulation/power-of-2) +- [Subset Generation](bit-manipulation/subset-generation) +- [Sum binary numbers](bit-manipulation/sum-binary-numbers) +- [Sum equals XOR](bit-manipulation/sum-equals-xor) +- [Thrice unique number](bit-manipulation/thrice-unique-number) +- [Twice unique number](bit-manipulation/twice-unique-number) +- [XOR Swap](bit-manipulation/xor-swap) + +## [Cellular Automaton](cellular-automaton) + +- [Brians Brain](cellular-automaton/brians-brain) +- [Conways Game of life](cellular-automaton/conways-game-of-life) +- [Elementary Cellular Automata](cellular-automaton/elementary-cellular-automata) +- [Generic Algorithm](cellular-automaton/generic-algorithm) +- [Langtons Ant](cellular-automaton/langtons-ant) +- [Nobili Cellular Automata](cellular-automaton/nobili-cellular-automata) +- [Von Neoumann Cellular Automata](cellular-automaton/von-neoumann-cellular-automata) + +## [Computational Geometry](computational-geometry) + +- [2D Line intersection](computational-geometry/) +- [2D Separating Axis test](computational-geometry/) +- [Area of polygon](computational-geometry/) +- [Area of triangle](computational-geometry/) +- [Axis aligned bounding box collision](computational-geometry/) +- [Bresenham Line](computational-geometry/) +- [Chans Algorithm](computational-geometry/) +- [Cohen Sutherland Lineclip](computational-geometry/) +- [Distance between points](computational-geometry/) +- [Graham Scan](computational-geometry/) +- [Halfplane intersection](computational-geometry/) +- [Jarvis March](computational-geometry/) +- [Quickull](computational-geometry/) +- [Sphere tetrahedron intersection](computational-geometry/) +- [Sutherland Hodgeman clipping](computational-geometry/) + +## [Cryptography](cryptography) + +- [Affine Cipher](cryptography/) +- [Atbash Cipher](cryptography/) +- [Autokey Cipher](cryptography/) +- [Baconian Cipher](cryptography/) +- [Caesar Cipher](cryptography/) +- [Colummnar Cipher](cryptography/) +- [Vigenere Cipher](cryptography/) -This work is licensed under a [MIT License](https://github.com/abranhe/algorithms/blob/master/LICENSE) +## [Data Structures](data-structures) -[![MIT IMG][mit-license]]((https://github.com/abranhe/algorithms/blob/master/LICENSE)) +- [Bag](data-structures/bag/) +- [Hashes](data-structures/hashes/) +- [Linked List](data-structures/linked-list/) +- [List](data-structures/list/) +- [Queue](data-structures/queue/) +- [Stack](data-structures/stack/) +- [Tree](data-structures/tree/) -To the extent possible under law, [Carlos Abraham](https://go.abranhe.com/github) has waived all copyright and related or neighboring rights to this work. +## [Divide and conquer](divide-and-conquer) +- [Strassen Matrix Manipulation](divide-and-conquer/) +- [Closest Pair of Point](divide-and-conquer/) +- [Inversion Count](divide-and-conquer/) +- [Karatsuba Multiplication](divide-and-conquer/) +- [Maximum Contiguous subsequence sum](divide-and-conquer/) +- [Merge Sort using divide and conquer](divide-and-conquer/) +- [Quick Sort using divide and conquer](divide-and-conquer/) +- [Tournament Method to find min max](divide-and-conquer/) +- [Warnock Algorithm](divide-and-conquer/) +- [X Power Y](divide-and-conquer/) -[mit-license]: https://cdn.abranhe.com/projects/algorithms/mit-license.png +## [Dynamic Programming](dynamic-programming) + +- [Array Median](dynamic-programming) +- [Optima Binary Search Tree](dynamic-programming) +- [Binomial Coefficient](dynamic-programming) + +## [Gaming Theory](gaming-theory) + +- [Nim Next Best Move Game](gaming-theory/) +- [Nim Win Loss Game](gaming-theory/) +- [Grundy Numbers Kayle Game](gaming-theory/) + +## [Graphs](graphs) + +- [Bipartite Check](graphs/) +- [Adjacency Lists graphs representation](graphs/) +- [A* (A Star)](https://allalgorithms.com/docs/a-star) + +## [Greedy Algorithms](greedy-algorithms) + +- [Activity Selection](greedy-algorithms) +- [Dijkstra Shortest Path](greedy-algorithms) +- [Egyptian Fraction](greedy-algorithms) + +## [Math](math) + +- [2 Sum](math/) +- [Add Polynomials](math/) +- [Amicable Numbers](math/) +- [Armstrong Numbers](math/) +- [Automorphic Numbers](math/) +- [Average Stream Numbers](math/) +- [Babylonian Method](math/) +- [Binomial Coefficient](math/) +- [Catalan Number](math/) +- [Check is Square](math/) +- [Convolution](math/) +- [Coprime Numbers](math/) +- [Count Digits](math/) +- [Count Trailing Zeroes](math/) +- [Decoding of String](math/) +- [Delannoy Number](math/) +- [Derangements](math/) +- [DFA Division](math/) +- [Diophantine](math/) +- [Divided Differences](math/) +- [Euler Totient](math/) +- [Exponentiation Power](math/) +- [Factorial](math/factorial) +- [Fast Fourier transform](math/) +- [Fast inverse (sqrt) Square Root](math/) + +## [Networking](networking) + +- [Packet Sniffer](networking/) +- [Determine Endianess](networking/) +- [Validate IP](networking/) + +## [Numerical Analysis](numerical-analysis) + +- [Integral](numerical-analysis/integral) +- [Monte Carlo](numerical-analysis/monte-carlo) +- [Runge Kutt](numerical-analysis/runge-kutt) + +## [Operating system](operating-system) + +- [Currency](operating-system/) +- [Deadlocks](operating-system/) +- [Memory Management](operating-system/) +- [Scheduling](operating-system/) +- [Shell](operating-system/) + +## [Randomized Algorithms](randomized-algorithms) + +- [Birthday Paradox](randomized-algorithms) +- [Karger Minimum Cut Algorithm](randomized-algorithms) +- [Kth Smallest Element Algorithm](randomized-algorithms) +- [Random from Stream](randomized-algorithms) +- [Random Node Linked list](randomized-algorithms) +- [Randomized Quicksort](randomized-algorithms) +- [Reservoir Sampling](randomized-algorithms) +- [Shuffle an Array](randomized-algorithms) + +## [Searches](searches) + +- [Binary Search](searches) +- [Exponential Search](searches) +- [Fibonacci Search](searches) +- [Fuzzy Search](searches) +- [Interpolation Search](searches) +- [Jump Search](searches) +- [Linear Search](searches) +- [Ternay Search](searches) + +## [Selections Algorithms](selections-algorithms) + +- [Median of Medians](selections-algorithms) +- [Quick Select](selections-algorithms) + +## [Sorting](sorting) + +- [Bead Sort](sorting/) +- [Bogo Sort](sorting/) +- [Bubble Sort](sorting/) +- [Bucket Sort](sorting/) +- [Circle Sort](sorting/) +- [Comb Sort](sorting/) +- [Counting Sort](sorting/) +- [Cycle Sort](sorting/) +- [Flash Sort](sorting/) +- [Gnome Sort](sorting/) +- [Heap Sort](sorting/) +- [Insertion Sort](sorting/) +- [Intro Sort](sorting/) +- [Median Sort](sorting/) +- [Merge Sort](sorting/) +- [Pipeonhole Sort](sorting/) +- [Quick Sort](sorting/) +- [Radix Sort](sorting/) +- [Selection Sort](sorting/) +- [Shaker Sort](sorting/) +- [Shell Sort](sorting/) +- [Sleep Sort](sorting/) +- [Stooge Sort](sorting/) +- [Topological Sort](sorting/) +- [Tree Sort](sorting/) + +## [Strings](strings) + +- [Aho Corasick Algorithm](strings) +- [Anagram Search](strings) +- [Arithmetic on large numbers](strings) +- [Boyer Moore Algorithm](strings) +- [Finite Automata](strings) +- [Kasai Algorithm](strings) +- [Kmp Algorithm](strings) +- [Levenshteing Distance](strings) +- [Lipogram Checker](strings) + +## [Online Challenges](online-challenges) + +- [Coderbyte](online-challenges/coderbyte) +- [Code Chef](online-challenges/code-chef) +- [Code Eval](online-challenges/code-eval) +- [Hackerearth](online-challenges/hackerearth) +- [Hackerrank](online-challenges/hackerrank) +- [LeetCode](online-challenges/leetcode) +- [Project Euler](online-challenges/project-euler) +- [Rosalind](online-challenges/rosalind) +- [SPOJ](online-challenges/spoj) +- [Top Coder](online-challenges/top-coder)` + +## [Others](others) + +- [Average](others/) +- [Biggest of n numbers](others/) +- [Biggest Suffix](others/) +- [Fifteen Puzzle](others/) +- [Jaccard Similarity](others/) +- [Jose Phus Problem](others/) +- [Lapindrom Checker](others/) +- [Leap Year](others/) +- [Magic Square](others/) +- [Majority Element](others/) +- [Minimum subarray size with degree](others/) +- [No operator addition](others/) +- [Paint fill](others/) +- [Split list](others/) +- [Tokenizer](others/) +- [Unique number](others/) + +## License + +This work is released under MIT License. + +To the extent possible under law, [Abraham Hernandez (@abranhe)](https://go.abranhe.com/github) has waived all copyright and related or neighboring rights to this work.

-
+
\ No newline at end of file diff --git a/sorting/ShellSort.js b/sorting/ShellSort.js deleted file mode 100644 index 61df2d9..0000000 --- a/sorting/ShellSort.js +++ /dev/null @@ -1,29 +0,0 @@ -/* "Shell sort or Shell's method, is an in-place comparison sort. -It can be seen as either a generalization of sorting by exchange (bubble sort) or sorting by insertion (insertion sort). -The method starts by sorting pairs of elements far apart from each other, then progressively reducing the gap between elements to be compared. -Starting with far apart elements can move some out-of-place elements into position faster than a simple nearest neighbor exchange." */ - -function shellSort(arr) { - var increment = arr.length / 2; - while (increment > 0) { - for (i = increment; i < arr.length; i++) { - var j = i; - var temp = arr[i]; - - while (j >= increment && arr[j-increment] > temp) { - arr[j] = arr[j-increment]; - j = j - increment; - } - - arr[j] = temp; - } - - if (increment == 2) { - increment = 1; - } else { - increment = parseInt(increment*5 / 11); - } - } - return arr; -} - diff --git a/src/.gitkeep b/src/.gitkeep new file mode 100644 index 0000000..e69de29 From c7d9e004c5692a98bc513165637716bac003167e Mon Sep 17 00:00:00 2001 From: Ayoola Akindolani Date: Tue, 8 Oct 2019 00:06:38 +0100 Subject: [PATCH 088/101] added algorithm to check if a given number is a perfect square --- math/isPerfectSquare.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 math/isPerfectSquare.js diff --git a/math/isPerfectSquare.js b/math/isPerfectSquare.js new file mode 100644 index 0000000..18a4dff --- /dev/null +++ b/math/isPerfectSquare.js @@ -0,0 +1,15 @@ +// JavaScript implementation of to check if a number is a perfect square +// +// Author: Ayoola Akindolani + +var isPerfectSquare = function(num) { + if (num >= 0 && Math.sqrt(num) % 1 === 0) { + console.log("Number is a perfect square."); + } else { + console.log("Number is not a perfect square."); + } +}; + +isPerfectSquare(81); +isPerfectSquare(9); +isPerfectSquare(8); From b13781baa24c0ec13a27a959b410b02e38f89fea Mon Sep 17 00:00:00 2001 From: Abdelhak Ihadjadene Date: Thu, 1 Oct 2020 01:21:12 +0100 Subject: [PATCH 089/101] added Binary Tree class with: insert, find, contains methods. --- data-structures/BinaryTree.js | 83 +++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 data-structures/BinaryTree.js diff --git a/data-structures/BinaryTree.js b/data-structures/BinaryTree.js new file mode 100644 index 0000000..245def0 --- /dev/null +++ b/data-structures/BinaryTree.js @@ -0,0 +1,83 @@ +class Node { + constructor(value) { + this.value = value; + this.left = null; + this.right = null; + } +} + +class BinarySearchTree { + constructor() { + this.root = null; + } + insert(value) { + var newNode = new Node(value); + if (this.root === null) { + this.root = newNode; + return this; + } + var current = this.root; + while (true) { + if (value === current.value) return undefined; + if (value < current.value) { + if (current.left === null) { + current.left = newNode; + return this; + } + current = current.left; + } else { + if (current.right === null) { + current.right = newNode; + return this; + } + current = current.right; + } + } + } + find(value) { + if (this.root === null) return false; + var current = this.root, + found = false; + while (current && !found) { + if (value < current.value) { + current = current.left; + } else if (value > current.value) { + current = current.right; + } else { + found = true; + } + } + if (!found) return undefined; + return current; + } + contains(value) { + if (this.root === null) return false; + var current = this.root, + found = false; + while (current && !found) { + if (value < current.value) current = current.left; + else if (value > current.value) current = current.right; + else return true; + } + return false; + } +} + +// 10 +// 5 13 +// 2 7 11 16 + +var tree = new BinarySearchTree(); +tree.insert(10); +tree.insert(5); +tree.insert(13); +tree.insert(11); +tree.insert(2); +tree.insert(16); +tree.insert(7); + +console.log(tree.find(13)); +console.log(tree.find(19)); + +console.log(tree.contains(2)); +console.log(tree.contains(534)); From 46fd9852918833f4d0717df9a7beedb74ce9d4cd Mon Sep 17 00:00:00 2001 From: Abdelhak Ihadjadene Date: Thu, 1 Oct 2020 01:34:48 +0100 Subject: [PATCH 090/101] added BFS, DFSPostOrder, DFSPreOrder and DFSInOrder algorithms as class mthods, all of them return array representaions --- data-structures/BinaryTree.js | 63 ++++++++++++++++++++++++++++++++--- 1 file changed, 59 insertions(+), 4 deletions(-) diff --git a/data-structures/BinaryTree.js b/data-structures/BinaryTree.js index 245def0..3fe0df5 100644 --- a/data-structures/BinaryTree.js +++ b/data-structures/BinaryTree.js @@ -10,6 +10,7 @@ class BinarySearchTree { constructor() { this.root = null; } + insert(value) { var newNode = new Node(value); if (this.root === null) { @@ -34,6 +35,7 @@ class BinarySearchTree { } } } + find(value) { if (this.root === null) return false; var current = this.root, @@ -50,6 +52,7 @@ class BinarySearchTree { if (!found) return undefined; return current; } + contains(value) { if (this.root === null) return false; var current = this.root, @@ -61,6 +64,53 @@ class BinarySearchTree { } return false; } + + BreadthFirstSearch() { + let node = this.root, + data = [], + queue = []; + queue.push(node); + + while (queue.length) { + node = queue.shift(); + data.push(node.value); + if (node.left) queue.push(node.left); + if (node.right) queue.push(node.right); + } + + return data; + } + + DepthFirstSearchPreOrder() { + let data = []; + function traverse(node) { + data.push(node.value); + if (node.left) traverse(node.left); + if (node.right) traverse(node.right); + } + traverse(this.root); + return data; + } + DepthFirstSearchPostOrder() { + let data = []; + function traverse(node) { + if (node.left) traverse(node.left); + if (node.right) traverse(node.right); + data.push(node.value); + } + traverse(this.root); + return data; + } + DepthFirstSearchInOrder() { + let data = []; + function traverse(node) { + if (node.left) traverse(node.left); + data.push(node.value); + if (node.right) traverse(node.right); + } + traverse(this.root); + return data; + } } // 10 @@ -76,8 +126,13 @@ tree.insert(2); tree.insert(16); tree.insert(7); -console.log(tree.find(13)); -console.log(tree.find(19)); +console.log("node with value 13:", tree.find(13)); +console.log("node with value 19:", tree.find(19)); + +console.log("tree coontais node with value 2:", tree.contains(2)); +console.log("tree coontais node with value 534:", tree.contains(534)); -console.log(tree.contains(2)); -console.log(tree.contains(534)); +console.log("BreadthFirstSearch:", tree.BreadthFirstSearch()); +console.log("DepthFirstSearchPreOrder:", tree.DepthFirstSearchPreOrder()); +console.log("DepthFirstSearchPostOrder:", tree.DepthFirstSearchPostOrder()); +console.log("DepthFirstSearchInOrder:", tree.DepthFirstSearchInOrder()); From 1ba8b512c139db4e03fca650b9e79d20e30448f8 Mon Sep 17 00:00:00 2001 From: Abdelhak Ihadjadene Date: Thu, 1 Oct 2020 01:53:13 +0100 Subject: [PATCH 091/101] added Jump Search algorithm --- searching/jumpSearch.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 searching/jumpSearch.js diff --git a/searching/jumpSearch.js b/searching/jumpSearch.js new file mode 100644 index 0000000..66c1f9c --- /dev/null +++ b/searching/jumpSearch.js @@ -0,0 +1,29 @@ +/** + * + * @param {Array} arr + * @param {Number} x + */ +function jumpSearch(arr, x) { + let len = arr.length; + let step = Math.sqrt(len); + + let prev = 0; + while (arr[parseInt(Math.min(step, len) - 1)] < x) { + prev = step; + step += Math.sqrt(len); + if (prev >= len) return -1; + } + + while (arr[parseInt(prev)] < x) { + prev += 1; + + if (prev === Math.min(step, len)) return -1; + } + if (arr[parseInt(prev)] === x) return prev; + + return -1; +} + +let arr = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]; + +console.log(jumpSearch(arr, 610)); From 80604f80eea84867850fbd5ec0f780ea2e09eda6 Mon Sep 17 00:00:00 2001 From: shirogin <42269089+shirogin@users.noreply.github.com> Date: Thu, 1 Oct 2020 02:48:25 +0100 Subject: [PATCH 092/101] Binarry Tree -Create Random Tree -Add Values -find some values --- Classes/Tree.js | 58 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Classes/Tree.js diff --git a/Classes/Tree.js b/Classes/Tree.js new file mode 100644 index 0000000..1184ad5 --- /dev/null +++ b/Classes/Tree.js @@ -0,0 +1,58 @@ +// JavaScript implementation of Binary Search + +// Author: Youcef Madadi + +// Binary Tree +export default class BinaryTree{ + left=null; + right=null; + value; + + constructor(value,left,right) { + this.value = value; + if(left instanceof BinaryTree)this.left = left; + if(right instanceof BinaryTree)this.right= right; + } + AddValue(value){ + if(value>this.value){ + if(this.right) return this.right.AddValue(value); + this.right=new BinaryTree(value) + }else if(value value ) { + if(this.left)return this.left.findValue(value); + } + else if( this.value < value ) { + if(this.right) return this.right.findValue(value); + } + else return true + return false; + } + static CreateRandomTree(){ + let root=new BinaryTree(Math.floor(Math.random() * 100)), + deep= Math.floor(Math.random() * 50); + for( let i=0 ; i Date: Thu, 1 Oct 2020 02:50:01 +0100 Subject: [PATCH 093/101] Update Tree.js --- Classes/Tree.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Classes/Tree.js b/Classes/Tree.js index 1184ad5..931518f 100644 --- a/Classes/Tree.js +++ b/Classes/Tree.js @@ -3,7 +3,7 @@ // Author: Youcef Madadi // Binary Tree -export default class BinaryTree{ +class BinaryTree{ left=null; right=null; value; From 82151f61835a14948fa82bfff0d7cad5f6eb4aa8 Mon Sep 17 00:00:00 2001 From: Johanes Boas Badia <13517009@std.stei.itb.ac.id> Date: Sat, 3 Oct 2020 21:11:15 +0700 Subject: [PATCH 094/101] add 2sum.js --- math/2sum.js | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 math/2sum.js diff --git a/math/2sum.js b/math/2sum.js new file mode 100644 index 0000000..d5c0ea3 --- /dev/null +++ b/math/2sum.js @@ -0,0 +1,30 @@ +// File name: 2sum.js +// Author: boasmarbun (https://github.com/boasmarbun) +// Date created: 02/10/2020 + +function twoSum (nums, target) { + var diff = 0; + for (var firstIndex = 0; firstIndex <= nums.length; firstIndex++) { + diff = target - nums[firstIndex]; + var secondIndex = nums.indexOf(diff, firstIndex+1); + if(secondIndex != -1) { + return [firstIndex, secondIndex]; + } + } + return [0]; +}; + +// uncomment below for testing +// var testArray1 = [1,2,3,9] +// var target1 = 5 +// var testArray2 = [0,3,4,0] +// var target2 = 0 +// var testArray3 = [-2, -3, -7, -13, -6] +// var target3 = -8 +// var testArray4 = [] +// var target4 = 2 + +// console.log(twoSum(testArray1, target1)) +// console.log(twoSum(testArray2, target2)) +// console.log(twoSum(testArray3, target3)) +// console.log(twoSum(testArray4, target4)) \ No newline at end of file From dfff5b1655e6e1956b27c147991b3945ced9b23d Mon Sep 17 00:00:00 2001 From: Mika Date: Sat, 3 Oct 2020 20:19:02 +0300 Subject: [PATCH 095/101] Added vigenere cipher --- algorithms/ciphers/vigenere.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 algorithms/ciphers/vigenere.js diff --git a/algorithms/ciphers/vigenere.js b/algorithms/ciphers/vigenere.js new file mode 100644 index 0000000..1cfe027 --- /dev/null +++ b/algorithms/ciphers/vigenere.js @@ -0,0 +1,21 @@ +function vigenere(plaintext, key) { + const upperKey = key.toUpperCase(); + let decryptedMessage = ''; + for (let i = 0, keyIndex = 0; i < plaintext.length; keyIndex += 1, i += 1) { + const char = plaintext.charCodeAt(i); + const keyCode = upperKey.charCodeAt(keyIndex % upperKey.length); + if (char >= 97 && char <= 122) { + const index = ((char - 97 + keyCode - 65) % 26); + decryptedMessage += String.fromCharCode(index + 97); + } else if (char >= 65 && char <= 90) { + const index = ((char - 65 + keyCode - 65) % 26); + decryptedMessage += String.fromCharCode(index + 65); + } else { + keyIndex -= 1; + decryptedMessage += String.fromCharCode(char); + } + } + return decryptedMessage; +} + +console.log(vigenere('The quick brown fox jumps over the lazy dog.', 'key')); // Dlc aygmo zbsux jmh nswtq yzcb xfo pyjc byk. From ecc36fb7c8fe1bf55aa665215ad837da7eab40be Mon Sep 17 00:00:00 2001 From: Abraham Hernandez Date: Sun, 4 Oct 2020 02:05:11 -0400 Subject: [PATCH 096/101] cleanup --- {Classes => algorithms/classes}/Tree.js | 0 .../data-structures}/BinaryTree.js | 0 .../dynamic-programming/cookies_function.js | 48 +++++++++++++++++++ {math => algorithms/math}/2sum.js | 0 {math => algorithms/math}/evenNumbers.js | 0 {math => algorithms/math}/isPerfectSquare.js | 0 {math => algorithms/math}/randomNumber.js | 0 .../searching}/jumpSearch.js | 0 {sorting => algorithms/sorting}/Distance.js | 0 {sorting => algorithms/sorting}/color.js | 0 {strings => algorithms/strings}/anagram.js | 0 angle-clock/clock.js | 44 ----------------- dynamic-programming/cookies_function.js | 47 ------------------ sorting/README.md | 28 ----------- sorting/gnomesort.js | 27 ----------- 15 files changed, 48 insertions(+), 146 deletions(-) rename {Classes => algorithms/classes}/Tree.js (100%) rename {data-structures => algorithms/data-structures}/BinaryTree.js (100%) create mode 100644 algorithms/dynamic-programming/cookies_function.js rename {math => algorithms/math}/2sum.js (100%) rename {math => algorithms/math}/evenNumbers.js (100%) rename {math => algorithms/math}/isPerfectSquare.js (100%) rename {math => algorithms/math}/randomNumber.js (100%) rename {searching => algorithms/searching}/jumpSearch.js (100%) rename {sorting => algorithms/sorting}/Distance.js (100%) rename {sorting => algorithms/sorting}/color.js (100%) rename {strings => algorithms/strings}/anagram.js (100%) delete mode 100644 angle-clock/clock.js delete mode 100644 dynamic-programming/cookies_function.js delete mode 100644 sorting/README.md delete mode 100644 sorting/gnomesort.js diff --git a/Classes/Tree.js b/algorithms/classes/Tree.js similarity index 100% rename from Classes/Tree.js rename to algorithms/classes/Tree.js diff --git a/data-structures/BinaryTree.js b/algorithms/data-structures/BinaryTree.js similarity index 100% rename from data-structures/BinaryTree.js rename to algorithms/data-structures/BinaryTree.js diff --git a/algorithms/dynamic-programming/cookies_function.js b/algorithms/dynamic-programming/cookies_function.js new file mode 100644 index 0000000..f522ec1 --- /dev/null +++ b/algorithms/dynamic-programming/cookies_function.js @@ -0,0 +1,48 @@ +// Useful Functions to create , read and delete the cookies. + +(function ($) { + 'use strict'; + + function createCookie(name, value, days) { + var expires; + + if (days) { + var date = new Date(); + date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000); + expires = '; expires=' + date.toGMTString(); + } else { + expires = ''; + } + document.cookie = + encodeURIComponent(name) + + '=' + + encodeURIComponent(value) + + expires + + '; path=/'; + } + + // How to Create Cookies? + createCookie('el_data', 'Prajakta'); + + function readCookie(name) { + var nameEQ = encodeURIComponent(name) + '='; + var ca = document.cookie.split(';'); + for (var i = 0; i < ca.length; i++) { + var c = ca[i]; + while (c.charAt(0) === ' ') c = c.substring(1, c.length); + if (c.indexOf(nameEQ) === 0) + return decodeURIComponent(c.substring(nameEQ.length, c.length)); + } + return null; + } + + // How to read cookies? + var name = readCookie('el_data'); + + function eraseCookie(name) { + createCookie(name, '', -1); + } + + // How to delete cookies? + eraseCookie('el_data'); +})(jQuery); diff --git a/math/2sum.js b/algorithms/math/2sum.js similarity index 100% rename from math/2sum.js rename to algorithms/math/2sum.js diff --git a/math/evenNumbers.js b/algorithms/math/evenNumbers.js similarity index 100% rename from math/evenNumbers.js rename to algorithms/math/evenNumbers.js diff --git a/math/isPerfectSquare.js b/algorithms/math/isPerfectSquare.js similarity index 100% rename from math/isPerfectSquare.js rename to algorithms/math/isPerfectSquare.js diff --git a/math/randomNumber.js b/algorithms/math/randomNumber.js similarity index 100% rename from math/randomNumber.js rename to algorithms/math/randomNumber.js diff --git a/searching/jumpSearch.js b/algorithms/searching/jumpSearch.js similarity index 100% rename from searching/jumpSearch.js rename to algorithms/searching/jumpSearch.js diff --git a/sorting/Distance.js b/algorithms/sorting/Distance.js similarity index 100% rename from sorting/Distance.js rename to algorithms/sorting/Distance.js diff --git a/sorting/color.js b/algorithms/sorting/color.js similarity index 100% rename from sorting/color.js rename to algorithms/sorting/color.js diff --git a/strings/anagram.js b/algorithms/strings/anagram.js similarity index 100% rename from strings/anagram.js rename to algorithms/strings/anagram.js diff --git a/angle-clock/clock.js b/angle-clock/clock.js deleted file mode 100644 index 7ca33be..0000000 --- a/angle-clock/clock.js +++ /dev/null @@ -1,44 +0,0 @@ -function calculateTime(hour, angle){ - var time; - - if( hour > 12){ - hour = hour -12; - } - - if(angle == 0){ - if(hour < 13){ - var mint = hour*5; - }else{ - var mint = (hour-12)*5; - } - }else{ - var mint = angle/6; - } - - if((hour*5)+Math.round(mint) < 60){ - var f_mint = (hour*5)+Math.round(mint); - }else{ - var f_mint = ((hour*5)+Math.round(mint))-60; - } - - if(f_mint >= 55){ - f_mint += 5; - }else if(f_mint >= 44){ - f_mint += 4 - }else if(f_mint >= 31){ - f_mint += 3 - }else if(f_mint >= 20){ - f_mint += 2 - }else if(f_mint >= 8){ - f_mint++ - } - - if(angle >= 180){ - time = hour + ' : ' + f_mint; - }else{ - time = hour + ' : ' + f_mint; - } - - console.log(time); -} -calculateTime(3, 179); \ No newline at end of file diff --git a/dynamic-programming/cookies_function.js b/dynamic-programming/cookies_function.js deleted file mode 100644 index efe3133..0000000 --- a/dynamic-programming/cookies_function.js +++ /dev/null @@ -1,47 +0,0 @@ -# Useful Functions to create , read and delete the cookies. - -(function( $ ) { - "use strict"; - -function createCookie(name, value, days) { - - var expires; - - if (days) { - var date = new Date(); - date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); - expires = "; expires=" + date.toGMTString(); - } else { - expires = ""; - } - document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/"; -} - -// How to Create Cookies? -createCookie('el_data', 'Prajakta'); - - -function readCookie(name) { - var nameEQ = encodeURIComponent(name) + "="; - var ca = document.cookie.split(';'); - for (var i = 0; i < ca.length; i++) { - var c = ca[i]; - while (c.charAt(0) === ' ') - c = c.substring(1, c.length); - if (c.indexOf(nameEQ) === 0) - return decodeURIComponent(c.substring(nameEQ.length, c.length)); - } - return null; -} - -// How to read cookies? -var name = readCookie('el_data'); - -function eraseCookie(name) { - createCookie(name, "", -1); -} - -// How to delete cookies? -eraseCookie('el_data'); - -})( jQuery ); diff --git a/sorting/README.md b/sorting/README.md deleted file mode 100644 index b5e612c..0000000 --- a/sorting/README.md +++ /dev/null @@ -1,28 +0,0 @@ -
- -
-
- -
-
-

Sorting ▲lgorithms implemented in Javascript

-
- -## Contents - -- [Gnome Sort]() - Gnome sort is a sorting algorithm originally proposed by Dr. Hamid Sarbazi-Azad (Professor of Computer Engineering at Sharif University of Technology) in 2000 and called "stupid sort"[1] (not to be confused with bogosort), and then later on described by Dick Grune and named "gnome sort". - The algorithm always finds the first place where two adjacent elements are in the wrong order, and swaps them. It takes advantage of the fact that performing a swap can introduce a new out-of-order adjacent pair only next to the two swapped elements.. - - - -## License - -This work is licensed under a [MIT License](https://github.com/abranhe/algorithms/blob/master/LICENSE) - -[![MIT IMG][mit-license]]((https://github.com/abranhe/algorithms/blob/master/LICENSE)) - -To the extent possible under law, [Carlos Abraham](https://go.abranhe.com/github) has waived all copyright and related or neighboring rights to this work. - - -[mit-license]: https://cdn.abraham.gq/projects/algorithms/mit-license.png diff --git a/sorting/gnomesort.js b/sorting/gnomesort.js deleted file mode 100644 index 8a2909f..0000000 --- a/sorting/gnomesort.js +++ /dev/null @@ -1,27 +0,0 @@ -/* -* Gnome sort is a sorting algorithm originally proposed by Dr. Hamid Sarbazi-Azad (Professor of Computer Engineering at Sharif University of Technology) in 2000 and called "stupid sort"[1] (not to be confused with bogosort), and then later on described by Dick Grune and named "gnome sort". The algorithm always finds the first place where two adjacent elements are in the wrong order, and swaps them. It takes advantage of the fact that performing a swap can introduce a new out-of-order adjacent pair only next to the two swapped elements. -*/ - -function gnomeSort(arr) -{ - function moveBack(i) - { - for( ; i > 0 && arr[i-1] > arr[i]; i--) - { - var t = arr[i]; - arr[i] = arr[i-1]; - arr[i-1] = t; - } - } - for (var i = 1; i < arr.length; i++) - { - if (arr[i-1] > arr[i]) moveBack(i); - } - return arr; -} - -var arra = [3, 0, 2, 5, -1, 4, 1]; -console.log("Original Array Elements"); -console.log(arra); -console.log("Sorted Array Elements"); -console.log(gnomeSort(arra)); From dc2176dea97f1bd65763726368acf966d573ee65 Mon Sep 17 00:00:00 2001 From: Nithya-Prakash Date: Wed, 7 Oct 2020 14:37:36 +0530 Subject: [PATCH 097/101] Added PascalsTriangle algorithm using Recursion --- algorithms/math/pascalsTriangle.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 algorithms/math/pascalsTriangle.js diff --git a/algorithms/math/pascalsTriangle.js b/algorithms/math/pascalsTriangle.js new file mode 100644 index 0000000..7104eb6 --- /dev/null +++ b/algorithms/math/pascalsTriangle.js @@ -0,0 +1,23 @@ +function pascalTriangleRecursive(lineNumber) { + if (lineNumber === 0) { + return [1]; + } + + const currentLineSize = lineNumber + 1; + const previousLineSize = currentLineSize - 1; + + const currentLine = []; + + const previousLine = pascalTriangleRecursive(lineNumber - 1); + + for (let numIndex = 0; numIndex < currentLineSize; numIndex += 1) { + const leftCoefficient = numIndex - 1 >= 0 ? previousLine[numIndex - 1] : 0; + const rightCoefficient = + numIndex < previousLineSize ? previousLine[numIndex] : 0; + + currentLine[numIndex] = leftCoefficient + rightCoefficient; + } + + return currentLine; +} +console.log(pascalTriangleRecursive(40)); From b3604fa3bdae44bf02be543369bb1e7115f2ba7b Mon Sep 17 00:00:00 2001 From: Jan Tabacki Date: Wed, 7 Oct 2020 08:08:53 +0200 Subject: [PATCH 098/101] * fixed toString method in stack.js implementation. Now reads all elements returns them as a string and uses data property instead of element property that did not exist. --- algorithms/data-structures/stack.js | 40 ++++++++++++++++------------- 1 file changed, 22 insertions(+), 18 deletions(-) diff --git a/algorithms/data-structures/stack.js b/algorithms/data-structures/stack.js index 22377be..62a772b 100644 --- a/algorithms/data-structures/stack.js +++ b/algorithms/data-structures/stack.js @@ -1,12 +1,15 @@ /** - * @author Rashik Ansar and Luiz Guerra - * - * - * Implemtaion of Stack data structure - * Stack follows LIFO (Last In First Out) priniciple - * For Insertion and Deletion its complexity is O(1) - * For Accessing and Searching its complexity is O(n) - */ +* @author Rashik Ansar and Luiz Guerra +* +* Implemtaion of Stack data structure +* Stack follows LIFO (Last In First Out) priniciple +* For Insertion and Deletion its complexity is O(1) +* For Accessing and Searching its complexity is O(n) +* +* @author Jan Tabacki +* Fix in toString method, display all elements and get data property instead of element +* which does no exist. +*/ class Stack { /** @@ -63,21 +66,21 @@ class Stack { } return this.first.data; } - + /** * @returns size of the Stack */ size() { return this.size; } - + /** * @returns if Stack is empty */ isEmpty() { return this.size == 0; } - + /** * clears the Stack */ @@ -86,19 +89,20 @@ class Stack { this.last = null; this.size = 0; } - + /** * @returns the Stack */ toString() { - let str = ""; + let str = ""; let aux = this.first; - for (let i = 0; i < this.count; i++) - str += aux.element + " "; - aux = aux.next; + while (aux) { + str += aux.data + " "; + aux = aux.next; + } return str; } - + } class Node { @@ -106,4 +110,4 @@ class Node { this.data = data; this.next = null; } -} +} \ No newline at end of file From 27e64ebb97d3f22a9188dbc6aee86ea77303b317 Mon Sep 17 00:00:00 2001 From: Nithya-Prakash Date: Tue, 13 Oct 2020 14:34:53 +0530 Subject: [PATCH 099/101] added iterative euclideanAlgorithm --- algorithms/math/euclideanIterative.js | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 algorithms/math/euclideanIterative.js diff --git a/algorithms/math/euclideanIterative.js b/algorithms/math/euclideanIterative.js new file mode 100644 index 0000000..77fde72 --- /dev/null +++ b/algorithms/math/euclideanIterative.js @@ -0,0 +1,12 @@ +function euclideanAlgorithmIterative(originalA, originalB) { + let a = Math.abs(originalA); + let b = Math.abs(originalB); + while (a && b && a !== b) { + [a, b] = a > b ? [a - b, b] : [a, b - a]; + } + return a || b; +} + +var gcd = euclideanAlgorithmIterative(4, 7); + +console.log(gcd); From 823ea170bda2ffff293400100b02b70661ac1fc9 Mon Sep 17 00:00:00 2001 From: Nithya-Prakash Date: Tue, 13 Oct 2020 14:47:49 +0530 Subject: [PATCH 100/101] added euclideanAlgorithm and iterative euclidean --- algorithms/math/euclidean.js | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 algorithms/math/euclidean.js diff --git a/algorithms/math/euclidean.js b/algorithms/math/euclidean.js new file mode 100644 index 0000000..ddeb520 --- /dev/null +++ b/algorithms/math/euclidean.js @@ -0,0 +1,9 @@ +function euclideanAlgorithm(originalA, originalB) { + const a = Math.abs(originalA); + const b = Math.abs(originalB); + + return b === 0 ? a : euclideanAlgorithm(b, a % b); +} + +var gcd = euclideanAlgorithm(1, 3); +console.log(gcd); From 351ccaaebc5e7ebe38d27a1258ddaf1df970a2c5 Mon Sep 17 00:00:00 2001 From: Nithya-Prakash Date: Wed, 14 Oct 2020 09:39:13 +0530 Subject: [PATCH 101/101] added max heap algorithm --- algorithms/data-structures/maxHeap.js | 77 +++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 algorithms/data-structures/maxHeap.js diff --git a/algorithms/data-structures/maxHeap.js b/algorithms/data-structures/maxHeap.js new file mode 100644 index 0000000..5d3f91d --- /dev/null +++ b/algorithms/data-structures/maxHeap.js @@ -0,0 +1,77 @@ +class BinaryHeap { + constructor() { + this.heap = []; + } + + insert(value) { + this.heap.push(value); + this.heapify(); + } + + size() { + return this.heap.length; + } + + empty() { + return this.size() === 0; + } + + heapify() { + let index = this.size() - 1; + + while (index > 0) { + const element = this.heap[index]; + const parentIndex = Math.floor((index - 1) / 2); + const parent = this.heap[parentIndex]; + + if (parent[0] >= element[0]) break; + this.heap[index] = parent; + this.heap[parentIndex] = element; + index = parentIndex; + } + } + + extractMax() { + const max = this.heap[0]; + const tmp = this.heap.pop(); + if (!this.empty()) { + this.heap[0] = tmp; + this.sinkDown(0); + } + return max; + } + + sinkDown(index) { + const left = 2 * index + 1; + const right = 2 * index + 2; + let largest = index; + const length = this.size(); + + if (left < length && this.heap[left][0] > this.heap[largest][0]) { + largest = left; + } + if (right < length && this.heap[right][0] > this.heap[largest][0]) { + largest = right; + } + // swap + if (largest !== index) { + const tmp = this.heap[largest]; + this.heap[largest] = this.heap[index]; + this.heap[index] = tmp; + this.sinkDown(largest); + } + } +} + +const maxHeap = new BinaryHeap(); +maxHeap.insert([4]); +maxHeap.insert([3]); +maxHeap.insert([6]); +maxHeap.insert([1]); +maxHeap.insert([8]); +maxHeap.insert([2]); + +while (!maxHeap.empty()) { + const mx = maxHeap.extractMax(); + console.log(mx); +}