@ -1,6 +1,6 @@
|
||||
---
|
||||
title: arithmeticProgression
|
||||
tags: math,beginner
|
||||
tags: math,algorithm,beginner
|
||||
---
|
||||
|
||||
Creates an array of numbers in the arithmetic progression, starting with the given positive integer and up to the specified limit.
|
||||
@ -8,7 +8,7 @@ Creates an array of numbers in the arithmetic progression, starting with the giv
|
||||
- Use `Array.from()` to create an array of the desired length, `lim/n`, and a map function to fill it with the desired values in the given range.
|
||||
|
||||
```js
|
||||
const arithmeticProgression = (n, lim) =>
|
||||
const arithmeticProgression = (n, lim) =>
|
||||
Array.from({ length: Math.ceil(lim / n) }, (_, i) => (i + 1) * n );
|
||||
```
|
||||
|
||||
|
||||
32
snippets/binarySearch.md
Normal file
32
snippets/binarySearch.md
Normal file
@ -0,0 +1,32 @@
|
||||
---
|
||||
title: binarySearch
|
||||
tags: algorithm,array,beginner
|
||||
---
|
||||
|
||||
Finds the index of a given element in a sorted array using the binary search algorithm.
|
||||
|
||||
- Declare the left and right search boundaries, `l` and `r`, initialized to `0` and the `length` of the array respectively.
|
||||
- Use a `while` loop to repeatedly narrow down the search subarray, using `Math.floor()` to cut it in half.
|
||||
- Return the index of the element if found, otherwise return `-1`.
|
||||
- **Note:** Does not account for duplicate values in the array.
|
||||
|
||||
```js
|
||||
const binarySearch = (arr, item) => {
|
||||
let l = 0,
|
||||
r = arr.length - 1;
|
||||
while (l <= r) {
|
||||
const mid = Math.floor((l + r) / 2);
|
||||
const guess = arr[mid];
|
||||
if (guess === item) return mid;
|
||||
if (guess > item) r = mid - 1;
|
||||
else l = mid + 1;
|
||||
}
|
||||
return -1;
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
binarySearch([1, 2, 3, 4, 5], 1); // 0
|
||||
binarySearch([1, 2, 3, 4, 5], 5); // 4
|
||||
binarySearch([1, 2, 3, 4, 5], 6); // -1
|
||||
```
|
||||
@ -1,6 +1,6 @@
|
||||
---
|
||||
title: binomialCoefficient
|
||||
tags: math,beginner
|
||||
tags: math,algorithm,beginner
|
||||
---
|
||||
|
||||
Calculates the number of ways to choose `k` items from `n` items without repetition and without order.
|
||||
|
||||
34
snippets/bubbleSort.md
Normal file
34
snippets/bubbleSort.md
Normal file
@ -0,0 +1,34 @@
|
||||
---
|
||||
title: bubbleSort
|
||||
tags: algorithm,array,beginner
|
||||
---
|
||||
|
||||
Sorts an array of numbers, using the bubble sort algorithm.
|
||||
|
||||
- Declare a variable, `swapped`, that indicates if any values were swapped during the current iteration.
|
||||
- Use the spread operator (`...`) to clone the original array, `arr`.
|
||||
- Use a `for` loop to iterate over the elements of the cloned array, terminating before the last element.
|
||||
- Use a nested `for` loop to iterate over the segment of the array between `0` and `i`, swapping any adjacent out of order elements and setting `swapped` to `true`.
|
||||
- If `swapped` is `false` after an iteration, no more changes are needed, so the cloned array is returned.
|
||||
|
||||
```js
|
||||
const bubbleSort = arr => {
|
||||
let swapped = false;
|
||||
const a = [...arr];
|
||||
for (let i = 1; i < a.length - 1; i++) {
|
||||
swapped = false;
|
||||
for (let j = 0; j < a.length - i; j++) {
|
||||
if (a[j + 1] < a[j]) {
|
||||
[a[j], a[j + 1]] = [a[j + 1], a[j]];
|
||||
swapped = true;
|
||||
}
|
||||
}
|
||||
if (!swapped) return a;
|
||||
}
|
||||
return a;
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
bubbleSort([2, 1, 4, 3]); // [1, 2, 3, 4]
|
||||
```
|
||||
30
snippets/bucketSort.md
Normal file
30
snippets/bucketSort.md
Normal file
@ -0,0 +1,30 @@
|
||||
---
|
||||
title: bucketSort
|
||||
tags: algorithm,array,intermediate
|
||||
---
|
||||
|
||||
Sorts an array of numbers, using the bucket sort algorithm.
|
||||
|
||||
- Use `Math.min(),` `Math.max()` and the spread operator (`...`) to find the minimum and maximum values of the given array.
|
||||
- Use `Array.from()` and `Math.floor()` to create the appropriate number of `buckets` (empty arrays).
|
||||
- Use `Array.prototype.forEach()` to populate each bucket with the appropriate elements from the array.
|
||||
- Use `Array.prototype.reduce()`, the spread operator (`...`) and `Array.prototype.sort()` to sort each bucket and append it to the result.
|
||||
|
||||
```js
|
||||
const bucketSort = (arr, size = 5) => {
|
||||
const min = Math.min(...arr);
|
||||
const max = Math.max(...arr);
|
||||
const buckets = Array.from(
|
||||
{ length: Math.floor((max - min) / size) + 1 },
|
||||
() => []
|
||||
);
|
||||
arr.forEach(val => {
|
||||
buckets[Math.floor((val - min) / size)].push(val);
|
||||
});
|
||||
return buckets.reduce((acc, b) => [...acc, ...b.sort((a, b) => a - b)], []);
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
bucketSort([6, 3, 4, 1]); // [1, 3, 4, 6]
|
||||
```
|
||||
34
snippets/caesarCipher.md
Normal file
34
snippets/caesarCipher.md
Normal file
@ -0,0 +1,34 @@
|
||||
---
|
||||
title: caesarCipher
|
||||
tags: algorithm,string,beginner
|
||||
---
|
||||
|
||||
Encrypts or decrypts a given string using the Caesar cipher.
|
||||
|
||||
- Use the modulo (`%`) operator and the ternary operator (`?`) to calculate the correct encryption/decryption key.
|
||||
- Use the spread operator (`...`) and `Array.prototype.map()` to iterate over the letters of the given string.
|
||||
- Use `String.prototype.charCodeAt()` and `String.fromCharCode()` to convert each letter appropriately, ignoring special characters, spaces etc.
|
||||
- Use `Array.prototype.join()` to combine all the letters into a string.
|
||||
- Pass `true` to the last parameter, `decrypt`, to decrypt an encrypted string.
|
||||
|
||||
```js
|
||||
const caesarCipher = (str, shift, decrypt = false) => {
|
||||
const s = decrypt ? (26 - shift) % 26 : shift;
|
||||
const n = s > 0 ? s : 26 + (s % 26);
|
||||
return [...str]
|
||||
.map((l, i) => {
|
||||
const c = str.charCodeAt(i);
|
||||
if (c >= 65 && c <= 90)
|
||||
return String.fromCharCode(((c - 65 + n) % 26) + 65);
|
||||
if (c >= 97 && c <= 122)
|
||||
return String.fromCharCode(((c - 97 + n) % 26) + 97);
|
||||
return l;
|
||||
})
|
||||
.join('');
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
caesarCipher('Hello World!', -3); // 'Ebiil Tloia!'
|
||||
caesarCipher('Ebiil Tloia!', 23, true); // 'Hello World!'
|
||||
```
|
||||
18
snippets/cartesianProduct.md
Normal file
18
snippets/cartesianProduct.md
Normal file
@ -0,0 +1,18 @@
|
||||
---
|
||||
title: cartesianProduct
|
||||
tags: math,array,beginner
|
||||
---
|
||||
|
||||
Calculates the cartesian product of two arrays.
|
||||
|
||||
- Use `Array.prototype.reduce()`, `Array.prototype.map()` and the spread operator (`...`) to generate all possible element pairs from the two arrays.
|
||||
|
||||
```js
|
||||
const cartesianProduct = (a, b) =>
|
||||
a.reduce((p, x) => [...p, ...b.map(y => [x, y])], []);
|
||||
```
|
||||
|
||||
```js
|
||||
cartesianProduct(['x', 'y'], [1, 2]);
|
||||
// [['x', 1], ['x', 2], ['y', 1], ['y', 2]]
|
||||
```
|
||||
@ -1,6 +1,6 @@
|
||||
---
|
||||
title: distance
|
||||
tags: math,beginner
|
||||
tags: math,algorithm,beginner
|
||||
---
|
||||
|
||||
Calculates the distance between two points.
|
||||
|
||||
19
snippets/euclideanDistance.md
Normal file
19
snippets/euclideanDistance.md
Normal file
@ -0,0 +1,19 @@
|
||||
---
|
||||
title: euclideanDistance
|
||||
tags: math,algorithm,intermediate
|
||||
---
|
||||
|
||||
Calculates the distance between two points in any number of dimensions.
|
||||
|
||||
- Use `Object.keys()` and `Array.prototype.map()` to map each coordinate to its difference between the two points.
|
||||
- Use `Math.hypot()` to calculate the Euclidean distance between the two points.
|
||||
|
||||
```js
|
||||
const euclideanDistance = (a, b) =>
|
||||
Math.hypot(...Object.keys(a).map(k => b[k] - a[k]));
|
||||
```
|
||||
|
||||
```js
|
||||
euclideanDistance([1, 1], [2, 3]); // ~2.2361
|
||||
euclideanDistance([1, 1, 1], [2, 3, 2]); // ~2.4495
|
||||
```
|
||||
@ -1,6 +1,6 @@
|
||||
---
|
||||
title: factorial
|
||||
tags: math,recursion,beginner
|
||||
tags: math,algorithm,recursion,beginner
|
||||
---
|
||||
|
||||
Calculates the factorial of a number.
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
---
|
||||
title: fibonacci
|
||||
tags: math,intermediate
|
||||
tags: math,algorithm,intermediate
|
||||
---
|
||||
|
||||
Generates an array, containing the Fibonacci sequence, up until the nth term.
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
---
|
||||
title: gcd
|
||||
tags: math,recursion,beginner
|
||||
tags: math,algorithm,recursion,intermediate
|
||||
---
|
||||
|
||||
Calculates the greatest common divisor between two or more numbers/arrays.
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
---
|
||||
title: geometricProgression
|
||||
tags: math,intermediate
|
||||
tags: math,algorithm,intermediate
|
||||
---
|
||||
|
||||
Initializes an array containing the numbers in the specified range where `start` and `end` are inclusive and the ratio between two terms is `step`.
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
---
|
||||
title: hammingDistance
|
||||
tags: math,intermediate
|
||||
tags: math,algorithm,intermediate
|
||||
---
|
||||
|
||||
Calculates the Hamming distance between two values.
|
||||
|
||||
43
snippets/heapsort.md
Normal file
43
snippets/heapsort.md
Normal file
@ -0,0 +1,43 @@
|
||||
---
|
||||
title: heapsort
|
||||
tags: algorithm,array,recursion,advanced
|
||||
---
|
||||
|
||||
Sorts an array of numbers, using the heapsort algorithm.
|
||||
|
||||
- Use recursion.
|
||||
- Use the spread operator (`...`) to clone the original array, `arr`.
|
||||
- Use closures to declare a variable, `l`, and a function `heapify`.
|
||||
- Use a `for` loop and `Math.floor()` in combination with `heapify` to create a max heap from the array.
|
||||
- Use a `for` loop to repeatedly narrow down the considered range, using `heapify` and swapping values as necessary in order to sort the cloned array.
|
||||
|
||||
```js
|
||||
const heapsort = arr => {
|
||||
const a = [...arr];
|
||||
let l = a.length;
|
||||
|
||||
const heapify = (a, i) => {
|
||||
const left = 2 * i + 1;
|
||||
const right = 2 * i + 2;
|
||||
let max = i;
|
||||
if (left < l && a[left] > a[max]) max = left;
|
||||
if (right < l && a[right] > a[max]) max = right;
|
||||
if (max !== i) {
|
||||
[a[max], a[i]] = [a[i], a[max]];
|
||||
heapify(a, max);
|
||||
}
|
||||
};
|
||||
|
||||
for (let i = Math.floor(l / 2); i >= 0; i -= 1) heapify(a, i);
|
||||
for (i = a.length - 1; i > 0; i--) {
|
||||
[a[0], a[i]] = [a[i], a[0]];
|
||||
l--;
|
||||
heapify(a, 0);
|
||||
}
|
||||
return a;
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
heapsort([6, 3, 4, 1]); // [1, 3, 4, 6]
|
||||
```
|
||||
34
snippets/insertionSort.md
Normal file
34
snippets/insertionSort.md
Normal file
@ -0,0 +1,34 @@
|
||||
---
|
||||
title: insertionSort
|
||||
tags: algorithm,array,intermediate
|
||||
---
|
||||
|
||||
Sorts an array of numbers, using the insertion sort algorithm.
|
||||
|
||||
- Use `Array.prototype.reduce()` to iterate over all the elements in the given array.
|
||||
- If the `length` of the accumulator is `0`, add the current element to it.
|
||||
- Use `Array.prototype.some()` to iterate over the results in the accumulator until the correct position is found.
|
||||
- Use `Array.prototype.splice()` to insert the current element into the accumulator.
|
||||
|
||||
```js
|
||||
const insertionSort = arr =>
|
||||
arr.reduce((acc, x) => {
|
||||
if (!acc.length) return [x];
|
||||
acc.some((y, j) => {
|
||||
if (x <= y) {
|
||||
acc.splice(j, 0, x);
|
||||
return true;
|
||||
}
|
||||
if (x > y && j === acc.length - 1) {
|
||||
acc.splice(j + 1, 0, x);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
return acc;
|
||||
}, []);
|
||||
```
|
||||
|
||||
```js
|
||||
insertionSort([6, 3, 4, 1]); // [1, 3, 4, 6]
|
||||
```
|
||||
@ -1,6 +1,6 @@
|
||||
---
|
||||
title: isPrime
|
||||
tags: math,beginner
|
||||
tags: math,algorithm,beginner
|
||||
---
|
||||
|
||||
Checks if the provided integer is a prime number.
|
||||
|
||||
58
snippets/kMeans.md
Normal file
58
snippets/kMeans.md
Normal file
@ -0,0 +1,58 @@
|
||||
---
|
||||
title: kMeans
|
||||
tags: algorithm,array,advanced
|
||||
---
|
||||
|
||||
Groups the given data into `k` clusters using the k-means clustering algorithm.
|
||||
|
||||
- Use `Array.from()` and `Array.prototype.slice()` to initialize appropriate variables for the cluster `centroids`, `distances` and `classes`.
|
||||
- Use a `while` loop to repeat the assignment and update steps as long as there are changes in the previous iteration, as indicated by `itr`.
|
||||
- Calculate the euclidean distance between each data point and centroid using `Math.hypot()`, `Object.keys()` and `Array.prototype.map()`.
|
||||
- Use `Array.prototype.indexOf()` and `Math.min()` to find the closest centroid.
|
||||
- Use `Array.from()` and `Array.prototype.reduce()`, as well as `parseFloat()` and `Number.prototype.toFixed()` to calculate the new centroids.
|
||||
|
||||
```js
|
||||
const kMeans = (data, k = 1) => {
|
||||
const centroids = data.slice(0, k);
|
||||
const distances = Array.from({ length: data.length }, () =>
|
||||
Array.from({ length: k }, () => 0)
|
||||
);
|
||||
const classes = Array.from({ length: data.length }, () => -1);
|
||||
let itr = true;
|
||||
|
||||
while (itr) {
|
||||
itr = false;
|
||||
|
||||
for (let d in data) {
|
||||
for (let c = 0; c < k; c++) {
|
||||
distances[d][c] = Math.hypot(
|
||||
...Object.keys(data[0]).map(key => data[d][key] - centroids[c][key])
|
||||
);
|
||||
}
|
||||
const m = distances[d].indexOf(Math.min(...distances[d]));
|
||||
if (classes[d] !== m) itr = true;
|
||||
classes[d] = m;
|
||||
}
|
||||
|
||||
for (let c = 0; c < k; c++) {
|
||||
centroids[c] = Array.from({ length: data[0].length }, () => 0);
|
||||
const size = data.reduce((acc, _, d) => {
|
||||
if (classes[d] === c) {
|
||||
acc++;
|
||||
for (let i in data[0]) centroids[c][i] += data[d][i];
|
||||
}
|
||||
return acc;
|
||||
}, 0);
|
||||
for (let i in data[0]) {
|
||||
centroids[c][i] = parseFloat(Number(centroids[c][i] / size).toFixed(2));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return classes;
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
kMeans([[0, 0], [0, 1], [1, 3], [2, 0]], 2); // [0, 1, 1, 0]
|
||||
```
|
||||
49
snippets/kNearestNeighbors.md
Normal file
49
snippets/kNearestNeighbors.md
Normal file
@ -0,0 +1,49 @@
|
||||
---
|
||||
title: kNearestNeighbors
|
||||
tags: algorithm,array,advanced
|
||||
---
|
||||
|
||||
Classifies a data point relative to a labelled data set using the k-nearest neighbors algorithm.
|
||||
|
||||
- Use `Array.prototype.map()` to map the `data` to objects containing the euclidean distance of each element from `point`, calculated using `Math.hypot()`, `Object.keys()` and its `label`.
|
||||
- Use `Array.prototype.sort()` and `Array.prototype.slice()` to get the `k` nearest neighbors of `point`.
|
||||
- Use `Array.prototype.reduce()` in combination with `Object.keys()` and `Array.prototype.indexOf()` to find the most frequent `label` among them.
|
||||
|
||||
```js
|
||||
const kNearestNeighbors = (data, labels, point, k = 3) => {
|
||||
const kNearest = data
|
||||
.map((el, i) => ({
|
||||
dist: Math.hypot(...Object.keys(el).map(key => point[key] - el[key])),
|
||||
label: labels[i]
|
||||
}))
|
||||
.sort((a, b) => a.dist - b.dist)
|
||||
.slice(0, k);
|
||||
|
||||
return kNearest.reduce(
|
||||
(acc, { label }, i) => {
|
||||
acc.classCounts[label] =
|
||||
Object.keys(acc.classCounts).indexOf(label) !== -1
|
||||
? acc.classCounts[label] + 1
|
||||
: 1;
|
||||
if (acc.classCounts[label] > acc.topClassCount) {
|
||||
acc.topClassCount = acc.classCounts[label];
|
||||
acc.topClass = label;
|
||||
}
|
||||
return acc;
|
||||
},
|
||||
{
|
||||
classCounts: {},
|
||||
topClass: kNearest[0].label,
|
||||
topClassCount: 0
|
||||
}
|
||||
).topClass;
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
const data = [[0, 0], [0, 1], [1, 3], [2, 0]];
|
||||
const labels = [0, 1, 1, 0];
|
||||
|
||||
kNearestNeighbors(data, labels, [1, 2], 2); // 1
|
||||
kNearestNeighbors(data, labels, [1, 0], 2); // 0
|
||||
```
|
||||
@ -1,6 +1,6 @@
|
||||
---
|
||||
title: lcm
|
||||
tags: math,recursion,intermediate
|
||||
tags: math,algorithm,recursion,intermediate
|
||||
---
|
||||
|
||||
Calculates the least common multiple of two or more numbers.
|
||||
|
||||
38
snippets/levenshteinDistance.md
Normal file
38
snippets/levenshteinDistance.md
Normal file
@ -0,0 +1,38 @@
|
||||
---
|
||||
title: levenshteinDistance
|
||||
tags: string,algorithm,intermediate
|
||||
---
|
||||
|
||||
Calculates the difference between two strings.
|
||||
|
||||
- If either of the two strings has a `length` of zero, return the `length` of the other one.
|
||||
- Use a `for` loop to iterate over the letters of the target string and a nested `for` loop to iterate over the letters of the source string.
|
||||
- Calculate the cost of substituting the letters corresponding to `i - 1` and `j - 1` in the target and source respectively (`0` if they are the same, `1` otherwise).
|
||||
- Use `Math.min()` to populate each element in the 2D array with the minimum of the cell above incremented by one, the cell to the left incremented by one or the cell to the top left incremented by the previously calculated cost.
|
||||
- Return the last element of the last row of the produced array.
|
||||
|
||||
```js
|
||||
const levenshteinDistance = (s, t) => {
|
||||
if (!s.length) return t.length;
|
||||
if (!t.length) return s.length;
|
||||
const arr = [];
|
||||
for (let i = 0; i <= t.length; i++) {
|
||||
arr[i] = [i];
|
||||
for (let j = 1; j <= s.length; j++) {
|
||||
arr[i][j] =
|
||||
i === 0
|
||||
? j
|
||||
: Math.min(
|
||||
arr[i - 1][j] + 1,
|
||||
arr[i][j - 1] + 1,
|
||||
arr[i - 1][j - 1] + (s[j - 1] === t[i - 1] ? 0 : 1)
|
||||
);
|
||||
}
|
||||
}
|
||||
return arr[t.length][s.length];
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
levenshteinDistance('duck', 'dark'); // 2
|
||||
```
|
||||
25
snippets/linearSearch.md
Normal file
25
snippets/linearSearch.md
Normal file
@ -0,0 +1,25 @@
|
||||
---
|
||||
title: linearSearch
|
||||
tags: algorithm,array,beginner
|
||||
---
|
||||
|
||||
Finds the first index of a given element in an array using the linear search algorithm.
|
||||
|
||||
- Use a `for...in` loop to iterate over the indexes of the given array.
|
||||
- Check if the element in the corresponding index is equal to `item`.
|
||||
- If the element is found, return the index, using the unary `+` operator to convert it from a string to a number.
|
||||
- If the element is not found after iterating over the whole array, return `-1`.
|
||||
|
||||
```js
|
||||
const linearSearch = (arr, item) => {
|
||||
for (const i in arr) {
|
||||
if (arr[i] === item) return +i;
|
||||
}
|
||||
return -1;
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
linearSearch([2, 9, 9], 9); // 1
|
||||
linearSearch([2, 9, 9], 7); // -1
|
||||
```
|
||||
@ -1,6 +1,6 @@
|
||||
---
|
||||
title: luhnCheck
|
||||
tags: math,advanced
|
||||
tags: math,algorithm,advanced
|
||||
---
|
||||
|
||||
Implementation of the [Luhn Algorithm](https://en.wikipedia.org/wiki/Luhn_algorithm) used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers etc.
|
||||
|
||||
30
snippets/mergeSort.md
Normal file
30
snippets/mergeSort.md
Normal file
@ -0,0 +1,30 @@
|
||||
---
|
||||
title: mergeSort
|
||||
tags: algorithm,array,recursion,advanced
|
||||
---
|
||||
|
||||
Sorts an array of numbers, using the merge sort algorithm.
|
||||
|
||||
- Use recursion.
|
||||
- If the `length` of the array is less than `2`, return the array.
|
||||
- Use `Math.floor()` to calculate the middle point of the array.
|
||||
- Use `Array.prototype.slice()` to slice the array in two and recursively call `mergeSort()` on the created subarrays.
|
||||
- Finally, use `Array.from()` and `Array.prototype.shift()` to combine the two sorted subarrays into one.
|
||||
|
||||
```js
|
||||
const mergeSort = arr => {
|
||||
if (arr.length < 2) return arr;
|
||||
const mid = Math.floor(arr.length / 2);
|
||||
const l = mergeSort(arr.slice(0, mid));
|
||||
const r = mergeSort(arr.slice(mid, arr.length));
|
||||
return Array.from({ length: l.length + r.length }, () => {
|
||||
if (!l.length) return r.shift();
|
||||
else if (!r.length) return l.shift();
|
||||
else return l[0] > r[0] ? r.shift() : l.shift();
|
||||
});
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
mergeSort([5, 1, 4, 2, 3]); // [1, 2, 3, 4, 5]
|
||||
```
|
||||
26
snippets/mergeSortedArrays.md
Normal file
26
snippets/mergeSortedArrays.md
Normal file
@ -0,0 +1,26 @@
|
||||
---
|
||||
title: mergeSortedArrays
|
||||
tags: array,intermediate
|
||||
---
|
||||
|
||||
Merges two sorted arrays into one.
|
||||
|
||||
- Use the spread operator (`...`) to clone both of the given arrays.
|
||||
- Use `Array.from()` to create an array of the appropriate length based on the given arrays.
|
||||
- Use `Array.prototype.shift()` to populate the newly created array from the removed elements of the cloned arrays.
|
||||
|
||||
```js
|
||||
const mergeSortedArrays = (a, b) => {
|
||||
const _a = [...a],
|
||||
_b = [...b];
|
||||
return Array.from({ length: _a.length + _b.length }, () => {
|
||||
if (!_a.length) return _b.shift();
|
||||
else if (!_b.length) return _a.shift();
|
||||
else return _a[0] > _b[0] ? _b.shift() : _a.shift();
|
||||
});
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
mergeSortedArrays([1, 4, 5], [2, 3, 6]); // [1, 2, 3, 4, 5, 6]
|
||||
```
|
||||
@ -1,6 +1,6 @@
|
||||
---
|
||||
title: permutations
|
||||
tags: array,recursion,advanced
|
||||
tags: array,algorithm,recursion,advanced
|
||||
---
|
||||
|
||||
Generates all permutations of an array's elements (contains duplicates).
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
---
|
||||
title: powerset
|
||||
tags: math,beginner
|
||||
tags: math,algorithm,beginner
|
||||
---
|
||||
|
||||
Returns the powerset of a given array of numbers.
|
||||
|
||||
29
snippets/primeFactors.md
Normal file
29
snippets/primeFactors.md
Normal file
@ -0,0 +1,29 @@
|
||||
---
|
||||
title: primeFactors
|
||||
tags: math,algorithm,beginner
|
||||
---
|
||||
|
||||
Finds the prime factors of a given number using the trial division algorithm.
|
||||
|
||||
- Use a `while` loop to iterate over all possible prime factors, starting with `2`.
|
||||
- If the current factor, `f`, exactly divides `n`, add `f` to the factors array and divide `n` by `f`. Otherwise, increment `f` by one.
|
||||
|
||||
```js
|
||||
const primeFactors = n => {
|
||||
let a = [],
|
||||
f = 2;
|
||||
while (n > 1) {
|
||||
if (n % f === 0) {
|
||||
a.push(f);
|
||||
n /= f;
|
||||
} else {
|
||||
f++;
|
||||
}
|
||||
}
|
||||
return a;
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
primeFactors(147); // [3, 7, 7]
|
||||
```
|
||||
@ -1,6 +1,6 @@
|
||||
---
|
||||
title: primes
|
||||
tags: math,intermediate
|
||||
tags: math,algorithm,intermediate
|
||||
---
|
||||
|
||||
Generates primes up to a given number, using the Sieve of Eratosthenes.
|
||||
|
||||
38
snippets/quickSort.md
Normal file
38
snippets/quickSort.md
Normal file
@ -0,0 +1,38 @@
|
||||
---
|
||||
title: quickSort
|
||||
tags: algorithm,array,recursion,advanced
|
||||
---
|
||||
|
||||
Sorts an array of numbers, using the quicksort algorithm.
|
||||
|
||||
- Use recursion.
|
||||
- Use the spread operator (`...`) to clone the original array, `arr`.
|
||||
- If the `length` of the array is less than `2`, return the cloned array.
|
||||
- Use `Math.floor()` to calculate the index of the pivot element.
|
||||
- Use `Array.prototype.reduce()` and `Array.prototype.push()` to split the array into two subarrays (elements smaller or equal to the `pivot` and elements greater than it), destructuring the result into two arrays.
|
||||
- Recursively call `quickSort()` on the created subarrays.
|
||||
|
||||
```js
|
||||
const quickSort = arr => {
|
||||
const a = [...arr];
|
||||
if (a.length < 2) return a;
|
||||
const pivotIndex = Math.floor(arr.length / 2);
|
||||
const pivot = a[pivotIndex];
|
||||
const [lo, hi] = a.reduce(
|
||||
(acc, val, i) => {
|
||||
if (val < pivot || (val === pivot && i != pivotIndex)) {
|
||||
acc[0].push(val);
|
||||
} else if (val > pivot) {
|
||||
acc[1].push(val);
|
||||
}
|
||||
return acc;
|
||||
},
|
||||
[[], []]
|
||||
);
|
||||
return [...quickSort(lo), pivot, ...quickSort(hi)];
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
quickSort([1, 6, 1, 5, 3, 2, 1, 4]); // [1, 1, 1, 2, 3, 4, 5, 6]
|
||||
```
|
||||
27
snippets/selectionSort.md
Normal file
27
snippets/selectionSort.md
Normal file
@ -0,0 +1,27 @@
|
||||
---
|
||||
title: selectionSort
|
||||
tags: algorithm,array,intermediate
|
||||
---
|
||||
|
||||
Sorts an array of numbers, using the selection sort algorithm.
|
||||
|
||||
- Use the spread operator (`...`) to clone the original array, `arr`.
|
||||
- Use a `for` loop to iterate over elements in the array.
|
||||
- Use `Array.prototype.slice()` and `Array.prototype.reduce()` to find the index of the minimum element in the subarray to the right of the current index and perform a swap, if necessary.
|
||||
|
||||
```js
|
||||
const selectionSort = arr => {
|
||||
const a = [...arr];
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
const min = a
|
||||
.slice(i + 1)
|
||||
.reduce((acc, val, j) => (val < a[acc] ? j + i + 1 : acc), i);
|
||||
if (min !== i) [a[i], a[min]] = [a[min], a[i]];
|
||||
}
|
||||
return a;
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
selectionSort([5, 1, 4, 2, 3]); // [1, 2, 3, 4, 5]
|
||||
```
|
||||
@ -1,6 +1,6 @@
|
||||
---
|
||||
title: vectorDistance
|
||||
tags: math,beginner
|
||||
tags: math,algorithm,beginner
|
||||
---
|
||||
|
||||
Calculates the distance between two vectors.
|
||||
|
||||
Reference in New Issue
Block a user