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:
@ -0,0 +1,50 @@
|
||||
---
|
||||
title: Check if Tree is Binary Search Tree
|
||||
---
|
||||
# Check if Tree is Binary Search Tree
|
||||
|
||||
---
|
||||
## Solutions
|
||||
|
||||
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
||||
|
||||
```javascript
|
||||
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
|
||||
function Node(value) {
|
||||
this.value = value;
|
||||
this.left = null;
|
||||
this.right = null;
|
||||
}
|
||||
function BinarySearchTree() {
|
||||
this.root = null;
|
||||
}
|
||||
function isBinarySearchTree(tree) {
|
||||
if (tree.root == null) {
|
||||
return null;
|
||||
} else {
|
||||
let isBST = true;
|
||||
function checkTree(node) {
|
||||
if (node.left != null) {
|
||||
const left = node.left;
|
||||
if (left.value > node.value) {
|
||||
isBST = false;
|
||||
} else {
|
||||
checkTree(left);
|
||||
}
|
||||
}
|
||||
if (node.right != null) {
|
||||
const right = node.right;
|
||||
if (right.value < node.value) {
|
||||
isBST = false;
|
||||
} else {
|
||||
checkTree(right);
|
||||
}
|
||||
}
|
||||
}
|
||||
checkTree(tree.root);
|
||||
return isBST;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
</details>
|
@ -1,5 +1,5 @@
|
||||
---
|
||||
title: Multiples of 3 and 5
|
||||
title: 'Problem 1: Multiples of 3 and 5'
|
||||
---
|
||||
# Problem 1: Multiples of 3 and 5
|
||||
|
||||
|
@ -1,5 +1,5 @@
|
||||
---
|
||||
title: Summation of primes
|
||||
title: 'Problem 10: Summation of primes'
|
||||
---
|
||||
# Problem 10: Summation of primes
|
||||
|
||||
|
@ -1,9 +1,9 @@
|
||||
---
|
||||
title: Solving the diophantine equation 1/a+1/b= p/10n
|
||||
title: 'Problem 152: Writing half as a sum of inverse squares'
|
||||
---
|
||||
## Problem 157: Solving the diophantine equation 1/a+1/b= p/10n
|
||||
## Problem 152: Writing one half as a sum of inverse squares
|
||||
|
||||
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/project-euler/problem-157-solving-the-diophantine-equation-1a1b-p10n/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
|
||||
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/project-euler/problem-152-writing-one-half-as-a-sum-of-inverse-squares/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>.
|
||||
|
@ -1,9 +1,9 @@
|
||||
---
|
||||
title: Writing 1/2 as a sum of inverse squares
|
||||
title: 'Problem 157: Solving the diophantine equation'
|
||||
---
|
||||
## Problem 152: Writing 1/2 as a sum of inverse squares
|
||||
## Problem 157: Solving the diophantine equation
|
||||
|
||||
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/project-euler/problem-152-writing-12-as-a-sum-of-inverse-squares/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
|
||||
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/project-euler/problem-157-solving-the-diophantine-equation/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>.
|
||||
|
@ -1,5 +1,5 @@
|
||||
---
|
||||
title: Even Fibonacci Numbers
|
||||
title: 'Problem 2: Even Fibonacci Numbers'
|
||||
---
|
||||
# Problem 2: Even Fibonacci Numbers
|
||||
|
||||
|
@ -1,9 +1,9 @@
|
||||
---
|
||||
title: Integer sided triangles for which the area/perimeter ratio is integral
|
||||
title: 'Problem 283: Integer sided triangles for which the area * perimeter ratio is integral'
|
||||
---
|
||||
## Problem 283: Integer sided triangles for which the area/perimeter ratio is integral
|
||||
## Problem 283: Integer sided triangles for which the area * perimeter ratio is integral
|
||||
|
||||
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/project-euler/problem-283-integer-sided-triangles-for-which-the--areaperimeter-ratio-is-integral/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
|
||||
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/project-euler/problem-283-integer-sided-triangles-for-which-the--area-perimeter-ratio-is-integral/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>.
|
||||
|
@ -1,5 +1,5 @@
|
||||
---
|
||||
title: Largest prime factor
|
||||
title: 'Problem 3: Largest prime factor'
|
||||
---
|
||||
# Problem 3: Largest prime factor
|
||||
|
||||
|
@ -1,5 +1,5 @@
|
||||
---
|
||||
title: Largest palindrome product
|
||||
title: 'Problem 4: Largest palindrome product'
|
||||
---
|
||||
# Problem 4: Largest palindrome product
|
||||
|
||||
|
@ -1,5 +1,5 @@
|
||||
---
|
||||
title: 10001st prime
|
||||
title: 'Problem 7: 10001st prime'
|
||||
---
|
||||
# Problem 7: 10001st prime
|
||||
|
||||
|
@ -1,5 +1,5 @@
|
||||
---
|
||||
title: Largest product in a series
|
||||
title: 'Problem 8: Largest product in a series'
|
||||
---
|
||||
# Problem 8: Largest product in a series
|
||||
|
||||
|
@ -1,5 +1,5 @@
|
||||
---
|
||||
title: Special Pythagorean triplet
|
||||
title: 'Problem 9: Special Pythagorean triplet'
|
||||
---
|
||||
# Problem 9: Special Pythagorean triplet
|
||||
|
||||
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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 -->
|
@ -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 -->
|
@ -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 -->
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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>
|
||||
|
@ -6,9 +6,9 @@ title: Use the Twitch JSON API
|
||||
|
||||
---
|
||||
## Problem Explanation
|
||||
Update September 29, 2016: Twitch has changed their API and now requires an API key in order to run queries. If you are using CodePen or GitHub pages to build these, we do not recommend adding an API key to your project for security reasons.
|
||||
Update December 28, 2018: Twitch has updated their API a few times since we wrote this. [The latest version of their API is here](https://dev.twitch.tv/docs/api/reference/#get-streams).
|
||||
|
||||
Instead of using Twitch's API, we recommend hard-coding <a href='https://gist.github.com/QuincyLarson/2ff6892f948d0b7118a99264fd9c1ce8' target='_blank' rel='nofollow'>this JSON</a> into your app as a variable. It is a series of responses for different accounts from Twitch.
|
||||
Due to a change in conditions on API usage, Twitch.tv requires an API key, but we've built a workaround. Use <a href='https://wind-bow.glitch.me' target='_blank'>https://wind-bow.glitch.me/helix</a> instead of twitch's API base URL (i.e. https://api.twitch.tv/helix ) and you'll still be able to get account information, without needing to sign up for an API key.
|
||||
|
||||
* * *
|
||||
|
||||
|
@ -3,8 +3,28 @@ title: Get Geolocation Data to Find A User's GPS Coordinates
|
||||
---
|
||||
# Get Geolocation Data to Find A User's GPS Coordinates
|
||||
|
||||
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/data-visualization/json-apis-and-ajax/get-geolocation-data-to-find-a-users-gps-coordinates/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
|
||||
--
|
||||
## Hints
|
||||
|
||||
<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>.
|
||||
### Hint 1
|
||||
Every browser has a built in navigator that can give us this information.
|
||||
|
||||
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
|
||||
The navigator will get our user's current longitude and latitude.
|
||||
|
||||
You will see a prompt to allow or block this site from knowing your current location. The challenge can be completed either way, as long as the code is correct.
|
||||
|
||||
By selecting allow you will see the text on the output phone change to your latitude and longitude
|
||||
|
||||
Here's some code that does this:
|
||||
|
||||
```javascript
|
||||
if (navigator.geolocation) {
|
||||
|
||||
navigator.geolocation.getCurrentPosition(function(position) {
|
||||
|
||||
$("#data").html("latitude: " + position.coords.latitude + "<br>longitude: " + position.coords.longitude);
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
```
|
||||
|
@ -0,0 +1,60 @@
|
||||
---
|
||||
title: Get JSON with the JavaScript fetch method
|
||||
---
|
||||
# Get JSON with the JavaScript fetch method
|
||||
|
||||
---
|
||||
## Solutions
|
||||
|
||||
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
||||
|
||||
```html
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded',function(){
|
||||
document.getElementById('getMessage').onclick= () => {
|
||||
fetch('/json/cats.json')
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
document.getElementById('message').innerHTML=JSON.stringify(data);
|
||||
})
|
||||
};
|
||||
});
|
||||
</script>
|
||||
<style>
|
||||
body {
|
||||
text-align: center;
|
||||
font-family: "Helvetica", sans-serif;
|
||||
}
|
||||
h1 {
|
||||
font-size: 2em;
|
||||
font-weight: bold;
|
||||
}
|
||||
.box {
|
||||
border-radius: 5px;
|
||||
background-color: #eee;
|
||||
padding: 20px 5px;
|
||||
}
|
||||
button {
|
||||
color: white;
|
||||
background-color: #4791d0;
|
||||
border-radius: 5px;
|
||||
border: 1px solid #4791d0;
|
||||
padding: 5px 10px 8px 10px;
|
||||
}
|
||||
button:hover {
|
||||
background-color: #0F5897;
|
||||
border: 1px solid #0F5897;
|
||||
}
|
||||
</style>
|
||||
<h1>Cat Photo Finder</h1>
|
||||
<p id="message">
|
||||
The message will go here
|
||||
</p>
|
||||
<p>
|
||||
<button id="getMessage">
|
||||
Get Message
|
||||
</button>
|
||||
</p>
|
||||
```
|
||||
|
||||
</details>
|
@ -3,8 +3,74 @@ title: Pre-filter JSON to Get the Data You Need
|
||||
---
|
||||
# Pre-filter JSON to Get the Data You Need
|
||||
|
||||
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/data-visualization/json-apis-and-ajax/pre-filter-json-to-get-the-data-you-need/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 -->
|
||||
```html
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded',function(){
|
||||
document.getElementById('getMessage').onclick=function(){
|
||||
req=new XMLHttpRequest();
|
||||
req.open("GET",'/json/cats.json',true);
|
||||
req.send();
|
||||
req.onload=function(){
|
||||
json=JSON.parse(req.responseText);
|
||||
var html = "";
|
||||
// Add your code below this line
|
||||
|
||||
json = json.filter(function(val) {
|
||||
return (val.id !== 1);
|
||||
});
|
||||
// Add your code above this line
|
||||
json.forEach(function(val) {
|
||||
html += "<div class = 'cat'>"
|
||||
|
||||
html += "<img src = '" + val.imageLink + "' " + "alt='" + val.altText + "'>"
|
||||
|
||||
html += "</div>"
|
||||
});
|
||||
document.getElementsByClassName('message')[0].innerHTML=html;
|
||||
};
|
||||
};
|
||||
});
|
||||
</script>
|
||||
<style>
|
||||
body {
|
||||
text-align: center;
|
||||
font-family: "Helvetica", sans-serif;
|
||||
}
|
||||
h1 {
|
||||
font-size: 2em;
|
||||
font-weight: bold;
|
||||
}
|
||||
.box {
|
||||
border-radius: 5px;
|
||||
background-color: #eee;
|
||||
padding: 20px 5px;
|
||||
}
|
||||
button {
|
||||
color: white;
|
||||
background-color: #4791d0;
|
||||
border-radius: 5px;
|
||||
border: 1px solid #4791d0;
|
||||
padding: 5px 10px 8px 10px;
|
||||
}
|
||||
button:hover {
|
||||
background-color: #0F5897;
|
||||
border: 1px solid #0F5897;
|
||||
}
|
||||
</style>
|
||||
<h1>Cat Photo Finder</h1>
|
||||
<p class="message box">
|
||||
The message will go here
|
||||
</p>
|
||||
<p>
|
||||
<button id="getMessage">
|
||||
Get Message
|
||||
</button>
|
||||
</p>
|
||||
```
|
||||
|
||||
</details>
|
@ -3,8 +3,72 @@ title: Warn Your Users of a Dangerous Action with btn-danger
|
||||
---
|
||||
# Warn Your Users of a Dangerous Action with btn-danger
|
||||
|
||||
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/front-end-libraries/bootstrap/warn-your-users-of-a-dangerous-action-with-btn-danger/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
|
||||
## Problem Explanation
|
||||
The `btn-danger` class is the button color you'll use to notify users that the button performs a destructive action, such as deleting a cat photo. Note that these buttons still need the `btn` and `btn-block` classes.
|
||||
|
||||
<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 -->
|
||||
```html
|
||||
<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css">
|
||||
<style>
|
||||
.red-text {
|
||||
color: red;
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-family: Lobster, Monospace;
|
||||
}
|
||||
|
||||
p {
|
||||
font-size: 16px;
|
||||
font-family: Monospace;
|
||||
}
|
||||
|
||||
.thick-green-border {
|
||||
border-color: green;
|
||||
border-width: 10px;
|
||||
border-style: solid;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.smaller-image {
|
||||
width: 100px;
|
||||
}
|
||||
</style>
|
||||
|
||||
<div class="container-fluid">
|
||||
<h2 class="red-text text-center">CatPhotoApp</h2>
|
||||
|
||||
<p>Click here for <a href="#">cat photos</a>.</p>
|
||||
|
||||
<a href="#"><img class="smaller-image thick-green-border" src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a>
|
||||
|
||||
<img src="https://bit.ly/fcc-running-cats" class="img-responsive" alt="Three kittens running towards the camera.">
|
||||
<button class="btn btn-block btn-primary">Like</button>
|
||||
<button class="btn btn-block btn-info">Info</button>
|
||||
<button class="btn btn-block btn-danger">Delete</button>
|
||||
<p>Things cats love:</p>
|
||||
<ul>
|
||||
<li>cat nip</li>
|
||||
<li>laser pointers</li>
|
||||
<li>lasagna</li>
|
||||
</ul>
|
||||
<p>Top 3 things cats hate:</p>
|
||||
<ol>
|
||||
<li>flea treatment</li>
|
||||
<li>thunder</li>
|
||||
<li>other cats</li>
|
||||
</ol>
|
||||
<form action="/submit-cat-photo">
|
||||
<label><input type="radio" name="indoor-outdoor"> Indoor</label>
|
||||
<label><input type="radio" name="indoor-outdoor"> Outdoor</label>
|
||||
<label><input type="checkbox" name="personality"> Loving</label>
|
||||
<label><input type="checkbox" name="personality"> Lazy</label>
|
||||
<label><input type="checkbox" name="personality"> Crazy</label>
|
||||
<input type="text" placeholder="cat photo URL" required>
|
||||
<button type="submit">Submit</button>
|
||||
</form>
|
||||
</div>
|
||||
```
|
||||
|
||||
</details>
|
||||
|
@ -3,8 +3,65 @@ title: Target Even Elements Using jQuery
|
||||
---
|
||||
# Target Even Elements Using jQuery
|
||||
|
||||
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/front-end-libraries/jquery/target-even-elements-using-jquery/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
|
||||
## Hints
|
||||
|
||||
<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>.
|
||||
### Hint # 1
|
||||
Here's how you would target all the `odd-numbered` elements with class target and give them classes:
|
||||
|
||||
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
|
||||
```javascript
|
||||
$('.target:odd').addClass('animated shake');
|
||||
```
|
||||
|
||||
This will shake all the even ones:
|
||||
|
||||
```javascript
|
||||
$('.target:even').addClass("shake");
|
||||
```
|
||||
The right way to do it would be $ `("button: even")` ...
|
||||
|
||||
## Solutions
|
||||
|
||||
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
||||
|
||||
```html
|
||||
<script>
|
||||
$(document).ready(function() {
|
||||
$("#target1").css("color", "red");
|
||||
$("#target1").prop("disabled", true);
|
||||
$("#target4").remove();
|
||||
$("#target2").appendTo("#right-well");
|
||||
$("#target5").clone().appendTo("#left-well");
|
||||
$("#target1").parent().css("background-color", "red");
|
||||
$("#right-well").children().css("color", "orange");
|
||||
$("#left-well").children().css("color", "green");
|
||||
$(".target:nth-child(2)").addClass("animated bounce");
|
||||
$(".target:even").addClass("animated shake");
|
||||
});
|
||||
</script>
|
||||
|
||||
<!-- Only change code above this line. -->
|
||||
|
||||
<div class="container-fluid">
|
||||
<h3 class="text-primary text-center">jQuery Playground</h3>
|
||||
<div class="row">
|
||||
<div class="col-xs-6">
|
||||
<h4>#left-well</h4>
|
||||
<div class="well" id="left-well">
|
||||
<button class="btn btn-default target" id="target1">#target1</button>
|
||||
<button class="btn btn-default target" id="target2">#target2</button>
|
||||
<button class="btn btn-default target" id="target3">#target3</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-xs-6">
|
||||
<h4>#right-well</h4>
|
||||
<div class="well" id="right-well">
|
||||
<button class="btn btn-default target" id="target4">#target4</button>
|
||||
<button class="btn btn-default target" id="target5">#target5</button>
|
||||
<button class="btn btn-default target" id="target6">#target6</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
</details>
|
||||
|
@ -0,0 +1,45 @@
|
||||
---
|
||||
title: Render with an If-Else Condition
|
||||
---
|
||||
# Render with an If-Else Condition
|
||||
|
||||
---
|
||||
## Solutions
|
||||
|
||||
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
||||
|
||||
```jsx
|
||||
class MyComponent extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
display: true
|
||||
}
|
||||
this.toggleDisplay = this.toggleDisplay.bind(this);
|
||||
}
|
||||
toggleDisplay() {
|
||||
this.setState({
|
||||
display: !this.state.display
|
||||
});
|
||||
}
|
||||
render() {
|
||||
// change code below this line
|
||||
if (this.state.display) {
|
||||
return (
|
||||
<div>
|
||||
<button onClick={this.toggleDisplay}>Toggle Display</button>
|
||||
<h1>Displayed!</h1>
|
||||
</div>
|
||||
);
|
||||
} else {
|
||||
return (
|
||||
<div>
|
||||
<button onClick={this.toggleDisplay}>Toggle Display</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
</details>
|
@ -17,7 +17,7 @@ JavaScript uses the `/` symbol for division.
|
||||
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
||||
|
||||
```javascript
|
||||
var quotient = 0.6 / 0.3; //quotient gets the value 2
|
||||
var quotient = 4.4 / 2.0; // Fix this line
|
||||
```
|
||||
</details>
|
||||
|
||||
|
@ -0,0 +1,25 @@
|
||||
---
|
||||
title: Use Recursion to Create a Range of Numbers
|
||||
---
|
||||
|
||||
# Use Recursion to Create a Range of Numbers
|
||||
|
||||
|
||||
---
|
||||
## Solutions
|
||||
|
||||
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
||||
|
||||
```javascript
|
||||
function rangeOfNumbers(startNum, endNum) {
|
||||
if (endNum - startNum === 0) {
|
||||
return [startNum];
|
||||
} else {
|
||||
var numbers = rangeOfNumbers(startNum, endNum - 1);
|
||||
numbers.push(endNum);
|
||||
return numbers;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
@ -0,0 +1,25 @@
|
||||
---
|
||||
title: Complete a Promise with resolve and reject
|
||||
---
|
||||
|
||||
# Complete a Promise with resolve and reject
|
||||
|
||||
---
|
||||
## Solutions
|
||||
|
||||
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
||||
|
||||
```javascript
|
||||
const makeServerRequest = new Promise((resolve, reject) => {
|
||||
// responseFromServer represents a response from a server
|
||||
let responseFromServer;
|
||||
|
||||
if(responseFromServer) {
|
||||
resolve("We got the data");
|
||||
} else {
|
||||
reject("Data not received");
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
</details>
|
@ -0,0 +1,17 @@
|
||||
---
|
||||
title: Create a JavaScript Promise
|
||||
---
|
||||
# Create a JavaScript Promise
|
||||
|
||||
---
|
||||
## Solutions
|
||||
|
||||
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
||||
|
||||
```javascript
|
||||
const makeServerRequest = new Promise((resolve, reject) => {
|
||||
|
||||
});
|
||||
```
|
||||
|
||||
</details>
|
@ -0,0 +1,21 @@
|
||||
---
|
||||
title: Create a Module Script
|
||||
---
|
||||
# Create a Module Script
|
||||
|
||||
---
|
||||
## Solutions
|
||||
|
||||
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
||||
|
||||
```html
|
||||
<html>
|
||||
<body>
|
||||
<!-- add your code below -->
|
||||
<script type="module" src="index.js"></script>
|
||||
<!-- add your code above -->
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
</details>
|
@ -0,0 +1,28 @@
|
||||
---
|
||||
title: Handle a Fulfilled Promise with then
|
||||
---
|
||||
# Handle a Fulfilled Promise with then
|
||||
|
||||
---
|
||||
## Solutions
|
||||
|
||||
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
||||
|
||||
```javascript
|
||||
const makeServerRequest = new Promise((resolve, reject) => {
|
||||
// responseFromServer is set to true to represent a successful response from a server
|
||||
let responseFromServer = true;
|
||||
|
||||
if(responseFromServer) {
|
||||
resolve("We got the data");
|
||||
} else {
|
||||
reject("Data not received");
|
||||
}
|
||||
});
|
||||
|
||||
makeServerRequest.then(result => {
|
||||
console.log(result);
|
||||
});
|
||||
```
|
||||
|
||||
</details>
|
@ -0,0 +1,32 @@
|
||||
---
|
||||
title: Handle a Rejected Promise with catch
|
||||
---
|
||||
# Handle a Rejected Promise with catch
|
||||
|
||||
---
|
||||
## Solutions
|
||||
|
||||
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
||||
|
||||
```javascript
|
||||
const makeServerRequest = new Promise((resolve, reject) => {
|
||||
// responseFromServer is set to false to represent an unsuccessful response from a server
|
||||
let responseFromServer = false;
|
||||
|
||||
if(responseFromServer) {
|
||||
resolve("We got the data");
|
||||
} else {
|
||||
reject("Data not received");
|
||||
}
|
||||
});
|
||||
|
||||
makeServerRequest.then(result => {
|
||||
console.log(result);
|
||||
});
|
||||
|
||||
makeServerRequest.catch(error => {
|
||||
console.log(error);
|
||||
});
|
||||
```
|
||||
|
||||
</details>
|
@ -0,0 +1,19 @@
|
||||
---
|
||||
title: Reuse Javascript Code Using import
|
||||
---
|
||||
# Reuse Javascript Code Using import
|
||||
|
||||
---
|
||||
## Solutions
|
||||
|
||||
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
||||
|
||||
```javascript
|
||||
import { uppercaseString, lowercaseString } from './string_functions.js';
|
||||
// add code above this line
|
||||
|
||||
uppercaseString("hello");
|
||||
lowercaseString("WORLD!");
|
||||
```
|
||||
|
||||
</details>
|
@ -4,9 +4,26 @@ title: Use Destructuring Assignment to Assign Variables from Objects
|
||||
|
||||
# Use Destructuring Assignment to Assign Variables from Objects
|
||||
|
||||
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/quadratic-equations/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>
|
||||
|
||||
#### More Information:
|
||||
<!-- Please add any articles you think might be helpful to read before writing the article -->
|
||||
```javascript
|
||||
const HIGH_TEMPERATURES = {
|
||||
yesterday: 75,
|
||||
today: 77,
|
||||
tomorrow: 80
|
||||
};
|
||||
|
||||
// change code below this line
|
||||
|
||||
const { today: highToday, tomorrow: highTomorrow } = HIGH_TEMPERATURES;
|
||||
|
||||
// change code above this line
|
||||
|
||||
console.log(highToday); // should be 77
|
||||
console.log(highTomorrow); // should be 80
|
||||
```
|
||||
|
||||
</details>
|
@ -0,0 +1,29 @@
|
||||
---
|
||||
title: Use Destructuring Assignment to Extract Values from Objects
|
||||
---
|
||||
# Use Destructuring Assignment to Extract Values from Objects
|
||||
|
||||
---
|
||||
## Solutions
|
||||
|
||||
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
||||
|
||||
```javascript
|
||||
const HIGH_TEMPERATURES = {
|
||||
yesterday: 75,
|
||||
today: 77,
|
||||
tomorrow: 80
|
||||
};
|
||||
|
||||
// change code below this line
|
||||
|
||||
const { today, tomorrow } = HIGH_TEMPERATURES;
|
||||
|
||||
// change code above this line
|
||||
|
||||
console.log(yesterday) // should be not defined
|
||||
console.log(today); // should be 77
|
||||
console.log(tomorrow); // should be 80
|
||||
```
|
||||
|
||||
</details>
|
@ -0,0 +1,21 @@
|
||||
---
|
||||
title: Use export to Share a Code Block
|
||||
---
|
||||
# Use export to Share a Code Block
|
||||
|
||||
---
|
||||
## Solutions
|
||||
|
||||
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
||||
|
||||
```javascript
|
||||
export const uppercaseString = (string) => {
|
||||
return string.toUpperCase();
|
||||
}
|
||||
|
||||
export const lowercaseString = (string) => {
|
||||
return string.toLowerCase()
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
@ -1,7 +1,7 @@
|
||||
---
|
||||
title: Write Concise Object Literal Declarations Using Simple Fields
|
||||
title: Write Concise Object Literal Declarations Using Object Property Shorthand
|
||||
---
|
||||
# Write Concise Object Literal Declarations Using Simple Fields
|
||||
# Write Concise Object Literal Declarations Using Object Property Shorthand
|
||||
|
||||
---
|
||||
## Problem Explanation
|
@ -17,10 +17,10 @@ Use the `join` method (among others) inside the `sentensify` function to make a
|
||||
---
|
||||
## Hints
|
||||
|
||||
### Hint1
|
||||
### Hint 1
|
||||
You may need to convert the string to an array first.
|
||||
|
||||
### Hint2
|
||||
### Hint 2
|
||||
You may need to use regular expression to split the string.
|
||||
|
||||
|
||||
|
@ -1,56 +0,0 @@
|
||||
---
|
||||
title: Cascading CSS Variables
|
||||
---
|
||||
# Cascading CSS Variables
|
||||
|
||||
---
|
||||
## Problem Explanation
|
||||
Cascading CSS variables (officially called custom properties) are entities which behave similarly to traditional variables, in that variables allow for data to be stored and updated to reflect new values later<sup>2</sup>.
|
||||
|
||||
CSS variables are defined to contain specific values and be reused throughout a document. They are set using custom property notation (e.g., `--main-color: black`) and are accessed using the `var()` function (e.g., `color: var(--main-color)`)<sup>1</sup>. Declare the CSS variable in the `:root` or `body` selectors for global access.
|
||||
|
||||
When maintaining complex CSS documents, it is not only beneficial to use CSS Variables but also smart. When making future updates instead of searching potential hundreds of lines of code, one only needs to update the necessary CSS variable<sup>1</sup>.
|
||||
|
||||
|
||||
**Example Syntax:**
|
||||
|
||||
```css
|
||||
:root {
|
||||
--main-bkgnd-color: #00B8CB;
|
||||
}
|
||||
|
||||
body {
|
||||
background-color: var(--main-bkgnd-color);
|
||||
font-family: 'Raleway', Helvetica, sans-serif;
|
||||
}
|
||||
```
|
||||
Declaring the variable:
|
||||
```css
|
||||
--custom-name: value
|
||||
```
|
||||
|
||||
Using the variable:
|
||||
```css
|
||||
var(--custom-name)
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
## Solutions
|
||||
|
||||
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
||||
|
||||
|
||||
In the ```:root``` selector we need to declare the ```--penguin-belly``` variable and give it the value of ```pink```:
|
||||
|
||||
```css
|
||||
:root {
|
||||
--penguin-belly: pink;
|
||||
}
|
||||
```
|
||||
|
||||
#### Relevant Links
|
||||
|
||||
1. [Visit MDN's Cascading CSS Variables page for more information.](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables)
|
||||
2. [Perna, Maria Antonietta. "A Practical Guide to CSS Variables (Custom Properties)" *sitepoint*. August 01, 2018. Accessed: October 5, 2018](https://www.sitepoint.com/practical-guide-css-variables-custom-properties/)
|
||||
</details>
|
@ -0,0 +1,252 @@
|
||||
---
|
||||
title: Cascading CSS Variables
|
||||
---
|
||||
# Cascading CSS Variables
|
||||
|
||||
---
|
||||
## Problem Explanation
|
||||
Cascading CSS variables (officially called custom properties) are entities which behave similarly to traditional variables, in that variables allow for data to be stored and updated to reflect new values later<sup>2</sup>.
|
||||
|
||||
CSS variables are defined to contain specific values and be reused throughout a document. They are set using custom property notation (e.g., `--main-color: black`) and are accessed using the `var()` function (e.g., `color: var(--main-color)`)<sup>1</sup>. Declare the CSS variable in the `:root` or `body` selectors for global access.
|
||||
|
||||
When maintaining complex CSS documents, it is not only beneficial to use CSS Variables but also smart. When making future updates instead of searching potential hundreds of lines of code, one only needs to update the necessary CSS variable<sup>1</sup>.
|
||||
|
||||
|
||||
**Example Syntax:**
|
||||
|
||||
```css
|
||||
:root {
|
||||
--main-bkgnd-color: #00B8CB;
|
||||
}
|
||||
|
||||
body {
|
||||
background-color: var(--main-bkgnd-color);
|
||||
font-family: 'Raleway', Helvetica, sans-serif;
|
||||
}
|
||||
```
|
||||
Declaring the variable:
|
||||
```css
|
||||
--custom-name: value
|
||||
```
|
||||
|
||||
Using the variable:
|
||||
```css
|
||||
var(--custom-name)
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
## Solutions
|
||||
|
||||
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
||||
|
||||
|
||||
In the ```:root``` selector we need to declare the ```--penguin-belly``` variable and give it the value of ```pink```:
|
||||
|
||||
```html
|
||||
<style>
|
||||
:root {
|
||||
--penguin-belly: pink;
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--penguin-belly, #c6faf1);
|
||||
}
|
||||
|
||||
.penguin {
|
||||
--penguin-skin: gray;
|
||||
--penguin-beak: orange;
|
||||
position: relative;
|
||||
margin: auto;
|
||||
display: block;
|
||||
margin-top: 5%;
|
||||
width: 300px;
|
||||
height: 300px;
|
||||
}
|
||||
|
||||
.right-cheek {
|
||||
top: 15%;
|
||||
left: 35%;
|
||||
background: var(--penguin-belly, white);
|
||||
width: 60%;
|
||||
height: 70%;
|
||||
border-radius: 70% 70% 60% 60%;
|
||||
}
|
||||
|
||||
.left-cheek {
|
||||
top: 15%;
|
||||
left: 5%;
|
||||
background: var(--penguin-belly, white);
|
||||
width: 60%;
|
||||
height: 70%;
|
||||
border-radius: 70% 70% 60% 60%;
|
||||
}
|
||||
|
||||
.belly {
|
||||
top: 60%;
|
||||
left: 2.5%;
|
||||
background: var(--penguin-belly, white);
|
||||
width: 95%;
|
||||
height: 100%;
|
||||
border-radius: 120% 120% 100% 100%;
|
||||
}
|
||||
|
||||
.penguin-top {
|
||||
top: 10%;
|
||||
left: 25%;
|
||||
background: var(--penguin-skin, gray);
|
||||
width: 50%;
|
||||
height: 45%;
|
||||
border-radius: 70% 70% 60% 60%;
|
||||
}
|
||||
|
||||
.penguin-bottom {
|
||||
top: 40%;
|
||||
left: 23.5%;
|
||||
background: var(--penguin-skin, gray);
|
||||
width: 53%;
|
||||
height: 45%;
|
||||
border-radius: 70% 70% 100% 100%;
|
||||
}
|
||||
|
||||
.right-hand {
|
||||
top: 0%;
|
||||
left: -5%;
|
||||
background: var(--penguin-skin, gray);
|
||||
width: 30%;
|
||||
height: 60%;
|
||||
border-radius: 30% 30% 120% 30%;
|
||||
transform: rotate(45deg);
|
||||
z-index: -1;
|
||||
}
|
||||
|
||||
.left-hand {
|
||||
top: 0%;
|
||||
left: 75%;
|
||||
background: var(--penguin-skin, gray);
|
||||
width: 30%;
|
||||
height: 60%;
|
||||
border-radius: 30% 30% 30% 120%;
|
||||
transform: rotate(-45deg);
|
||||
z-index: -1;
|
||||
}
|
||||
|
||||
.right-feet {
|
||||
top: 85%;
|
||||
left: 60%;
|
||||
background: var(--penguin-beak, orange);
|
||||
width: 15%;
|
||||
height: 30%;
|
||||
border-radius: 50% 50% 50% 50%;
|
||||
transform: rotate(-80deg);
|
||||
z-index: -2222;
|
||||
}
|
||||
|
||||
.left-feet {
|
||||
top: 85%;
|
||||
left: 25%;
|
||||
background: var(--penguin-beak, orange);
|
||||
width: 15%;
|
||||
height: 30%;
|
||||
border-radius: 50% 50% 50% 50%;
|
||||
transform: rotate(80deg);
|
||||
z-index: -2222;
|
||||
}
|
||||
|
||||
.right-eye {
|
||||
top: 45%;
|
||||
left: 60%;
|
||||
background: black;
|
||||
width: 15%;
|
||||
height: 17%;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.left-eye {
|
||||
top: 45%;
|
||||
left: 25%;
|
||||
background: black;
|
||||
width: 15%;
|
||||
height: 17%;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.sparkle {
|
||||
top: 25%;
|
||||
left: 15%;
|
||||
background: white;
|
||||
width: 35%;
|
||||
height: 35%;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.blush-right {
|
||||
top: 65%;
|
||||
left: 15%;
|
||||
background: pink;
|
||||
width: 15%;
|
||||
height: 10%;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.blush-left {
|
||||
top: 65%;
|
||||
left: 70%;
|
||||
background: pink;
|
||||
width: 15%;
|
||||
height: 10%;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.beak-top {
|
||||
top: 60%;
|
||||
left: 40%;
|
||||
background: var(--penguin-beak, orange);
|
||||
width: 20%;
|
||||
height: 10%;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.beak-bottom {
|
||||
top: 65%;
|
||||
left: 42%;
|
||||
background: var(--penguin-beak, orange);
|
||||
width: 16%;
|
||||
height: 10%;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.penguin * {
|
||||
position: absolute;
|
||||
}
|
||||
</style>
|
||||
<div class="penguin">
|
||||
<div class="penguin-bottom">
|
||||
<div class="right-hand"></div>
|
||||
<div class="left-hand"></div>
|
||||
<div class="right-feet"></div>
|
||||
<div class="left-feet"></div>
|
||||
</div>
|
||||
<div class="penguin-top">
|
||||
<div class="right-cheek"></div>
|
||||
<div class="left-cheek"></div>
|
||||
<div class="belly"></div>
|
||||
<div class="right-eye">
|
||||
<div class="sparkle"></div>
|
||||
</div>
|
||||
<div class="left-eye">
|
||||
<div class="sparkle"></div>
|
||||
</div>
|
||||
<div class="blush-right"></div>
|
||||
<div class="blush-left"></div>
|
||||
<div class="beak-top"></div>
|
||||
<div class="beak-bottom"></div>
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
#### Relevant Links
|
||||
|
||||
1. [Visit MDN's Cascading CSS Variables page for more information.](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables)
|
||||
2. [Perna, Maria Antonietta. "A Practical Guide to CSS Variables (Custom Properties)" *sitepoint*. August 01, 2018. Accessed: October 5, 2018](https://www.sitepoint.com/practical-guide-css-variables-custom-properties/)
|
||||
</details>
|
Reference in New Issue
Block a user