fix(guide) add stubs, update spellings and prepare for move (#36531)

* fix(guide) add stubs and correct file path misspellings and pr… (#36528)

* fix: corrected file path to match curriculum

* fix: renamed to newer challenge name

* fix: added solutions to articles from challenge files

* fix: added missing .english to file name

* fix: added missing title to guide article

* fix: correct solution for guide article

* fix: replaced stub with hint

* fix: added space in Hint headers

* fix: added solution to guide article

* fix: added solution to guide article

* test: replaced stub with hint and solution

* fix: add Problem number: to title

* fix: changed generatorexponential to correct name

* fix: renamed knight's tour to knights-tour

* fix: updated guide article
This commit is contained in:
mrugesh
2019-07-30 00:25:58 +05:30
committed by GitHub
parent e23c80a021
commit 91df817cfe
89 changed files with 3074 additions and 129 deletions

View File

@@ -0,0 +1,35 @@
---
title: Averages/Mode
---
# Averages/Mode
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function mode(arr) {
const counter = {};
let result = [];
let max = 0;
// for (const i in arr) {
arr.forEach(el => {
if (!(el in counter)) {
counter[el] = 0;
}
counter[el]++;
if (counter[el] === max) {
result.push(el);
}
else if (counter[el] > max) {
max = counter[el];
result = [el];
}
});
return result;
}
```
</details>

View File

@@ -0,0 +1,76 @@
---
title: Averages-Pythagorean means
---
# Averages-Pythagorean means
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function pythagoreanMeans(rangeArr) {
// arithmeticMean :: [Number] -> Number
const arithmeticMean = xs =>
foldl((sum, n) => sum + n, 0, xs) / length(xs);
// geometricMean :: [Number] -> Number
const geometricMean = xs =>
raise(foldl((product, x) => product * x, 1, xs), 1 / length(xs));
// harmonicMean :: [Number] -> Number
const harmonicMean = xs =>
length(xs) / foldl((invSum, n) => invSum + (1 / n), 0, xs);
// GENERIC FUNCTIONS ------------------------------------------------------
// A list of functions applied to a list of arguments
// <*> :: [(a -> b)] -> [a] -> [b]
const ap = (fs, xs) => //
Array.prototype.concat(...fs.map(f => //
Array.prototype.concat(...xs.map(x => [f(x)]))));
// foldl :: (b -> a -> b) -> b -> [a] -> b
const foldl = (f, a, xs) => xs.reduce(f, a);
// length :: [a] -> Int
const length = xs => xs.length;
// mapFromList :: [(k, v)] -> Dictionary
const mapFromList = kvs =>
foldl((a, [k, v]) =>
(a[(typeof k === 'string' && k)] = v, a), {}, kvs);
// raise :: Num -> Int -> Num
const raise = (n, e) => Math.pow(n, e);
/*
// show :: a -> String
// show :: a -> Int -> String
const show = (...x) =>
JSON.stringify.apply(
null, x.length > 1 ? [x[0], null, x[1]] : x
);
*/
// zip :: [a] -> [b] -> [(a,b)]
const zip = (xs, ys) =>
xs.slice(0, Math.min(xs.length, ys.length))
.map((x, i) => [x, ys[i]]);
// TEST -------------------------------------------------------------------
// mean :: Dictionary
const mean = mapFromList(zip(
['Arithmetic', 'Geometric', 'Harmonic'],
ap([arithmeticMean, geometricMean, harmonicMean], [
rangeArr
])
));
return {
values: mean,
test: `is A >= G >= H ? ${mean.Arithmetic >= mean.Geometric &&
mean.Geometric >= mean.Harmonic ? 'yes' : 'no'}`
};
}
```
</details>

View File

@@ -0,0 +1,18 @@
---
title: Averages-Root mean square
---
# Averages-Root mean square
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function rms(arr) {
const sumOfSquares = arr.reduce((s, x) => s + x * x, 0);
return Math.sqrt(sumOfSquares / arr.length);
}
```
</details>

View File

@@ -1,10 +0,0 @@
---
title: Averages/Mode
---
# Averages/Mode
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/rosetta-code/averagesmode/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

View File

@@ -1,10 +0,0 @@
---
title: Averages/Pythagorean means
---
# Averages/Pythagorean means
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/rosetta-code/averagespythagorean-means/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

View File

@@ -1,10 +0,0 @@
---
title: Averages/Root mean square
---
# Averages/Root mean square
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/rosetta-code/averagesroot-mean-square/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->

View File

@@ -0,0 +1,26 @@
---
title: Cumulative standard deviation
---
# Cumulative standard deviation
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function standardDeviation(arr) {
var sum = 0,
sum_sq = 0,
n = arr.length;
arr.forEach(function(e) {
sum += e;
sum_sq += e * e;
})
var std_dev=Math.sqrt((sum_sq / n) - Math.pow(sum / n, 2))
return Math.round(std_dev*1000)/1000;
}
```
</details>

View File

@@ -0,0 +1,40 @@
---
title: CUSIP
---
# CUSIP
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function isCusip(s) {
if (s.length != 9) return false;
var sum = 0;
var ASCII = x => x.charCodeAt(0);
for (var i = 0; i < 7; i++) {
var c = s.charCodeAt(i);
var v;
if (c >= ASCII('0') && c <= ASCII('9')) {
v = c - 48;
} else if (c >= ASCII('A') && c <= ASCII('Z')) {
v = c - 64; // lower case letters apparently invalid
} else if (c == ASCII('*')) {
v = 36;
} else if (c == ASCII('@')) {
v = 37;
} else if (c == ASCII('#')) {
v = 38;
} else {
return false;
}
if (i % 2 == 1) v *= 2; // check if odd as using 0-based indexing
sum += Math.floor(v / 10) + v % 10;
}
return s.charCodeAt(8) - 48 == (10 - (sum % 10)) % 10;
}
```
</details>

View File

@@ -0,0 +1,66 @@
---
title: Cut a rectangle
---
# Cut a rectangle
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function cutRectangle(w, h) {
if (w % 2 == 1 && h % 2 == 1)
return;
var dirs = [[0, -1], [-1, 0], [0, 1], [1, 0]];
var grid = new Array(h); for (var i = 0; i < grid.length; i++) grid[i]=new Array(w);
var stack = [];
var half = Math.floor((w * h) / 2);
var bits = Math.pow(2, half) - 1;
var result=0;
for (; bits > 0; bits -= 2) {
for (var i = 0; i < half; i++) {
var r = Math.floor(i / w);
var c = i % w;
grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;
grid[h - r - 1][w - c - 1] = 1 - grid[r][c];
}
stack.push(0);
grid[0][0] = 2;
var count = 1;
while (stack.length!=0) {
var pos = stack.pop();
var r = Math.floor(pos / w);
var c = pos % w;
for (var dir of dirs) {
var nextR = r + dir[0];
var nextC = c + dir[1];
if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {
if (grid[nextR][nextC] == 1) {
stack.push(nextR * w + nextC);
grid[nextR][nextC] = 2;
count++;
}
}
}
}
if (count == half) {
result++;
}
}
return result;
}
```
</details>

View File

@@ -0,0 +1,20 @@
---
title: Dot product
---
# Dot product
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function dotProduct(ary1, ary2) {
var dotprod = 0;
for (var i = 0; i < ary1.length; i++)
dotprod += ary1[i] * ary2[i];
return dotprod;
}
```
</details>

View File

@@ -0,0 +1,303 @@
---
title: K-d tree
---
# K-d tree
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function kdNN(fpoints, fpoint) {
function Node(obj, dimension, parent) {
this.obj = obj;
this.left = null;
this.right = null;
this.parent = parent;
this.dimension = dimension;
}
function kdTree(points, metric, dimensions) {
var self = this;
function buildTree(points, depth, parent) {
var dim = depth % dimensions.length,
median,
node;
if (points.length === 0) {
return null;
}
if (points.length === 1) {
return new Node(points[0], dim, parent);
}
points.sort(function (a, b) {
return a[dimensions[dim]] - b[dimensions[dim]];
});
median = Math.floor(points.length / 2);
node = new Node(points[median], dim, parent);
node.left = buildTree(points.slice(0, median), depth + 1, node);
node.right = buildTree(points.slice(median + 1), depth + 1, node);
return node;
}
this.root = buildTree(points, 0, null);
this.insert = function (point) {
function innerSearch(node, parent) {
if (node === null) {
return parent;
}
var dimension = dimensions[node.dimension];
if (point[dimension] < node.obj[dimension]) {
return innerSearch(node.left, node);
} else {
return innerSearch(node.right, node);
}
}
var insertPosition = innerSearch(this.root, null),
newNode,
dimension;
if (insertPosition === null) {
this.root = new Node(point, 0, null);
return;
}
newNode = new Node(point, (insertPosition.dimension + 1) % dimensions.length, insertPosition);
dimension = dimensions[insertPosition.dimension];
if (point[dimension] < insertPosition.obj[dimension]) {
insertPosition.left = newNode;
} else {
insertPosition.right = newNode;
}
};
this.nearest = function (point, maxNodes, maxDistance) {
var i,
result,
bestNodes;
bestNodes = new BinaryHeap(
function (e) { return -e[1]; }
);
function nearestSearch(node) {
var bestChild,
dimension = dimensions[node.dimension],
ownDistance = metric(point, node.obj),
linearPoint = {},
linearDistance,
otherChild,
i;
function saveNode(node, distance) {
bestNodes.push([node, distance]);
if (bestNodes.size() > maxNodes) {
bestNodes.pop();
}
}
for (i = 0; i < dimensions.length; i += 1) {
if (i === node.dimension) {
linearPoint[dimensions[i]] = point[dimensions[i]];
} else {
linearPoint[dimensions[i]] = node.obj[dimensions[i]];
}
}
linearDistance = metric(linearPoint, node.obj);
if (node.right === null && node.left === null) {
if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) {
saveNode(node, ownDistance);
}
return;
}
if (node.right === null) {
bestChild = node.left;
} else if (node.left === null) {
bestChild = node.right;
} else {
if (point[dimension] < node.obj[dimension]) {
bestChild = node.left;
} else {
bestChild = node.right;
}
}
nearestSearch(bestChild);
if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) {
saveNode(node, ownDistance);
}
if (bestNodes.size() < maxNodes || Math.abs(linearDistance) < bestNodes.peek()[1]) {
if (bestChild === node.left) {
otherChild = node.right;
} else {
otherChild = node.left;
}
if (otherChild !== null) {
nearestSearch(otherChild);
}
}
}
if (maxDistance) {
for (i = 0; i < maxNodes; i += 1) {
bestNodes.push([null, maxDistance]);
}
}
if (self.root)
nearestSearch(self.root);
result = [];
for (i = 0; i < Math.min(maxNodes, bestNodes.content.length); i += 1) {
if (bestNodes.content[i][0]) {
result.push([bestNodes.content[i][0].obj, bestNodes.content[i][1]]);
}
}
return result;
};
}
function BinaryHeap(scoreFunction) {
this.content = [];
this.scoreFunction = scoreFunction;
}
BinaryHeap.prototype = {
push: function (element) {
// Add the new element to the end of the array.
this.content.push(element);
// Allow it to bubble up.
this.bubbleUp(this.content.length - 1);
},
pop: function () {
// Store the first element so we can return it later.
var result = this.content[0];
// Get the element at the end of the array.
var end = this.content.pop();
// If there are any elements left, put the end element at the
// start, and let it sink down.
if (this.content.length > 0) {
this.content[0] = end;
this.sinkDown(0);
}
return result;
},
peek: function () {
return this.content[0];
},
size: function () {
return this.content.length;
},
bubbleUp: function (n) {
// Fetch the element that has to be moved.
var element = this.content[n];
// When at 0, an element can not go up any further.
while (n > 0) {
// Compute the parent element's index, and fetch it.
var parentN = Math.floor((n + 1) / 2) - 1,
parent = this.content[parentN];
// Swap the elements if the parent is greater.
if (this.scoreFunction(element) < this.scoreFunction(parent)) {
this.content[parentN] = element;
this.content[n] = parent;
// Update 'n' to continue at the new position.
n = parentN;
}
// Found a parent that is less, no need to move it further.
else {
break;
}
}
},
sinkDown: function (n) {
// Look up the target element and its score.
var length = this.content.length,
element = this.content[n],
elemScore = this.scoreFunction(element);
while (true) {
// Compute the indices of the child elements.
var child2N = (n + 1) * 2, child1N = child2N - 1;
// This is used to store the new position of the element,
// if any.
var swap = null;
// If the first child exists (is inside the array)...
if (child1N < length) {
// Look it up and compute its score.
var child1 = this.content[child1N],
child1Score = this.scoreFunction(child1);
// If the score is less than our element's, we need to swap.
if (child1Score < elemScore)
swap = child1N;
}
// Do the same checks for the other child.
if (child2N < length) {
var child2 = this.content[child2N],
child2Score = this.scoreFunction(child2);
if (child2Score < (swap == null ? elemScore : child1Score)) {
swap = child2N;
}
}
// If the element needs to be moved, swap it, and continue.
if (swap != null) {
this.content[n] = this.content[swap];
this.content[swap] = element;
n = swap;
}
// Otherwise, we are done.
else {
break;
}
}
}
};
var dims = []
for (var i = 0; i < fpoint.length; i++) dims.push(i)
var tree = new kdTree(fpoints, function (e1, e2) {
var d = 0;
var e3 = e1;
if (!Array.isArray(e1)) {
e3 = []
for (var key in e1)
e3.push(e1[key])
e1 = e3
}
e1.forEach(function (e, i) {
var sqd = (e1[i] - e2[i]);
d += sqd * sqd;
})
return d;
}, dims)
return tree.nearest(fpoint, 1, 1000)[0][0];
}
```
</details>

View File

@@ -0,0 +1,23 @@
---
title: Kaprekar numbers
---
# Kaprekar numbers
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function isKaprekar(n, bs) {
if (n < 1) return false;
if (n == 1) return true;
for (var a = n * n, b = 0, s = 1; a; s *= bs) {
b += a % bs * s;
a = Math.floor(a / bs);
if (b && a + b == n) return true;
} return false;
}
```
</details>

View File

@@ -0,0 +1,96 @@
---
title: Knight's tour
---
# Knight's tour
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function knightTour (w, h) {
var b, cnt=0;
var dx = [ -2, -2, -1, 1, 2, 2, 1, -1 ];
var dy = [ -1, 1, 2, 2, 1, -1, -2, -2 ];
function init_board()
{
var i, j, k, x, y;
// * b is board; a is board with 2 rows padded at each side
for(i=0;i<h;i++){
for(j=0;j<w;j++){
b[i][j]=255
}
}
for (i = 0; i < h; i++) {
for (j = 0; j < w; j++) {
for (k = 0; k < 8; k++) {
x = j + dx[k], y = i + dy[k];
if (b[i][j] == 255) b[i][j] = 0;
if(x >= 0 && x < w && y >= 0 && y < h) b[i][j]++;
}
}
}
}
function walk_board(x, y)
{
var i, nx, ny, least;
var steps = 0;
// printf(E"H"E"J"E"%d;%dH"E"32m[]"E"m", y + 1, 1 + 2 * x);
while (1) {
// * occupy cell
b[y][x] = 255;
// * reduce all neighbors' neighbor count
for (i = 0; i < 8; i++)
if(y+dy[i] >= 0 && x+dx[i] >= 0 && y+dy[i] < h && x+dx[i] < w)
b[ y + dy[i] ][ x + dx[i] ]--;
// find neighbor with lowest neighbor count
least = 255;
for (i = 0; i < 8; i++) {
if(y+dy[i] >= 0 && x+dx[i] >= 0 && y+dy[i] < h && x+dx[i] < w)
if (b[ y + dy[i] ][ x + dx[i] ] < least) {
nx = x + dx[i];
ny = y + dy[i];
least = b[ny][nx];
}
}
if (least > 7) {
return steps == w * h - 1;
}
steps++;
x = nx, y = ny;
}
}
function solve (x, y) {
b=new Array(h);
for(var i=0;i<h;i++)
b[i]=new Array(w)
init_board();
if (walk_board(x, y)) {
cnt++;
}
}
for(var i=0;i<h;i++){
for(var j=0;j<w;j++){
solve(j, i);
}
}
return cnt;
}
```
</details>

View File

@@ -0,0 +1,29 @@
---
title: Largest int from concatenated ints
---
# Largest int from concatenated ints
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function maxCombine(xs) {
return parseInt(
xs.sort(
function(x, y) {
var a = x.toString(),
b = y.toString(),
ab = parseInt(a + b),
ba = parseInt(b + a);
return ab > ba ? -1 : (ab < ba ? 1 : 0);
}
)
.join(''), 10
);
}
```
</details>

View File

@@ -0,0 +1,25 @@
---
title: Last Friday of each month
---
# Last Friday of each month
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function lastFriday (year, month) {
var i, last_day;
i = 0;
while (true) {
last_day = new Date(year, month, i);
if (last_day.getDay() === 5) {
return last_day.getDate();
}
i -= 1;
}
};
```
</details>

View File

@@ -0,0 +1,17 @@
---
title: Leap year
---
# Leap year
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function isLeapYear (year) {
return (year % 100 === 0) ? (year % 400 === 0) : (year % 4 === 0);
}
```
</details>

View File

@@ -0,0 +1,23 @@
---
title: Least common multiple
---
# Least common multiple
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function LCM (A) {
var n = A.length, a = Math.abs(A[0]);
for (var i = 1; i < n; i++)
{ var b = Math.abs(A[i]), c = a;
while (a && b){ a > b ? a %= b : b %= a; }
a = Math.abs(c*A[i])/(a+b);
}
return a;
}
```
</details>

View File

@@ -0,0 +1,32 @@
---
title: Left factorials
---
# Left factorials
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function leftFactorial(n) {
if (n == 0)
return 0
if (n == 1)
return 1;
// Note: for n>=20, the result may not be correct.
// This is because JavaScript uses 53 bit integers and
// for n>=20 result becomes too large.
let res = 2, fact = 2;
for (var i = 2; i < n; i++) {
res += fact;
fact *= (i + 1);
}
return res;
}
```
</details>

View File

@@ -0,0 +1,19 @@
---
title: Sort an array of composite structures
---
# Sort an array of composite structures
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function sortByKey (arr) {
return arr.sort(function(a, b) {
return a.key - b.key
});
}
```
</details>

View File

@@ -0,0 +1,31 @@
---
title: Sort disjoint sublist
---
# Sort disjoint sublist
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function sortDisjoint(values, indices) {
let sublist = [];
indices.sort(function (a, b) { return a - b; });
for (let i = 0; i < indices.length; i++) {
sublist.push(values[indices[i]]);
}
sublist.sort((a, b) => { return a - b; });
for (let i = 0; i < indices.length; i++) {
values[indices[i]] = sublist[i];
}
return values;
}
```
</details>

View File

@@ -0,0 +1,18 @@
---
title: Sort stability
---
# Sort stability
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function stableSort(arr) {
arr.sort(function(a, b) { return (a[1] < b[1] ? -1 : (a[1] > b[1] ? 1 : 0)) });
return arr;
}
```
</details>

View File

@@ -0,0 +1,23 @@
---
title: Sort using a custom comparator
---
# Sort using a custom comparator
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function lengthSorter(arr) {
arr.sort(function(a, b) {
var result = b.length - a.length;
if (result == 0)
result = a.localeCompare(b);
return result;
})
return arr;
}
```
</details>

View File

@@ -0,0 +1,49 @@
---
title: Sorting algorithms/Bead sort
---
# Sorting algorithms/Bead sort
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function beadSort(arr) {
var max = 0;
for (var i = 0; i < arr.length; i++)
if (arr[i] > max)
max = arr[i];;
var grid = new Array(arr.length);
for (var i = 0; i < grid.length; i++) {
grid[i] = new Array(max);
}
var levelcount = new Array(max);
levelcount.fill(0)
for (var i = 0; i < max; i++) {
levelcount[i] = 0;
for (var j = 0; j < arr.length; j++)
grid[j][i] = '_';
};
for (var i = 0; i < arr.length; i++) {
var num = arr[i];
for (var j = 0; num > 0; j++) {
grid[levelcount[j]++][j] = '*';
num--;
};
};
var sorted = new Array(arr.length)
sorted.fill(0)
for (var i = 0; i < arr.length; i++) {
var putt = 0;
for (var j = 0; j < max && (function(c) {
return c.charCodeAt == null ? c : c.charCodeAt(0);
})(grid[arr.length - 1 - i][j]) == '*'.charCodeAt(0); j++)
putt++;
sorted[i] = putt;
};
return sorted;
}
```
</details>

View File

@@ -0,0 +1,35 @@
---
title: Sorting algorithms/Bogosort
---
# Sorting algorithms/Bogosort
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function bogosort(v) {
function shuffle(v) {
for (var j, x, i = v.length; i; j = Math.floor(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
return v;
};
function isSorted(v) {
for (var i = 1; i < v.length; i++) {
if (v[i - 1] > v[i]) {
return false;
}
}
return true;
}
var sorted = false;
while (sorted == false) {
v = shuffle(v);
sorted = isSorted(v);
}
return v;
}
```
</details>

View File

@@ -0,0 +1,43 @@
---
title: Sorting algorithms/Cocktail sort
---
# Sorting algorithms/Cocktail sort
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function cocktailSort(arr) {
let isSorted = true;
while (isSorted) {
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
let temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
isSorted = true;
}
}
if (!isSorted)
break;
isSorted = false;
for (let j = arr.length - 1; j > 0; j--) {
if (arr[j - 1] > arr[j]) {
let temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
isSorted = true;
}
}
}
return arr;
}
```
</details>

View File

@@ -0,0 +1,56 @@
---
title: Sorting algorithms/Comb sort
---
# Sorting algorithms/Comb sort
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function combSort(arr) {
function is_array_sorted(arr) {
var sorted = true;
for (var i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
sorted = false;
break;
}
}
return sorted;
}
var iteration_count = 0;
var gap = arr.length - 2;
var decrease_factor = 1.25;
// Until array is not sorted, repeat iterations
while (!is_array_sorted(arr)) {
// If not first gap
if (iteration_count > 0)
// Calculate gap
gap = (gap == 1) ? gap : Math.floor(gap / decrease_factor);
// Set front and back elements and increment to a gap
var front = 0;
var back = gap;
while (back <= arr.length - 1) {
// If elements are not ordered swap them
if (arr[front] > arr[back]) {
var temp = arr[front];
arr[front] = arr[back];
arr[back] = temp;
}
// Increment and re-run swapping
front += 1;
back += 1;
}
iteration_count += 1;
}
return arr;
}
```
</details>

View File

@@ -0,0 +1,27 @@
---
title: Sorting algorithms/Gnome sort
---
# Sorting algorithms/Gnome sort
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function gnomeSort(a) {
function moveBack(i) {
for (; i > 0 && a[i - 1] > a[i]; i--) {
var t = a[i];
a[i] = a[i - 1];
a[i - 1] = t;
}
}
for (var i = 1; i < a.length; i++) {
if (a[i - 1] > a[i]) moveBack(i);
}
return a;
}
```
</details>

View File

@@ -0,0 +1,45 @@
---
title: Sorting algorithms/Pancake sort
---
# Sorting algorithms/Pancake sort
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function pancakeSort(arr) {
for (var i = arr.length - 1; i >= 1; i--) {
// find the index of the largest element not yet sorted
var max_idx = 0;
var max = arr[0];
for (var j = 1; j <= i; j++) {
if (arr[j] > max) {
max = arr[j];
max_idx = j;
}
}
if (max_idx == i)
continue; // element already in place
var new_slice;
// flip arr max element to index 0
if (max_idx > 0) {
new_slice = arr.slice(0, max_idx + 1).reverse();
for (var 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 (var j = 0; j <= i; j++)
arr[j] = new_slice[j];
}
return arr;
}
```
</details>

View File

@@ -0,0 +1,53 @@
---
title: Sorting algorithms/Permutation sort
---
# Sorting algorithms/Permutation sort
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function permutationSort(arr) {
function pSort(a) {
var list = [];
permute(a, a.length, list);
for (var i = 0; i < list.length; i++) {
var x = list[i];
if (isSorted(x))
return x;
}
return a;
};
function permute(a, n, list) {
if (n === 1) {
var b = a.slice();
list.push(b);
return;
}
for (var i = 0; i < n; i++) {
swap(a, i, n - 1);
permute(a, n - 1, list);
swap(a, i, n - 1);
};
};
function isSorted(a) {
for (var i = 1; i < a.length; i++)
if (a[i - 1] > a[i])
return false;;
return true;
};
function swap(arr, i, j) {
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
};
return pSort(arr);
}
```
</details>

View File

@@ -0,0 +1,25 @@
---
title: Sorting algorithms/Shell sort
---
# Sorting algorithms/Shell sort
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function shellSort(a) {
for (var h = a.length; h > 0; h = parseInt(h / 2)) {
for (var i = h; i < a.length; i++) {
var k = a[i];
for (var j = i; j >= h && k < a[j - h]; j -= h)
a[j] = a[j - h];
a[j] = k;
}
}
return a;
}
```
</details>

View File

@@ -0,0 +1,40 @@
---
title: Sorting algorithms/Stooge sort
---
# Sorting algorithms/Stooge sort
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function stoogeSort(arr) {
function stoogeSortRecurse(array, i, j) {
if (j === undefined) {
j = array.length - 1;
}
if (i === undefined) {
i = 0;
}
if (array[j] < array[i]) {
var aux = array[i];
array[i] = array[j];
array[j] = aux;
}
if (j - i > 1) {
var t = Math.floor((j - i + 1) / 3);
stoogeSortRecurse(array, i, j - t);
stoogeSortRecurse(array, i + t, j);
stoogeSortRecurse(array, i, j - t);
}
}
stoogeSortRecurse(arr);
return arr;
}
```
</details>

View File

@@ -0,0 +1,47 @@
---
title: Sorting algorithms/Strand sort
---
# Sorting algorithms/Strand sort
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function strandSort(list) {
function merge(left, right) {
var result = [];
while (left.length != 0 && right.length != 0) {
if (left[0] <= right[0])
result.push(left.shift());
else
result.push(right.shift());
}
result.push.apply(result, left);
result.push.apply(result, right);
return result;
}
if (list.length <= 1) return list;
var result = [];
while (list.length > 0) {
var sorted = [];
sorted.push(list.shift());
var len = list.length;
for (var i = 1; i < len; i++) {
var elem = list[i];
if (sorted[i - 1] <= elem) {
sorted.push(elem);
sorted.splice(i, 1);
}
}
result = merge(result, sorted);
}
return result;
}
```
</details>

View File

@@ -0,0 +1,38 @@
---
title: Soundex
---
# Soundex
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function soundex(s) {
var a = s.toLowerCase().split('')
var f = a.shift(),
r = '',
codes = {
a: '', e: '', i: '', o: '', u: '',
b: 1, f: 1, p: 1, v: 1,
c: 2, g: 2, j: 2, k: 2, q: 2, s: 2, x: 2, z: 2,
d: 3, t: 3,
l: 4,
m: 5, n: 5,
r: 6
};
r = f + a
.map(function(v, i, a) {
return codes[v]
})
.filter(function(v, i, a) {
return ((i === 0) ? v !== codes[f] : v !== a[i - 1]);
})
.join('');
return (r + '000').slice(0, 4).toUpperCase();
}
```
</details>

View File

@@ -0,0 +1,31 @@
---
title: Spiral matrix
---
# Spiral matrix
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function spiralArray(n) {
var arr = Array(n),
x = 0, y = n,
total = n * n--,
dx = 1, dy = 0,
i = 0, j = 0;
while (y) arr[--y] = [];
while (i < total) {
arr[y][x] = i++;
x += dx; y += dy;
if (++j == n) {
if (dy < 0) { x++; y++; n -= 2 }
j = dx; dx = -dy; dy = j; j = 0;
}
}
return arr;
}
```
</details>

View File

@@ -0,0 +1,46 @@
---
title: Split a character string based on change of character
---
# Split a character string based on change of character
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function split(str) {
const concat = xs =>
xs.length > 0 ? (() => {
const unit = typeof xs[0] === 'string' ? '' : [];
return unit.concat.apply(unit, xs);
})() : [];
const group = xs => groupBy((a, b) => a === b, xs);
const groupBy = (f, xs) => {
const dct = xs.slice(1)
.reduce((a, x) => {
const
h = a.active.length > 0 ? a.active[0] : undefined,
blnGroup = h !== undefined && f(h, x);
return {
active: blnGroup ? a.active.concat([x]) : [x],
sofar: blnGroup ? a.sofar : a.sofar.concat([a.active])
};
}, {
active: xs.length > 0 ? [xs[0]] : [],
sofar: []
});
return dct.sofar.concat(dct.active.length > 0 ? [dct.active] : []);
};
const map = (f, xs) => xs.map(f);
const stringChars = s => s.split('');
return map(concat, group(stringChars(str)))
}
```
</details>

View File

@@ -0,0 +1,58 @@
---
title: State name puzzle
---
# State name puzzle
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function solve(input) {
var orig = {};
input.forEach(function(e) {
orig[e.replace(/\s/g, "").toLowerCase()] = e;
})
input = Object.keys(orig)
var map = {};
for (var i = 0; i < input.length - 1; i++) {
var pair0 = input[i];
for (var j = i + 1; j < input.length; j++) {
var pair = [pair0, input[j]];
var s = pair0 + pair[1];
var key = s.split("").sort();
var val = map[key] ? map[key] : [];
val.push(pair);
map[key] = val;
}
}
var result = [];
Object.keys(map).forEach((key) => {
for (var i = 0; i < map[key].length - 1; i++) {
var a = map[key][i];
for (var j = i + 1; j < map[key].length; j++) {
var b = map[key][j];
if ((new Set([a[0], b[0], a[1], b[1]])).size < 4)
continue;
var from = [orig[a[0]], orig[a[1]]].sort()
var to = [orig[b[0]], orig[b[1]]].sort()
result.push({
from,
to
})
}
}
});
return result;
}
```
</details>

View File

@@ -0,0 +1,26 @@
---
title: Stern-Brocot sequence
---
# Stern-Brocot sequence
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function sternBrocot(num) {
function f(n) {
return n < 2 ? n : (n & 1) ? f(Math.floor(n / 2)) + f(Math.floor(n / 2 + 1)) : f(Math.floor(n / 2));
}
function gcd(a, b) {
return a ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b;
}
var n;
for (n = 1; f(n) != num; n++);
return n;
}
```
</details>

View File

@@ -0,0 +1,52 @@
---
title: Straddling checkerboard
---
# Straddling checkerboard
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function straddle(message, alphabet) {
var prefixes = new Array("", alphabet[0].indexOf(" "), alphabet[0].lastIndexOf(" "))
var out = ""
message = message.toUpperCase()
message = message.replace(/([0-9])/g, "/$1") // dumb way to escape numbers
for (var i = 0; i < message.length; i++) {
var chr = message[i]
if (chr == " ") continue
for (var j = 0; j < 3; j++) {
var k = alphabet[j].indexOf(chr)
if (k < 0) continue
out += prefixes[j].toString() + k
}
if (chr == "/") out += message[++i]
}
return out
}
function unstraddle(message, alphabet) {
var prefixes = new Array("", alphabet[0].indexOf(" "), alphabet[0].lastIndexOf(" "))
var out = ""
var n, o
for (var i = 0; i < message.length; i++) {
n = message[i] * 1
switch (n) {
case prefixes[1]:
o = alphabet[1][message[++i]];
break
case prefixes[2]:
o = alphabet[2][message[++i]];
break
default:
o = alphabet[0][n]
}
o == "/" ? out += message[++i] : out += o
}
return out
}
```
</details>

View File

@@ -0,0 +1,37 @@
---
title: Stream Merge
---
# Stream Merge
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function mergeLists(lists) {
function merge (l1, l2) {
var result = [], i=0, j=0;
while (l1.length && l2.length) {
if(l1[i]<=l2[j]){
result.push(l1.shift());
}else{
result.push(l2.shift());
}
}
result.push.apply(result, l1);
result.push.apply(result, l2);
return result;
}
var result=lists[0];
for (var i = 1; i < lists.length; i++) {
result=merge(result, lists[i]);
}
return result;
}
```
</details>

View File

@@ -0,0 +1,21 @@
---
title: Strip control codes and extended characters from a string
---
# Strip control codes and extended characters from a string
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function strip(s) {
return s.split('').filter(function(x) {
var n = x.charCodeAt(0);
return 31 < n && 127 > n;
}).join('');
}
```
</details>

View File

@@ -0,0 +1,34 @@
---
title: Subleq
---
# Subleq
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function Subleq(mem) {
var out = "";
var instructionPointer = 0;
do {
var a = mem[instructionPointer];
var b = mem[instructionPointer + 1];
if (a === -1) {} else if (b === -1) {
out += String.fromCharCode(mem[a]);
} else {
mem[b] -= mem[a];
if (mem[b] < 1) {
instructionPointer = mem[instructionPointer + 2];
continue;
}
}
instructionPointer += 3;
} while ((instructionPointer >= 0));
return out;
}
```
</details>

View File

@@ -0,0 +1,194 @@
---
title: Sudoku
---
# Sudoku
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function solveSudoku(puzzle) {
var solution;
class DoX {
constructor(V, H) {
this.V = V;
this.L = this;
this.R = this;
this.U = this;
this.D = this;
this.S = 1;
this.H = H || this;
H && (H.S += 1);
}
}
const addRight = (e, n) => {
n.R = e.R;
n.L = e;
e.R.L = n;
return e.R = n;
};
const addBelow = (e, n) => {
n.D = e.D;
n.U = e;
e.D.U = n;
return e.D = n;
};
const search = function(h, s) {
if (h.R == h) {
printSol(s);
} else {
let c = chooseColumn(h);
cover(c);
for (let r = c.D; r != c; r = r.D) {
s.push(r);
for (let j = r.R; r != j; j = j.R) {
cover(j.H);
}
search(h, s);
r = s.pop();
for (let j = r.R; j != r; j = j.R) {
uncover(j.H);
}
}
uncover(c);
}
};
const chooseColumn = h => {
let s = Number.POSITIVE_INFINITY;
let c = h;
for (let j = h.R; j != h; j = j.R) {
if (j.S < s) {
c = j;
s = j.S;
}
}
return c;
};
const cover = c => {
c.L.R = c.R;
c.R.L = c.L;
for (let i = c.D; i != c; i = i.D) {
for (let j = i.R; j != i; j = j.R) {
j.U.D = j.D;
j.D.U = j.U;
j.H.S = j.H.S - 1;
}
}
};
const uncover = c => {
for (let i = c.U; i != c; i = i.U) {
for (let j = i.L; i != j; j = j.L) {
j.H.S = j.H.S + 1;
j.U.D = j;
j.D.U = j;
}
}
c.L.R = c;
c.R.L = c;
};
const printSol = a => {
solution = a.reduce((p, c) => {
let [i, v] = c.V.split(':');
p[i * 1] = v;
return p;
}, new Array(a.length).fill('.'));
};
const gridMeta = s => {
const g = s.split('');
const cellCount = g.length;
const tokenCount = Math.sqrt(cellCount);
const N = Math.sqrt(tokenCount);
const g2D = g.map(e => isNaN(e * 1) ?
new Array(tokenCount).fill(1).map((_, i) => i + 1) : [e * 1]);
return [cellCount, N, tokenCount, g2D];
};
const indexesN = n => i => {
let c = Math.floor(i / (n * n));
i %= n * n;
return [c, i, Math.floor(c / n) * n + Math.floor(i / n)];
};
const reduceGrid = puzString => {
const [
numCells, // The total number of cells in a grid (81 for a 9x9 grid)
N, // the 'n' value of the grid. (3 for a 9x9 grid)
U, // The total number of unique tokens to be placed.
g2D // A 2D array representation of the grid, with each element
// being an array of candidates for a cell. Known cells are
// single element arrays.
] = gridMeta(puzString);
const getIndex = indexesN(N);
const headRow = new Array(4 * numCells)
.fill('')
.map((_, i) => new DoX(`H${i}`));
let H = new DoX('ROOT');
headRow.reduce((p, c) => addRight(p, c), H);
for (let i = 0; i < numCells; i++) {
const [ri, ci, bi] = getIndex(i);
g2D[i].forEach(num => {
let id = `${i}:${num}`;
let candIdx = num - 1;
// The 4 columns that we will populate.
const A = headRow[i];
const B = headRow[numCells + candIdx + (ri * U)];
const C = headRow[(numCells * 2) + candIdx + (ci * U)];
const D = headRow[(numCells * 3) + candIdx + (bi * U)];
// The Row-Column Constraint
let rcc = addBelow(A.U, new DoX(id, A));
// The Row-Number Constraint
let rnc = addBelow(B.U, addRight(rcc, new DoX(id, B)));
// The Column-Number Constraint
let cnc = addBelow(C.U, addRight(rnc, new DoX(id, C)));
// The Block-Number Constraint
addBelow(D.U, addRight(cnc, new DoX(id, D)));
});
}
search(H, []);
};
var stringPuzzle = "";
for (var i = 0; i < puzzle.length; i++) {
puzzle[i].forEach(function(e) {
if (e == -1)
stringPuzzle += ".";
else
stringPuzzle += e;
})
}
reduceGrid(stringPuzzle)
var result = [];
for (var i = 0; i < 9; i++) {
result.push(solution.slice(i * 9, (i + 1) * 9).map(e => parseInt(e)))
}
return result;
}
```
</details>

View File

@@ -0,0 +1,19 @@
---
title: Sum digits of an integer
---
# Sum digits of an integer
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function sumDigits(n) {
n += ''
for (var s=0, i=0, e=n.length; i<e; i+=1) s+=parseInt(n.charAt(i),36)
return s
}
```
</details>

View File

@@ -0,0 +1,21 @@
---
title: Sum multiples of 3 and 5
---
# Sum multiples of 3 and 5
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function sumMults(n) {
var sum = 0;
for (var i = 1; i < n; i++) {
if (i % 3 == 0 || i % 5 == 0) sum += i;
}
return sum;
}
```
</details>

View File

@@ -0,0 +1,22 @@
---
title: Sum of a series
---
# Sum of a series
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function sum(a, b) {
function fn(x) {
return 1 / (x * x)
}
var s = 0;
for (; a <= b; a++) s += fn(a);
return s;
}
```
</details>

View File

@@ -0,0 +1,23 @@
---
title: Sum of squares
---
# Sum of squares
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function sumsq(array) {
var sum = 0;
var i, iLen;
for (i = 0, iLen = array.length; i < iLen; i++) {
sum += array[i] * array[i];
}
return sum;
}
```
</details>

View File

@@ -0,0 +1,100 @@
---
title: Sum to 100
---
# Sum to 100
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function sumTo100(n) {
var permutationsWithRepetition = function(n, as) {
return as.length > 0 ?
foldl1(curry(cartesianProduct)(as), replicate(n, as)) : [];
};
var cartesianProduct = function(xs, ys) {
return [].concat.apply([], xs.map(function(x) {
return [].concat.apply([], ys.map(function(y) {
return [
[x].concat(y)
];
}));
}));
};
var curry = function(f) {
return function(a) {
return function(b) {
return f(a, b);
};
};
};
var flip = function(f) {
return function(a, b) {
return f.apply(null, [b, a]);
};
};
var foldl1 = function(f, xs) {
return xs.length > 0 ? xs.slice(1)
.reduce(f, xs[0]) : [];
};
var replicate = function(n, a) {
var v = [a],
o = [];
if (n < 1) return o;
while (n > 1) {
if (n & 1) o = o.concat(v);
n >>= 1;
v = v.concat(v);
}
return o.concat(v);
};
var asSum = function(xs) {
var dct = xs.reduceRight(function(a, sign, i) {
var d = i + 1; // zero-based index to [1-9] positions
if (sign !== 0) {
// Sum increased, digits cleared
return {
digits: [],
n: a.n + sign * parseInt([d].concat(a.digits)
.join(''), 10)
};
} else return { // Digits extended, sum unchanged
digits: [d].concat(a.digits),
n: a.n
};
}, {
digits: [],
n: 0
});
return dct.n + (
dct.digits.length > 0 ? parseInt(dct.digits.join(''), 10) : 0
);
};
var asString = function(xs) {
var ns = xs.reduce(function(a, sign, i) {
var d = (i + 1)
.toString();
return sign === 0 ? a + d : a + (sign > 0 ? '+' : '-') + d;
}, '');
return ns[0] === '+' ? tail(ns) : ns;
};
var universe = permutationsWithRepetition(9, [0, 1, -1])
.filter(function(x) {
return x[0] !== 1 && asSum(x) === n;
}).map(asString);
return universe.sort()
}
```
</details>

View File

@@ -0,0 +1,50 @@
---
title: Sutherland-Hodgman polygon clipping
---
# Sutherland-Hodgman polygon clipping
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function clip(subjectPolygon, clipPolygon) {
var cp1, cp2, s, e, i, j;
var inside = function(p) {
return (cp2[0] - cp1[0]) * (p[1] - cp1[1]) > (cp2[1] - cp1[1]) * (p[0] - cp1[0]);
};
var intersection = function() {
var dc = [cp1[0] - cp2[0], cp1[1] - cp2[1]],
dp = [s[0] - e[0], s[1] - e[1]],
n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0],
n2 = s[0] * e[1] - s[1] * e[0],
n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0]);
return [(n1 * dp[0] - n2 * dc[0]) * n3, (n1 * dp[1] - n2 * dc[1]) * n3];
};
var outputList = subjectPolygon;
cp1 = clipPolygon[clipPolygon.length - 1];
for (j in clipPolygon) {
var cp2 = clipPolygon[j];
var inputList = outputList;
outputList = [];
s = inputList[inputList.length - 1]; //last on the input list
for (i in inputList) {
var e = inputList[i];
if (inside(e)) {
if (!inside(s)) {
outputList.push(intersection());
}
outputList.push(e);
} else if (inside(s)) {
outputList.push(intersection());
}
s = e;
}
cp1 = cp2;
}
return outputList.map(e => e.map(f => Math.round(f * 1000) / 1000));
}
```
</details>

View File

@@ -0,0 +1,34 @@
---
title: Symmetric difference
---
# Symmetric difference
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function symmetricDifference(A, B) {
function relative_complement(A, B) {
return A.filter(function(elem) {
return B.indexOf(elem) == -1
});
}
function unique(ary) {
var u = ary.concat().sort();
for (var i = 1; i < u.length;) {
if (u[i - 1] === u[i])
u.splice(i, 1);
else
i++;
}
return u;
}
return unique(relative_complement(A, B).concat(relative_complement(B, A))).sort();
}
```
</details>

View File

@@ -3,8 +3,45 @@ title: Vector dot product
---
# Vector dot product
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/rosetta-code/vector-dot-product/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
---
## Solutions
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<details><summary>Solution 1 (Click to Show/Hide)</summary>
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
```javascript
function dotProduct(...vectors) {
if (!vectors || !vectors.length) {
return null;
}
if (!vectors[0] || !vectors[0].length) {
return null;
}
const vectorLen = vectors[0].length;
const numVectors = vectors.length;
// If all vectors not same length, return null
for (let i = 0; i < numVectors; i++) {
if (vectors[i].length !== vectorLen) {
return null; // return undefined
}
}
let prod = 0;
let sum = 0;
let j = vectorLen;
let i = numVectors;
// Sum terms
while (j--) {
i = numVectors;
prod = 1;
while (i--) {
prod *= vectors[i][j];
}
sum += prod;
}
return sum;
}
```
</details>