chore: import upstream snapshot with attribution
i18n - Build Validation / Validate i18n Builds (24) (push) Has been cancelled
CI - Node.js / Lint (24) (push) Has been cancelled
CI - Node.js / Build (24) (push) Has been cancelled
CI - Node.js / Test (24) (push) Has been cancelled
CI - Node.js / Test - Upcoming Changes (24) (push) Has been cancelled
CI - Node.js / Test - i18n (italian, 24) (push) Has been cancelled
CI - Node.js / Test - i18n (portuguese, 24) (push) Has been cancelled
CD - Docker - GHCR Images / Build and Push Images (push) Has been cancelled
i18n - Build Validation / Validate i18n Builds (24) (push) Has been cancelled
CI - Node.js / Lint (24) (push) Has been cancelled
CI - Node.js / Build (24) (push) Has been cancelled
CI - Node.js / Test (24) (push) Has been cancelled
CI - Node.js / Test - Upcoming Changes (24) (push) Has been cancelled
CI - Node.js / Test - i18n (italian, 24) (push) Has been cancelled
CI - Node.js / Test - i18n (portuguese, 24) (push) Has been cancelled
CD - Docker - GHCR Images / Build and Push Images (push) Has been cancelled
This commit is contained in:
+90
@@ -0,0 +1,90 @@
|
||||
---
|
||||
id: 6814d8e1516e86b171929de4
|
||||
title: "Challenge 1: Vowel Balance"
|
||||
challengeType: 28
|
||||
dashedName: challenge-1
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string, determine whether the number of vowels in the first half of the string is equal to the number of vowels in the second half.
|
||||
|
||||
- The string can contain any characters.
|
||||
- The letters `a`, `e`, `i`, `o`, and `u`, in either uppercase or lowercase, are considered vowels.
|
||||
- If there's an odd number of characters in the string, ignore the center character.
|
||||
|
||||
# --hints--
|
||||
|
||||
`isBalanced("racecar")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isBalanced("racecar"));
|
||||
```
|
||||
|
||||
`isBalanced("Lorem Ipsum")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isBalanced("Lorem Ipsum"));
|
||||
```
|
||||
|
||||
`isBalanced("Kitty Ipsum")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isBalanced("Kitty Ipsum"));
|
||||
```
|
||||
|
||||
`isBalanced("string")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isBalanced("string"));
|
||||
```
|
||||
|
||||
`isBalanced(" ")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isBalanced(" "));
|
||||
```
|
||||
|
||||
`isBalanced("abcdefghijklmnopqrstuvwxyz")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isBalanced("abcdefghijklmnopqrstuvwxyz"));
|
||||
```
|
||||
|
||||
`isBalanced("123A#b!E&*456-o.U")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isBalanced("123A#b!E&*456-o.U"));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function isBalanced(s) {
|
||||
|
||||
return s;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function isBalanced(s) {
|
||||
const vowels = 'aeiou';
|
||||
const half = Math.floor(s.length / 2);
|
||||
|
||||
let firstHalf = s.slice(0, half);
|
||||
let secondHalf = s.length % 2 === 0 ? s.slice(half) : s.slice(half + 1);
|
||||
|
||||
const countVowels = str =>
|
||||
str
|
||||
.toLowerCase()
|
||||
.split('')
|
||||
.filter(c => vowels.includes(c))
|
||||
.length;
|
||||
|
||||
return countVowels(firstHalf) === countVowels(secondHalf);
|
||||
}
|
||||
```
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
---
|
||||
id: 681cb05adab50c87ddb2e513
|
||||
title: "Challenge 2: Base Check"
|
||||
challengeType: 28
|
||||
dashedName: challenge-2
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string representing a number, and an integer base from 2 to 36, determine whether the number is valid in that base.
|
||||
|
||||
- The string may contain integers, and uppercase or lowercase characters.
|
||||
- The check should be case-insensitive.
|
||||
- The base can be any number 2-36.
|
||||
- A number is valid if every character is a valid digit in the given base.
|
||||
- Example of valid digits for bases:
|
||||
- Base 2: 0-1
|
||||
- Base 8: 0-7
|
||||
- Base 10: 0-9
|
||||
- Base 16: 0-9 and A-F
|
||||
- Base 36: 0-9 and A-Z
|
||||
|
||||
# --hints--
|
||||
|
||||
`isValidNumber("10101", 2)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isValidNumber("10101", 2))
|
||||
```
|
||||
|
||||
`isValidNumber("10201", 2)` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isValidNumber("10201", 2))
|
||||
```
|
||||
|
||||
`isValidNumber("76543210", 8)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isValidNumber("76543210", 8))
|
||||
```
|
||||
|
||||
`isValidNumber("9876543210", 8)` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isValidNumber("9876543210", 8))
|
||||
```
|
||||
|
||||
`isValidNumber("9876543210", 10)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isValidNumber("9876543210", 10))
|
||||
```
|
||||
|
||||
`isValidNumber("ABC", 10)` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isValidNumber("ABC", 10))
|
||||
```
|
||||
|
||||
`isValidNumber("ABC", 16)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isValidNumber("ABC", 16))
|
||||
```
|
||||
|
||||
`isValidNumber("Z", 36)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isValidNumber("Z", 36))
|
||||
```
|
||||
|
||||
`isValidNumber("ABC", 20)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isValidNumber("ABC", 20))
|
||||
```
|
||||
|
||||
`isValidNumber("4B4BA9", 16)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isValidNumber("4B4BA9", 16))
|
||||
```
|
||||
|
||||
`isValidNumber("5G3F8F", 16)` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isValidNumber("5G3F8F", 16))
|
||||
```
|
||||
|
||||
`isValidNumber("5G3F8F", 17)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isValidNumber("5G3F8F", 17))
|
||||
```
|
||||
|
||||
`isValidNumber("abc", 10)` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isValidNumber("abc", 10))
|
||||
```
|
||||
|
||||
`isValidNumber("abc", 16)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isValidNumber("abc", 16))
|
||||
```
|
||||
|
||||
`isValidNumber("AbC", 16)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isValidNumber("AbC", 16))
|
||||
```
|
||||
|
||||
`isValidNumber("z", 36)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isValidNumber("z", 36))
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function isValidNumber(n, base) {
|
||||
|
||||
return n;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function isValidNumber(n, base) {
|
||||
return new RegExp(`^[${'0123456789abcdefghijklmnopqrstuvwxyz'.substring(0, base)}]+\$`, "i").test(n);
|
||||
}
|
||||
```
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
---
|
||||
id: 681cb1a2dab50c87ddb2e514
|
||||
title: "Challenge 3: Fibonacci Sequence"
|
||||
challengeType: 28
|
||||
dashedName: challenge-3
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. When starting with `0` and `1`, the first 10 numbers in the sequence are `0`, `1`, `1`, `2`, `3`, `5`, `8`, `13`, `21`, `34`.
|
||||
|
||||
Given an array containing the first two numbers of a Fibonacci sequence, and an integer representing the length of the sequence, return an array containing the sequence of the given length.
|
||||
|
||||
- Your function should handle sequences of any length greater than or equal to zero.
|
||||
- If the length is zero, return an empty array.
|
||||
- Note that the starting numbers are part of the sequence.
|
||||
|
||||
# --hints--
|
||||
|
||||
`fibonacciSequence([0, 1], 20)` should return `[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fibonacciSequence([0, 1], 20), [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]);
|
||||
```
|
||||
|
||||
`fibonacciSequence([21, 32], 1)` should return `[21]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fibonacciSequence([21, 32], 1), [21]);
|
||||
```
|
||||
|
||||
`fibonacciSequence([0, 1], 0)` should return `[]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fibonacciSequence([0, 1], 0), []);
|
||||
```
|
||||
|
||||
`fibonacciSequence([10, 20], 2)` should return `[10, 20]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fibonacciSequence([10, 20], 2), [10, 20]);
|
||||
```
|
||||
|
||||
`fibonacciSequence([123456789, 987654321], 5)` should return `[123456789, 987654321, 1111111110, 2098765431, 3209876541]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fibonacciSequence([123456789, 987654321], 5), [123456789, 987654321, 1111111110, 2098765431, 3209876541]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function fibonacciSequence(startSequence, length) {
|
||||
|
||||
return length;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function fibonacciSequence(startSequence, length) {
|
||||
if (length === 0) return [];
|
||||
if (length === 1) return [startSequence[0]];
|
||||
if (length === 2) return [...startSequence];
|
||||
|
||||
const sequence = [...startSequence];
|
||||
while (sequence.length < length) {
|
||||
const nextValue = sequence[sequence.length - 1] + sequence[sequence.length - 2];
|
||||
sequence.push(nextValue);
|
||||
}
|
||||
return sequence;
|
||||
}
|
||||
```
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
---
|
||||
id: 681cb1afdab50c87ddb2e515
|
||||
title: "Challenge 4: S P A C E J A M"
|
||||
challengeType: 28
|
||||
dashedName: challenge-4
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string, remove all spaces from the string, insert two spaces between every character, convert all alphabetical letters to uppercase, and return the result.
|
||||
|
||||
- Non-alphabetical characters should remain unchanged (except for spaces).
|
||||
|
||||
# --hints--
|
||||
|
||||
`spaceJam("freeCodeCamp")` should return `"F R E E C O D E C A M P"`.
|
||||
|
||||
```js
|
||||
assert.equal(spaceJam("freeCodeCamp"), "F R E E C O D E C A M P");
|
||||
```
|
||||
|
||||
`spaceJam(" free Code Camp ")` should return `"F R E E C O D E C A M P"`.
|
||||
|
||||
```js
|
||||
assert.equal(spaceJam(" free Code Camp "), "F R E E C O D E C A M P");
|
||||
```
|
||||
|
||||
`spaceJam("Hello World?!")` should return `"H E L L O W O R L D ? !"`.
|
||||
|
||||
```js
|
||||
assert.equal(spaceJam("Hello World?!"), "H E L L O W O R L D ? !");
|
||||
```
|
||||
|
||||
`spaceJam("C@t$ & D0g$")` should return `"C @ T $ & D 0 G $"`.
|
||||
|
||||
```js
|
||||
assert.equal(spaceJam("C@t$ & D0g$"), "C @ T $ & D 0 G $");
|
||||
```
|
||||
|
||||
`spaceJam("allyourbase")` should return `"A L L Y O U R B A S E"`.
|
||||
|
||||
```js
|
||||
assert.equal(spaceJam("all your base"), "A L L Y O U R B A S E");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function spaceJam(s) {
|
||||
|
||||
return s;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function spaceJam(s) {
|
||||
return s.toUpperCase().replace(/\s+/g, '').split('').join(' ');
|
||||
}
|
||||
```
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
---
|
||||
id: 681cb1afdab50c87ddb2e516
|
||||
title: "Challenge 5: Jbelmud Text"
|
||||
challengeType: 28
|
||||
dashedName: challenge-5
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string, return a jumbled version of that string where each word is transformed using the following constraints:
|
||||
|
||||
- The first and last letters of the words remain in place
|
||||
- All letters between the first and last letter are sorted alphabetically.
|
||||
- The input strings will contain no punctuation, and will be entirely lowercase.
|
||||
|
||||
# --hints--
|
||||
|
||||
`jbelmu("hello world")` should return `"hello wlord"`.
|
||||
|
||||
```js
|
||||
assert.equal(jbelmu("hello world"), "hello wlord");
|
||||
```
|
||||
|
||||
`jbelmu("i love jumbled text")` should return `"i love jbelmud text"`.
|
||||
|
||||
```js
|
||||
assert.equal(jbelmu("i love jumbled text"), "i love jbelmud text");
|
||||
```
|
||||
|
||||
`jbelmu("freecodecamp is my favorite place to learn to code")` should return `"faccdeeemorp is my faiortve pacle to laern to cdoe"`.
|
||||
|
||||
```js
|
||||
assert.equal(jbelmu("freecodecamp is my favorite place to learn to code"), "faccdeeemorp is my faiortve pacle to laern to cdoe");
|
||||
```
|
||||
|
||||
`jbelmu("the quick brown fox jumps over the lazy dog")` should return `"the qciuk borwn fox jmpus oevr the lazy dog"`.
|
||||
|
||||
```js
|
||||
assert.equal(jbelmu("the quick brown fox jumps over the lazy dog"), "the qciuk borwn fox jmpus oevr the lazy dog");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function jbelmu(text) {
|
||||
|
||||
return text;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function jbelmu(text) {
|
||||
return text
|
||||
.split(' ')
|
||||
.map((word) => {
|
||||
if (word.length <= 3) return word;
|
||||
const first = word[0];
|
||||
const last = word[word.length - 1];
|
||||
const middle = word
|
||||
.slice(1, -1)
|
||||
.split('')
|
||||
.sort()
|
||||
.join('');
|
||||
return first + middle + last;
|
||||
})
|
||||
.join(' ');
|
||||
}
|
||||
```
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
---
|
||||
id: 681cb1afdab50c87ddb2e517
|
||||
title: "Challenge 6: Anagram Checker"
|
||||
challengeType: 28
|
||||
dashedName: challenge-6
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given two strings, determine if they are anagrams of each other (contain the same characters in any order).
|
||||
|
||||
- Ignore casing and white space.
|
||||
|
||||
# --hints--
|
||||
|
||||
`areAnagrams("listen", "silent")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(areAnagrams("listen", "silent"));
|
||||
```
|
||||
|
||||
`areAnagrams("School master", "The classroom")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(areAnagrams("School master", "The classroom"));
|
||||
```
|
||||
|
||||
`areAnagrams("A gentleman", "Elegant man")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(areAnagrams("A gentleman", "Elegant man"));
|
||||
```
|
||||
|
||||
`areAnagrams("Hello", "World")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(areAnagrams("Hello", "World"));
|
||||
```
|
||||
|
||||
`areAnagrams("apple", "banana")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(areAnagrams("apple", "banana"));
|
||||
```
|
||||
|
||||
`areAnagrams("cat", "dog")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(areAnagrams("cat", "dog"));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function areAnagrams(str1, str2) {
|
||||
|
||||
return str1;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function areAnagrams(str1, str2) {
|
||||
const clean = (str) =>
|
||||
str.replace(/\s+/g, '').toLowerCase().split('').sort().join('');
|
||||
|
||||
return clean(str1) === clean(str2);
|
||||
}
|
||||
```
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
---
|
||||
id: 681cb1b0dab50c87ddb2e518
|
||||
title: "Challenge 7: Targeted Sum"
|
||||
challengeType: 28
|
||||
dashedName: challenge-7
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given an array of numbers and an integer target, find two unique numbers in the array that add up to the target value. Return an array with the indices of those two numbers, or `"Target not found"` if no two numbers sum up to the target.
|
||||
|
||||
- The returned array should have the indices in ascending order.
|
||||
|
||||
# --hints--
|
||||
|
||||
`findTarget([2, 7, 11, 15], 9)` should return `[0, 1]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(findTarget([2, 7, 11, 15], 9), [0, 1]);
|
||||
```
|
||||
|
||||
`findTarget([3, 2, 4, 5], 6)` should return `[1, 2]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(findTarget([3, 2, 4, 5], 6), [1, 2]);
|
||||
```
|
||||
|
||||
`findTarget([1, 3, 5, 6, 7, 8], 15)` should return `[4, 5]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(findTarget([1, 3, 5, 6, 7, 8], 15), [4, 5]);
|
||||
```
|
||||
|
||||
`findTarget([1, 3, 5, 7], 14)` should return `"Target not found"`.
|
||||
|
||||
```js
|
||||
assert.equal(findTarget([1, 3, 5, 7], 14), "Target not found");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function findTarget(arr, target) {
|
||||
|
||||
return arr;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function findTarget(arr, target) {
|
||||
for (let i = 0; i < arr.length; i++) {
|
||||
for (let j = i + 1; j < arr.length; j++) {
|
||||
if (arr[i] + arr[j] === target) {
|
||||
return [i, j];
|
||||
}
|
||||
}
|
||||
}
|
||||
return 'Target not found'
|
||||
}
|
||||
```
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
---
|
||||
id: 681cb1b0dab50c87ddb2e519
|
||||
title: "Challenge 8: Factorializer"
|
||||
challengeType: 28
|
||||
dashedName: challenge-8
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given an integer from zero to 20, return the factorial of that number. The factorial of a number is the product of all the numbers between 1 and the given number.
|
||||
|
||||
- The factorial of zero is 1.
|
||||
|
||||
# --hints--
|
||||
|
||||
`factorial(0)` should return `1`.
|
||||
|
||||
```js
|
||||
assert.equal(factorial(0), 1);
|
||||
```
|
||||
|
||||
`factorial(5)` should return `120`.
|
||||
|
||||
```js
|
||||
assert.equal(factorial(5), 120);
|
||||
```
|
||||
|
||||
`factorial(20)` should return `2432902008176640000`.
|
||||
|
||||
```js
|
||||
assert.equal(factorial(20), 2432902008176640000);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function factorial(n) {
|
||||
|
||||
return n;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function factorial(n) {
|
||||
return n == 0 ? 1 : n * factorial(n - 1);
|
||||
}
|
||||
```
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
---
|
||||
id: 681cb1b0dab50c87ddb2e51a
|
||||
title: "Challenge 9: Sum of Squares"
|
||||
challengeType: 28
|
||||
dashedName: challenge-9
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a positive integer up to 1,000, return the sum of all the integers squared from 1 up to the number.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sumOfSquares(5)` should return `55`.
|
||||
|
||||
```js
|
||||
assert.equal(sumOfSquares(5), 55);
|
||||
```
|
||||
|
||||
`sumOfSquares(10)` should return `385`.
|
||||
|
||||
```js
|
||||
assert.equal(sumOfSquares(10), 385);
|
||||
```
|
||||
|
||||
`sumOfSquares(25)` should return `5525`.
|
||||
|
||||
```js
|
||||
assert.equal(sumOfSquares(25), 5525);
|
||||
```
|
||||
|
||||
`sumOfSquares(500)` should return `41791750`.
|
||||
|
||||
```js
|
||||
assert.equal(sumOfSquares(500), 41791750);
|
||||
```
|
||||
|
||||
`sumOfSquares(1000)` should return `333833500`.
|
||||
|
||||
```js
|
||||
assert.equal(sumOfSquares(1000), 333833500);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function sumOfSquares(n) {
|
||||
|
||||
return n;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function sumOfSquares(n) {
|
||||
let total = 1;
|
||||
for(let i = 2; i <= n; i++) {
|
||||
total += i * i;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
```
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
---
|
||||
id: 681cb1b0dab50c87ddb2e51b
|
||||
title: "Challenge 10: 3 Strikes"
|
||||
challengeType: 28
|
||||
dashedName: challenge-10
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given an integer between 1 and 10,000, return a count of how many numbers from 1 up to that integer whose square contains at least one digit 3.
|
||||
|
||||
# --hints--
|
||||
|
||||
`squaresWithThree(1)` should return `0`.
|
||||
|
||||
```js
|
||||
assert.equal(squaresWithThree(1), 0);
|
||||
```
|
||||
|
||||
`squaresWithThree(10)` should return `1`.
|
||||
|
||||
```js
|
||||
assert.equal(squaresWithThree(10), 1);
|
||||
```
|
||||
|
||||
`squaresWithThree(100)` should return `19`.
|
||||
|
||||
```js
|
||||
assert.equal(squaresWithThree(100), 19);
|
||||
```
|
||||
|
||||
`squaresWithThree(1000)` should return `326`.
|
||||
|
||||
```js
|
||||
assert.equal(squaresWithThree(1000), 326);
|
||||
```
|
||||
|
||||
`squaresWithThree(10000)` should return `4531`.
|
||||
|
||||
```js
|
||||
assert.equal(squaresWithThree(10000), 4531);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function squaresWithThree(n) {
|
||||
|
||||
return n;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function squaresWithThree(n) {
|
||||
let count = 0;
|
||||
|
||||
for (let i = 1; i <= n; i++) {
|
||||
const square = i * i;
|
||||
if (square.toString().includes('3')) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
```
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
---
|
||||
id: 68216eb60f957572e7c340c4
|
||||
title: "Challenge 11: Mile Pace"
|
||||
challengeType: 28
|
||||
dashedName: challenge-11
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a number of miles ran, and a time in `"MM:SS"` (minutes:seconds) it took to run those miles, return a string for the average time it took to run each mile in the format `"MM:SS"`.
|
||||
|
||||
- Add leading zeros when needed.
|
||||
|
||||
# --hints--
|
||||
|
||||
`milePace(3, "24:00")` should return `"08:00"`.
|
||||
|
||||
```js
|
||||
assert.equal(milePace(3, "24:00"), "08:00");
|
||||
```
|
||||
|
||||
`milePace(1, "06:45")` should return `"06:45"`.
|
||||
|
||||
```js
|
||||
assert.equal(milePace(1, "06:45"), "06:45");
|
||||
```
|
||||
|
||||
`milePace(2, "07:00")` should return `"03:30"`.
|
||||
|
||||
```js
|
||||
assert.equal(milePace(2, "07:00"), "03:30");
|
||||
```
|
||||
|
||||
`milePace(26.2, "120:35")` should return `"04:36"`.
|
||||
|
||||
```js
|
||||
assert.equal(milePace(26.2, "120:35"), "04:36");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function milePace(miles, duration) {
|
||||
|
||||
return miles;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function milePace(miles, duration) {
|
||||
const [minutes, seconds] = duration.split(':').map(Number);
|
||||
const totalSeconds = minutes * 60 + seconds;
|
||||
const avgSecondsPerMile = totalSeconds / miles;
|
||||
|
||||
const avgMinutes = Math.floor(avgSecondsPerMile / 60);
|
||||
const avgSeconds = Math.round(avgSecondsPerMile % 60);
|
||||
|
||||
const paddedMinutes = avgMinutes.toString().padStart(2, '0');
|
||||
const paddedSeconds = avgSeconds.toString().padStart(2, '0');
|
||||
|
||||
return `${paddedMinutes}:${paddedSeconds}`;
|
||||
}
|
||||
```
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
---
|
||||
id: 68216ef80f957572e7c340c5
|
||||
title: "Challenge 12: Message Decoder"
|
||||
challengeType: 28
|
||||
dashedName: challenge-12
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a secret message string, and an integer representing the number of letters that were used to shift the message to encode it, return the decoded string.
|
||||
|
||||
- A positive number means the message was shifted forward in the alphabet.
|
||||
- A negative number means the message was shifted backward in the alphabet.
|
||||
- Case matters, decoded characters should retain the case of their encoded counterparts.
|
||||
- Non-alphabetical characters should not get decoded.
|
||||
|
||||
# --hints--
|
||||
|
||||
`decode("Xlmw mw e wigvix qiwweki.", 4)` should return `"This is a secret message."`
|
||||
|
||||
```js
|
||||
assert.equal(decode("Xlmw mw e wigvix qiwweki.", 4), "This is a secret message.");
|
||||
```
|
||||
|
||||
`decode("Byffi Qilfx!", 20)` should return `"Hello World!"`
|
||||
|
||||
```js
|
||||
assert.equal(decode("Byffi Qilfx!", 20), "Hello World!");
|
||||
```
|
||||
|
||||
`decode("Zqd xnt njzx?", -1)` should return `"Are you okay?"`
|
||||
|
||||
```js
|
||||
assert.equal(decode("Zqd xnt njzx?", -1), "Are you okay?");
|
||||
```
|
||||
|
||||
`decode("oannLxmnLjvy", 9)` should return `"freeCodeCamp"`
|
||||
|
||||
```js
|
||||
assert.equal(decode("oannLxmnLjvy", 9), "freeCodeCamp");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function decode(message, shift) {
|
||||
|
||||
return message;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function decode(message, shift) {
|
||||
return message.split('').map(char => {
|
||||
if (/[a-zA-Z]/.test(char)) {
|
||||
const base = char === char.toLowerCase() ? 'a'.charCodeAt(0) : 'A'.charCodeAt(0);
|
||||
const charCode = char.charCodeAt(0);
|
||||
const offset = (charCode - base - shift + 26) % 26;
|
||||
return String.fromCharCode(base + offset);
|
||||
} else {
|
||||
return char;
|
||||
}
|
||||
}).join('');
|
||||
}
|
||||
```
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
---
|
||||
id: 6821ebc9237de8297eaee78f
|
||||
title: "Challenge 13: Unnatural Prime"
|
||||
challengeType: 28
|
||||
dashedName: challenge-13
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given an integer, determine if that number is a prime number or a negative prime number.
|
||||
|
||||
- A prime number is a positive integer greater than 1 that is only divisible by 1 and itself.
|
||||
- A negative prime number is the negative version of a positive prime number.
|
||||
- `1` and `0` are not considered prime numbers.
|
||||
|
||||
# --hints--
|
||||
|
||||
`isUnnaturalPrime(1)` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isUnnaturalPrime(1));
|
||||
```
|
||||
|
||||
`isUnnaturalPrime(-1)` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isUnnaturalPrime(-1));
|
||||
```
|
||||
|
||||
`isUnnaturalPrime(19)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isUnnaturalPrime(19));
|
||||
```
|
||||
|
||||
`isUnnaturalPrime(-23)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isUnnaturalPrime(-23));
|
||||
```
|
||||
|
||||
`isUnnaturalPrime(0)` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isUnnaturalPrime(0));
|
||||
```
|
||||
|
||||
`isUnnaturalPrime(97)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isUnnaturalPrime(97));
|
||||
```
|
||||
|
||||
`isUnnaturalPrime(-61)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isUnnaturalPrime(-61));
|
||||
```
|
||||
|
||||
`isUnnaturalPrime(99)` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isUnnaturalPrime(99));
|
||||
```
|
||||
|
||||
`isUnnaturalPrime(-44)` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isUnnaturalPrime(-44));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function isUnnaturalPrime(n) {
|
||||
|
||||
return n;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function isUnnaturalPrime(n) {
|
||||
const abs = Math.abs(n);
|
||||
|
||||
if (abs <= 1) return false;
|
||||
|
||||
for (let i = 2; i <= Math.sqrt(abs); i++) {
|
||||
if (abs % i === 0) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
---
|
||||
id: 6821ebce237de8297eaee790
|
||||
title: "Challenge 14: Character Battle"
|
||||
challengeType: 28
|
||||
dashedName: challenge-14
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given two strings representing your army and an opposing army, each character from your army battles the character at the same position from the opposing army using the following rules:
|
||||
|
||||
- Characters `a-z` have a strength of `1-26`, respectively.
|
||||
- Characters `A-Z` have a strength of `27-52`, respectively.
|
||||
- Digits `0-9` have a strength of their face value.
|
||||
- All other characters have a value of zero.
|
||||
- Each character can only fight one battle.
|
||||
|
||||
For each battle, the stronger character wins. The army with more victories, wins the war. Return the following values:
|
||||
|
||||
- `"Opponent retreated"` if your army has more characters than the opposing army.
|
||||
- `"We retreated"` if the opposing army has more characters than yours.
|
||||
- `"We won"` if your army won more battles.
|
||||
- `"We lost"` if the opposing army won more battles.
|
||||
- `"It was a tie"` if both armies won the same number of battles.
|
||||
|
||||
# --hints--
|
||||
|
||||
`battle("Hello", "World")` should return `"We lost"`.
|
||||
|
||||
```js
|
||||
assert.equal(battle("Hello", "World"), "We lost");
|
||||
```
|
||||
|
||||
`battle("pizza", "salad")` should return `"We won"`.
|
||||
|
||||
```js
|
||||
assert.equal(battle("pizza", "salad"), "We won");
|
||||
```
|
||||
|
||||
`battle("C@T5", "D0G$")` should return `"We won"`.
|
||||
|
||||
```js
|
||||
assert.equal(battle("C@T5", "D0G$"), "We won");
|
||||
```
|
||||
|
||||
`battle("kn!ght", "orc")` should return `"Opponent retreated"`.
|
||||
|
||||
```js
|
||||
assert.equal(battle("kn!ght", "orc"), "Opponent retreated");
|
||||
```
|
||||
|
||||
`battle("PC", "Mac")` should return `"We retreated"`.
|
||||
|
||||
```js
|
||||
assert.equal(battle("PC", "Mac"), "We retreated");
|
||||
```
|
||||
|
||||
`battle("Wizards", "Dragons")` should return `"It was a tie"`.
|
||||
|
||||
```js
|
||||
assert.equal(battle("Wizards", "Dragons"), "It was a tie");
|
||||
```
|
||||
|
||||
`battle("Mr. Smith", "Dr. Jones")` should return `"It was a tie"`.
|
||||
|
||||
```js
|
||||
assert.equal(battle("Mr. Smith", "Dr. Jones"), "It was a tie");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function battle(myArmy, opposingArmy) {
|
||||
|
||||
return myArmy;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function getStrength(soldier) {
|
||||
const soldiers = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
||||
let strength = 0;
|
||||
|
||||
if (/\d/.test(soldier)) {
|
||||
strength = parseInt(soldier);
|
||||
} else if (soldiers.includes(soldier)) {
|
||||
strength = soldiers.indexOf(soldier) + 1;
|
||||
}
|
||||
|
||||
return strength;
|
||||
}
|
||||
|
||||
function battle(myArmy, opposingArmy) {
|
||||
if (myArmy.length > opposingArmy.length) return 'Opponent retreated';
|
||||
if (opposingArmy.length > myArmy.length) return 'We retreated';
|
||||
|
||||
let myWins = 0;
|
||||
let theirWins = 0;
|
||||
|
||||
for (let i = 0; i < myArmy.length; i++) {
|
||||
const mySoldier = myArmy[i];
|
||||
const theirSoldier = opposingArmy[i];
|
||||
|
||||
const myStrength = getStrength(mySoldier);
|
||||
const theirStrength = getStrength(theirSoldier);
|
||||
|
||||
if (myStrength > theirStrength) myWins++;
|
||||
if (theirStrength > myStrength) theirWins++;
|
||||
}
|
||||
|
||||
return myWins > theirWins ? 'We won' : theirWins > myWins ? 'We lost' : 'It was a tie';
|
||||
}
|
||||
```
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
---
|
||||
id: 6821ebd4237de8297eaee791
|
||||
title: "Challenge 15: camelCase"
|
||||
challengeType: 28
|
||||
dashedName: challenge-15
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string, return its camel case version using the following rules:
|
||||
|
||||
- Words in the string argument are separated by one or more characters from the following set: space (` `), dash (`-`), or underscore (`_`). Treat any sequence of these as a word break.
|
||||
- The first word should be all lowercase.
|
||||
- Each subsequent word should start with an uppercase letter, with the rest of it lowercase.
|
||||
- All spaces and separators should be removed.
|
||||
|
||||
# --hints--
|
||||
|
||||
`toCamelCase("hello world")` should return `"helloWorld"`.
|
||||
|
||||
```js
|
||||
assert.equal(toCamelCase("hello world"), "helloWorld");
|
||||
```
|
||||
|
||||
`toCamelCase("HELLO WORLD")` should return `"helloWorld"`.
|
||||
|
||||
```js
|
||||
assert.equal(toCamelCase("HELLO WORLD"), "helloWorld");
|
||||
```
|
||||
|
||||
`toCamelCase("secret agent-X")` should return `"secretAgentX"`.
|
||||
|
||||
```js
|
||||
assert.equal(toCamelCase("secret agent-X"), "secretAgentX");
|
||||
```
|
||||
|
||||
`toCamelCase("FREE cODE cAMP")` should return `"freeCodeCamp"`.
|
||||
|
||||
```js
|
||||
assert.equal(toCamelCase("FREE cODE cAMP"), "freeCodeCamp");
|
||||
```
|
||||
|
||||
`toCamelCase("ye old-_-sea faring_buccaneer_-_with a - peg__leg----and a_parrot_ _named- _squawk")` should return `"yeOldSeaFaringBuccaneerWithAPegLegAndAParrotNamedSquawk"`.
|
||||
|
||||
```js
|
||||
assert.equal(toCamelCase("ye old-_-sea faring_buccaneer_-_with a - peg__leg----and a_parrot_ _named- _squawk"), "yeOldSeaFaringBuccaneerWithAPegLegAndAParrotNamedSquawk");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function toCamelCase(s) {
|
||||
|
||||
return s;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function toCamelCase(s) {
|
||||
const words = s.replace(/[_\- ]+/g, ' ').split(' ');
|
||||
|
||||
return words.map((word, i) => {
|
||||
if (i === 0) {
|
||||
return word.toLowerCase();
|
||||
} else {
|
||||
const tempWord = word.split('');
|
||||
return tempWord.shift().toUpperCase() + tempWord.join('').toLowerCase();
|
||||
}
|
||||
}).join('')
|
||||
}
|
||||
```
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
---
|
||||
id: 6821ebda237de8297eaee792
|
||||
title: "Challenge 16: Reverse Parenthesis"
|
||||
challengeType: 28
|
||||
dashedName: challenge-16
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string that contains properly nested parentheses, return the decoded version of the string using the following rules:
|
||||
|
||||
- All characters inside each pair of parentheses should be reversed.
|
||||
- Parentheses should be removed from the final result.
|
||||
- If parentheses are nested, the innermost pair should be reversed first, and then its result should be included in the reversal of the outer pair.
|
||||
- Assume all parentheses are evenly balanced and correctly nested.
|
||||
|
||||
# --hints--
|
||||
|
||||
`decode("(f(b(dc)e)a)")` should return `"abcdef"`.
|
||||
|
||||
```js
|
||||
assert.equal(decode("(f(b(dc)e)a)"), "abcdef");
|
||||
```
|
||||
|
||||
`decode("((is?)(a(t d)h)e(n y( uo)r)aC)")` should return `"Can you read this?"`.
|
||||
|
||||
```js
|
||||
assert.equal(decode("((is?)(a(t d)h)e(n y( uo)r)aC)"), "Can you read this?");
|
||||
```
|
||||
|
||||
`decode("f(Ce(re))o((e(aC)m)d)p")` should return `"freeCodeCamp"`.
|
||||
|
||||
```js
|
||||
assert.equal(decode("f(Ce(re))o((e(aC)m)d)p"), "freeCodeCamp");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function decode(s) {
|
||||
|
||||
return s;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function decode(s) {
|
||||
while (s.includes(')')) {
|
||||
const closeIndex = s.indexOf(')');
|
||||
const openIndex = s.lastIndexOf('(', closeIndex);
|
||||
const before = s.slice(0, openIndex);
|
||||
const group = s.slice(openIndex + 1, closeIndex).split('').reverse().join('');
|
||||
const after = s.slice(closeIndex + 1);
|
||||
s = before + group + after;
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
```
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
---
|
||||
id: 6821ebdf237de8297eaee793
|
||||
title: "Challenge 17: Unorder of Operations"
|
||||
challengeType: 28
|
||||
dashedName: challenge-17
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given an array of integers and an array of string operators, apply the operations to the numbers sequentially from left-to-right. Repeat the operations as needed until all numbers are used. Return the final result.
|
||||
|
||||
For example, given `[1, 2, 3, 4, 5]` and `['+', '*']`, return the result of evaluating `1 + 2 * 3 + 4 * 5` from left-to-right ignoring standard order of operations.
|
||||
|
||||
- Valid operators are `+`, `-`, `*`, `/`, and `%`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`evaluate([5, 6, 7, 8, 9], ['+', '-'])` should return `3`
|
||||
|
||||
```js
|
||||
assert.equal(evaluate([5, 6, 7, 8, 9], ['+', '-']), 3);
|
||||
```
|
||||
|
||||
`evaluate([17, 61, 40, 24, 38, 14], ['+', '%'])` should return `38`
|
||||
|
||||
```js
|
||||
assert.equal(evaluate([17, 61, 40, 24, 38, 14], ['+', '%']), 38);
|
||||
```
|
||||
|
||||
`evaluate([20, 2, 4, 24, 12, 3], ['*', '/'])` should return `60`
|
||||
|
||||
```js
|
||||
assert.equal(evaluate([20, 2, 4, 24, 12, 3], ['*', '/']), 60);
|
||||
```
|
||||
|
||||
`evaluate([11, 4, 10, 17, 2], ['*', '*', '%'])` should return `30`
|
||||
|
||||
```js
|
||||
assert.equal(evaluate([11, 4, 10, 17, 2], ['*', '*', '%']), 30);
|
||||
```
|
||||
|
||||
`evaluate([33, 11, 29, 13], ['/', '-'])` should return `-2`
|
||||
|
||||
```js
|
||||
assert.equal(evaluate([33, 11, 29, 13], ['/', '-']), -2);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function evaluate(numbers, operators) {
|
||||
|
||||
return numbers;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function doMath(a, b, operator) {
|
||||
switch (operator) {
|
||||
case "+":
|
||||
return a + b;
|
||||
case "-":
|
||||
return a - b;
|
||||
case "*":
|
||||
return a * b;
|
||||
case "/":
|
||||
return a / b;
|
||||
default:
|
||||
return a % b;
|
||||
}
|
||||
}
|
||||
|
||||
function evaluate(numbers, operators) {
|
||||
let total = numbers[0];
|
||||
|
||||
for (let i = 1; i < numbers.length; i++) {
|
||||
const operator = operators[(i - 1) % operators.length];
|
||||
total = doMath(total, numbers[i], operator);
|
||||
}
|
||||
|
||||
return total;
|
||||
}
|
||||
```
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
---
|
||||
id: 6821ebe4237de8297eaee794
|
||||
title: "Challenge 18: Second Best"
|
||||
challengeType: 28
|
||||
dashedName: challenge-18
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given an array of integers representing the price of different laptops, and an integer representing your budget, return:
|
||||
|
||||
1. The second most expensive laptop if it is within your budget, or
|
||||
2. The most expensive laptop that is within your budget, or
|
||||
3. `0` if no laptops are within your budget.
|
||||
|
||||
- Duplicate prices should be ignored.
|
||||
|
||||
# --hints--
|
||||
|
||||
`getLaptopCost([1500, 2000, 1800, 1400], 1900)` should return `1800`
|
||||
|
||||
```js
|
||||
assert.equal(getLaptopCost([1500, 2000, 1800, 1400], 1900), 1800);
|
||||
```
|
||||
|
||||
`getLaptopCost([1500, 2000, 2000, 1800, 1400], 1900)` should return `1800`
|
||||
|
||||
```js
|
||||
assert.equal(getLaptopCost([1500, 2000, 2000, 1800, 1400], 1900), 1800);
|
||||
```
|
||||
|
||||
`getLaptopCost([2099, 1599, 1899, 1499], 2200)` should return `1899`
|
||||
|
||||
```js
|
||||
assert.equal(getLaptopCost([2099, 1599, 1899, 1499], 2200), 1899);
|
||||
```
|
||||
|
||||
`getLaptopCost([2099, 1599, 1899, 1499], 1000)` should return `0`
|
||||
|
||||
```js
|
||||
assert.equal(getLaptopCost([2099, 1599, 1899, 1499], 1000), 0);
|
||||
```
|
||||
|
||||
`getLaptopCost([1200, 1500, 1600, 1800, 1400, 2000], 1450)` should return `1400`
|
||||
|
||||
```js
|
||||
assert.equal(getLaptopCost([1200, 1500, 1600, 1800, 1400, 2000], 1450), 1400);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function getLaptopCost(laptops, budget) {
|
||||
|
||||
return laptops;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function getLaptopCost(laptops, budget) {
|
||||
laptops = [...new Set(laptops)].sort((a, b) => b - a);
|
||||
|
||||
if (budget >= laptops[1]) return laptops[1];
|
||||
if (budget < laptops[laptops.length - 1]) return 0;
|
||||
|
||||
for (let i = 2; i < laptops.length; i++) {
|
||||
if (budget >= laptops[i]) return laptops[i];
|
||||
}
|
||||
}
|
||||
```
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
---
|
||||
id: 6821ebea237de8297eaee795
|
||||
title: "Challenge 19: Candlelight"
|
||||
challengeType: 28
|
||||
dashedName: challenge-19
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given an integer representing the number of candles you start with, and an integer representing how many burned candles it takes to create a new one, return the number of candles you will have used after creating and burning as many as you can.
|
||||
|
||||
For example, if given 7 candles and it takes 2 burned candles to make a new one:
|
||||
|
||||
1. Burn 7 candles to get 7 leftovers,
|
||||
2. Recycle 6 leftovers into 3 new candles (1 leftover remains),
|
||||
3. Burn 3 candles to get 3 more leftovers (4 total),
|
||||
4. Recycle 4 leftovers into 2 new candles,
|
||||
5. Burn 2 candles to get 2 leftovers,
|
||||
6. Recycle 2 leftovers into 1 new candle,
|
||||
7. Burn 1 candle.
|
||||
|
||||
You will have burned 13 total candles in the example.
|
||||
|
||||
# --hints--
|
||||
|
||||
`burnCandles(7, 2)` should return `13`
|
||||
|
||||
```js
|
||||
assert.equal(burnCandles(7, 2), 13);
|
||||
```
|
||||
|
||||
`burnCandles(10, 5)` should return `12`
|
||||
|
||||
```js
|
||||
assert.equal(burnCandles(10, 5), 12);
|
||||
```
|
||||
|
||||
`burnCandles(20, 3)` should return `29`
|
||||
|
||||
```js
|
||||
assert.equal(burnCandles(20, 3), 29);
|
||||
```
|
||||
|
||||
`burnCandles(17, 4)` should return `22`
|
||||
|
||||
```js
|
||||
assert.equal(burnCandles(17, 4), 22);
|
||||
```
|
||||
|
||||
`burnCandles(2345, 3)` should return `3517`
|
||||
|
||||
```js
|
||||
assert.equal(burnCandles(2345, 3), 3517);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function burnCandles(candles, leftoversNeeded) {
|
||||
|
||||
return candles;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function burnCandles(candles, leftoversNeeded) {
|
||||
let totalBurned = 0;
|
||||
let unusedLeftovers = 0;
|
||||
|
||||
while (candles > 0) {
|
||||
totalBurned += candles;
|
||||
const leftovers = candles + unusedLeftovers;
|
||||
candles = Math.floor(leftovers / leftoversNeeded);
|
||||
unusedLeftovers = leftovers % leftoversNeeded;
|
||||
}
|
||||
|
||||
return totalBurned;
|
||||
}
|
||||
```
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
---
|
||||
id: 6821ebee237de8297eaee796
|
||||
title: "Challenge 20: Array Duplicates"
|
||||
challengeType: 28
|
||||
dashedName: challenge-20
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given an array of integers, return an array of integers that appear more than once in the initial array, sorted in ascending order. If no values appear more than once, return an empty array.
|
||||
|
||||
- Only include one instance of each value in the returned array.
|
||||
|
||||
# --hints--
|
||||
|
||||
`findDuplicates([1, 2, 3, 4, 5])` should return `[]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(findDuplicates([1, 2, 3, 4, 5]), []);
|
||||
```
|
||||
|
||||
`findDuplicates([1, 2, 3, 4, 1, 2])` should return `[1, 2]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(findDuplicates([1, 2, 3, 4, 1, 2]), [1, 2]);
|
||||
```
|
||||
|
||||
`findDuplicates([2, 34, 0, 1, -6, 23, 5, 3, 2, 5, 67, -6, 23, 2, 43, 2, 12, 0, 2, 4, 4])` should return `[-6, 0, 2, 4, 5, 23]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(findDuplicates([2, 34, 0, 1, -6, 23, 5, 3, 2, 5, 67, -6, 23, 2, 43, 2, 12, 0, 2, 4, 4]), [-6, 0, 2, 4, 5, 23]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function findDuplicates(arr) {
|
||||
|
||||
return arr;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function findDuplicates(arr) {
|
||||
const duplicates = [];
|
||||
|
||||
for (let i = 0; i < arr.length - 1; i++) {
|
||||
for (let j = i + 1; j < arr.length; j++) {
|
||||
if (arr[i] === arr[j] && !duplicates.includes(arr[i])) {
|
||||
duplicates.push(arr[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return duplicates.sort((a, b) => a - b);
|
||||
}
|
||||
```
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
---
|
||||
id: 6821ebf3237de8297eaee797
|
||||
title: "Challenge 21: Hex Generator"
|
||||
challengeType: 28
|
||||
dashedName: challenge-21
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a named CSS color string, generate a random hexadecimal (hex) color code that is dominant in the given color.
|
||||
|
||||
- The function should handle `"red"`, `"green"`, or `"blue"` as an input argument.
|
||||
- If the input is not one of those, the function should return `"Invalid color"`.
|
||||
- The function should return a random six-character hex color code where the input color value is greater than any of the others.
|
||||
- Example of valid outputs for a given input:
|
||||
|
||||
| Input | Output |
|
||||
|---------|----------|
|
||||
| `"red"` | `"FF0000"` |
|
||||
| `"green"` | `"00FF00"` |
|
||||
| `"blue"` | `"0000FF"` |
|
||||
|
||||
# --hints--
|
||||
|
||||
`generateHex("yellow")` should return `"Invalid color"`.
|
||||
|
||||
```js
|
||||
assert.equal(generateHex("yellow"), "Invalid color");
|
||||
```
|
||||
|
||||
`generateHex("red")` should return a six-character string.
|
||||
|
||||
```js
|
||||
assert.lengthOf(generateHex("red"), 6);
|
||||
```
|
||||
|
||||
`generateHex("red")` should return a valid six-character hex color code.
|
||||
|
||||
```js
|
||||
const hex = generateHex("red").toUpperCase();
|
||||
const isValidHex = /^[0-9A-F]{6}$/.test(hex);
|
||||
assert.isTrue(isValidHex);
|
||||
```
|
||||
|
||||
`generateHex("red")` should return a valid hex color with a higher red value than other colors.
|
||||
|
||||
```js
|
||||
const hex = generateHex("red").toUpperCase();
|
||||
const isValidHex = /^[0-9A-F]{6}$/.test(hex);
|
||||
assert.isTrue(isValidHex);
|
||||
|
||||
const r = parseInt(hex.slice(0, 2), 16);
|
||||
const g = parseInt(hex.slice(2, 4), 16);
|
||||
const b = parseInt(hex.slice(4, 6), 16);
|
||||
|
||||
assert.isAbove(r, g);
|
||||
assert.isAbove(r, b);
|
||||
```
|
||||
|
||||
Calling `generateHex("red")` twice should return two different hex color values where red is dominant.
|
||||
|
||||
```js
|
||||
const hex1 = generateHex("red").toUpperCase();
|
||||
const isValidHex1 = /^[0-9A-F]{6}$/.test(hex1)
|
||||
assert.isTrue(isValidHex1);
|
||||
|
||||
const r1 = parseInt(hex1.slice(0, 2), 16);
|
||||
const g1 = parseInt(hex1.slice(2, 4), 16);
|
||||
const b1 = parseInt(hex1.slice(4, 6), 16);
|
||||
|
||||
assert.isAbove(r1, g1);
|
||||
assert.isAbove(r1, b1);
|
||||
|
||||
const hex2 = generateHex("red").toUpperCase();
|
||||
const isValidHex2 = /^[0-9A-F]{6}$/.test(hex2);
|
||||
assert.isTrue(isValidHex2);
|
||||
|
||||
const r2 = parseInt(hex2.slice(0, 2), 16);
|
||||
const g2 = parseInt(hex2.slice(2, 4), 16);
|
||||
const b2 = parseInt(hex2.slice(4, 6), 16);
|
||||
|
||||
assert.isAbove(r2, g2);
|
||||
assert.isAbove(r2, b2);
|
||||
assert.notEqual(hex1, hex2);
|
||||
```
|
||||
|
||||
Calling `generateHex("green")` twice should return two different hex color values where green is dominant.
|
||||
|
||||
```js
|
||||
const hex1 = generateHex("green").toUpperCase();
|
||||
const isValidHex1 = /^[0-9A-F]{6}$/.test(hex1)
|
||||
assert.isTrue(isValidHex1);
|
||||
|
||||
const r1 = parseInt(hex1.slice(0, 2), 16);
|
||||
const g1 = parseInt(hex1.slice(2, 4), 16);
|
||||
const b1 = parseInt(hex1.slice(4, 6), 16);
|
||||
|
||||
assert.isAbove(g1, r1);
|
||||
assert.isAbove(g1, b1);
|
||||
|
||||
const hex2 = generateHex("green").toUpperCase();
|
||||
const isValidHex2 = /^[0-9A-F]{6}$/.test(hex2);
|
||||
assert.isTrue(isValidHex2);
|
||||
|
||||
const r2 = parseInt(hex2.slice(0, 2), 16);
|
||||
const g2 = parseInt(hex2.slice(2, 4), 16);
|
||||
const b2 = parseInt(hex2.slice(4, 6), 16);
|
||||
|
||||
assert.isAbove(g2, r2);
|
||||
assert.isAbove(g2, b2);
|
||||
assert.notEqual(hex1, hex2);
|
||||
```
|
||||
|
||||
Calling `generateHex("blue")` twice should return two different hex color values where blue is dominant.
|
||||
|
||||
```js
|
||||
const hex1 = generateHex("blue").toUpperCase();
|
||||
const isValidHex1 = /^[0-9A-F]{6}$/.test(hex1)
|
||||
assert.isTrue(isValidHex1);
|
||||
|
||||
const r1 = parseInt(hex1.slice(0, 2), 16);
|
||||
const g1 = parseInt(hex1.slice(2, 4), 16);
|
||||
const b1 = parseInt(hex1.slice(4, 6), 16);
|
||||
|
||||
assert.isAbove(b1, r1);
|
||||
assert.isAbove(b1, g1);
|
||||
|
||||
const hex2 = generateHex("blue").toUpperCase();
|
||||
const isValidHex2 = /^[0-9A-F]{6}$/.test(hex2);
|
||||
assert.isTrue(isValidHex2);
|
||||
|
||||
const r2 = parseInt(hex2.slice(0, 2), 16);
|
||||
const g2 = parseInt(hex2.slice(2, 4), 16);
|
||||
const b2 = parseInt(hex2.slice(4, 6), 16);
|
||||
|
||||
assert.isAbove(b2, r2);
|
||||
assert.isAbove(b2, g2);
|
||||
assert.notEqual(hex1, hex2);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function generateHex(color) {
|
||||
|
||||
return color;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function generateHex(color) {
|
||||
const toHex = n => n.toString(16).padStart(2, "0").toUpperCase();
|
||||
|
||||
const dominant = Math.floor(Math.random() * 86) + 170;
|
||||
const weak1 = Math.floor(Math.random() * 170);
|
||||
const weak2 = Math.floor(Math.random() * 170);
|
||||
|
||||
let r, g, b;
|
||||
|
||||
switch (color) {
|
||||
case "red":
|
||||
r = dominant;
|
||||
g = weak1;
|
||||
b = weak2;
|
||||
break;
|
||||
case "green":
|
||||
r = weak1;
|
||||
g = dominant;
|
||||
b = weak2;
|
||||
break;
|
||||
case "blue":
|
||||
r = weak1;
|
||||
g = weak2;
|
||||
b = dominant;
|
||||
break;
|
||||
default:
|
||||
return "Invalid color";
|
||||
}
|
||||
|
||||
return `${toHex(r)}${toHex(g)}${toHex(b)}`;
|
||||
}
|
||||
```
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
---
|
||||
id: 6821ebf8237de8297eaee798
|
||||
title: "Challenge 22: Tribonacci Sequence"
|
||||
challengeType: 28
|
||||
dashedName: challenge-22
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The Tribonacci sequence is a series of numbers where each number is the sum of the three preceding ones. When starting with `0`, `0` and `1`, the first 10 numbers in the sequence are `0`, `0`, `1`, `1`, `2`, `4`, `7`, `13`, `24`, `44`.
|
||||
|
||||
Given an array containing the first three numbers of a Tribonacci sequence, and an integer representing the length of the sequence, return an array containing the sequence of the given length.
|
||||
|
||||
- Your function should handle sequences of any length greater than or equal to zero.
|
||||
- If the length is zero, return an empty array.
|
||||
- Note that the starting numbers are part of the sequence.
|
||||
|
||||
# --hints--
|
||||
|
||||
`tribonacciSequence([0, 0, 1], 20)` should return `[0, 0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149, 274, 504, 927, 1705, 3136, 5768, 10609, 19513]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(tribonacciSequence([0, 0, 1], 20), [0, 0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149, 274, 504, 927, 1705, 3136, 5768, 10609, 19513]);
|
||||
```
|
||||
|
||||
`tribonacciSequence([21, 32, 43], 1)` should return `[21]`.
|
||||
|
||||
|
||||
```js
|
||||
assert.deepEqual(tribonacciSequence([21, 32, 43], 1), [21]);
|
||||
```
|
||||
|
||||
`tribonacciSequence([0, 0, 1], 0)` should return `[]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(tribonacciSequence([0, 0, 1], 0), []);
|
||||
```
|
||||
|
||||
`tribonacciSequence([10, 20, 30], 2)` should return `[10, 20]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(tribonacciSequence([10, 20, 30], 2), [10, 20]);
|
||||
```
|
||||
|
||||
`tribonacciSequence([10, 20, 30], 3)` should return `[10, 20, 30]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(tribonacciSequence([10, 20, 30], 3), [10, 20, 30]);
|
||||
```
|
||||
|
||||
`tribonacciSequence([123, 456, 789], 8)` should return `[123, 456, 789, 1368, 2613, 4770, 8751, 16134]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(tribonacciSequence([123, 456, 789], 8), [123, 456, 789, 1368, 2613, 4770, 8751, 16134]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function tribonacciSequence(startSequence, length) {
|
||||
|
||||
return length;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function tribonacciSequence(startSequence, length) {
|
||||
if (length === 0) return [];
|
||||
if (length === 1) return [startSequence[0]];
|
||||
if (length === 2) return [startSequence[0], startSequence[1]];
|
||||
if (length === 3) return [...startSequence];
|
||||
|
||||
const sequence = [...startSequence];
|
||||
while (sequence.length < length) {
|
||||
const nextValue = sequence[sequence.length - 1] + sequence[sequence.length - 2] + + sequence[sequence.length - 3];
|
||||
sequence.push(nextValue);
|
||||
}
|
||||
return sequence;
|
||||
}
|
||||
```
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
---
|
||||
id: 6821ebfd237de8297eaee799
|
||||
title: "Challenge 23: RGB to Hex"
|
||||
challengeType: 28
|
||||
dashedName: challenge-23
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a CSS `rgb(r, g, b)` color string, return its hexadecimal equivalent.
|
||||
|
||||
Here are some example outputs for a given input:
|
||||
|
||||
| Input | Output |
|
||||
|---------|----------|
|
||||
| `"rgb(255, 255, 255)"`| `"#ffffff"` |
|
||||
| `"rgb(1, 2, 3)"` | `"#010203"` |
|
||||
|
||||
- Make any letters lowercase.
|
||||
- Return a `#` followed by six characters. Don't use any shorthand values.
|
||||
|
||||
# --hints--
|
||||
|
||||
`rgbToHex("rgb(255, 255, 255)")` should return `"#ffffff"`.
|
||||
|
||||
```js
|
||||
assert.equal(rgbToHex("rgb(255, 255, 255)"), "#ffffff");
|
||||
```
|
||||
|
||||
`rgbToHex("rgb(1, 11, 111)")` should return `"#010b6f"`.
|
||||
|
||||
```js
|
||||
assert.equal(rgbToHex("rgb(1, 11, 111)"), "#010b6f");
|
||||
```
|
||||
|
||||
`rgbToHex("rgb(173, 216, 230)")` should return `"#add8e6"`.
|
||||
|
||||
```js
|
||||
assert.equal(rgbToHex("rgb(173, 216, 230)"), "#add8e6");
|
||||
```
|
||||
|
||||
`rgbToHex("rgb(79, 123, 201)")` should return `"#4f7bc9"`.
|
||||
|
||||
```js
|
||||
assert.equal(rgbToHex("rgb(79, 123, 201)"), "#4f7bc9");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function rgbToHex(rgb) {
|
||||
|
||||
return rgb;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function rgbToHex(rgb) {
|
||||
const match = rgb.match(/\d+/g);
|
||||
const [r, g, b] = match.map(num =>
|
||||
Math.max(0, Math.min(255, parseInt(num)))
|
||||
.toString(16)
|
||||
.padStart(2, '0')
|
||||
);
|
||||
|
||||
return `#${r}${g}${b}`;
|
||||
}
|
||||
```
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
---
|
||||
id: 6821ec02237de8297eaee79a
|
||||
title: "Challenge 24: Pangram"
|
||||
challengeType: 28
|
||||
dashedName: challenge-24
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a word or sentence and a string of lowercase letters, determine if the word or sentence uses all the letters from the given set at least once and no other letters.
|
||||
|
||||
- Ignore non-alphabetical characters in the word or sentence.
|
||||
- Ignore letter casing in the word or sentence.
|
||||
|
||||
# --hints--
|
||||
|
||||
`isPangram("hello", "helo")` should return `true`
|
||||
|
||||
```js
|
||||
assert.isTrue(isPangram("hello", "helo"));
|
||||
```
|
||||
|
||||
`isPangram("hello", "hel")` should return `false`
|
||||
|
||||
```js
|
||||
assert.isFalse(isPangram("hello", "hel"));
|
||||
```
|
||||
|
||||
`isPangram("hello", "helow")` should return `false`
|
||||
|
||||
```js
|
||||
assert.isFalse(isPangram("hello", "helow"));
|
||||
```
|
||||
|
||||
`isPangram("hello world", "helowrd")` should return `true`
|
||||
|
||||
```js
|
||||
assert.isTrue(isPangram("hello world", "helowrd"));
|
||||
```
|
||||
|
||||
`isPangram("Hello World!", "helowrd")` should return `true`
|
||||
|
||||
```js
|
||||
assert.isTrue(isPangram("Hello World!", "helowrd"));
|
||||
```
|
||||
|
||||
`isPangram("Hello World!", "heliowrd")` should return `false`
|
||||
|
||||
```js
|
||||
assert.isFalse(isPangram("Hello World!", "heliowrd"));
|
||||
```
|
||||
|
||||
`isPangram("freeCodeCamp", "frcdmp")` should return `false`
|
||||
|
||||
```js
|
||||
assert.isFalse(isPangram("freeCodeCamp", "frcdmp"));
|
||||
```
|
||||
|
||||
`isPangram("The quick brown fox jumps over the lazy dog.", "abcdefghijklmnopqrstuvwxyz")` should return `true`
|
||||
|
||||
```js
|
||||
assert.isTrue(isPangram("The quick brown fox jumps over the lazy dog.", "abcdefghijklmnopqrstuvwxyz"));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function isPangram(sentence, letters) {
|
||||
|
||||
return sentence;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function isPangram(sentence, letters) {
|
||||
const usedLetters = [];
|
||||
for (let i = 0; i < sentence.length; i++) {
|
||||
const letter = sentence[i].toLowerCase();
|
||||
if (!usedLetters.includes(letter) && /[a-z]/.test(letter)) {
|
||||
usedLetters.push(letter);
|
||||
}
|
||||
}
|
||||
|
||||
const sortedLetters = letters.split('').sort().join('');
|
||||
const sortedUsedLetters = usedLetters.sort().join('');
|
||||
|
||||
return sortedLetters === sortedUsedLetters;
|
||||
}
|
||||
```
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
---
|
||||
id: 68adce01c0e1144d0a902956
|
||||
title: "Challenge 25: Vowel Repeater"
|
||||
challengeType: 28
|
||||
dashedName: challenge-25
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string, return a new version of the string where each vowel is duplicated one more time than the previous vowel you encountered. For instance, the first vowel in the sentence should remain unchanged. The second vowel should appear twice in a row. The third vowel should appear three times in a row, and so on.
|
||||
|
||||
- The letters `a`, `e`, `i`, `o`, and `u`, in either uppercase or lowercase, are considered vowels.
|
||||
- The original vowel should keeps its case.
|
||||
- Repeated vowels should be lowercase.
|
||||
- All non-vowel characters should keep their original case.
|
||||
|
||||
# --hints--
|
||||
|
||||
`repeatVowels("hello world")` should return `"helloo wooorld"`.
|
||||
|
||||
```js
|
||||
assert.equal(repeatVowels("hello world"), "helloo wooorld");
|
||||
```
|
||||
|
||||
`repeatVowels("freeCodeCamp")` should return `"freeeCooodeeeeCaaaaamp"`.
|
||||
|
||||
```js
|
||||
assert.equal(repeatVowels("freeCodeCamp"), "freeeCooodeeeeCaaaaamp");
|
||||
```
|
||||
|
||||
`repeatVowels("AEIOU")` should return `"AEeIiiOoooUuuuu"`.
|
||||
|
||||
```js
|
||||
assert.equal(repeatVowels("AEIOU"), "AEeIiiOoooUuuuu");
|
||||
```
|
||||
|
||||
`repeatVowels("I like eating ice cream in Iceland")` should return `"I liikeee eeeeaaaaatiiiiiing iiiiiiiceeeeeeee creeeeeeeeeaaaaaaaaaam iiiiiiiiiiin Iiiiiiiiiiiiceeeeeeeeeeeeelaaaaaaaaaaaaaand"`.
|
||||
|
||||
```js
|
||||
assert.equal(repeatVowels("I like eating ice cream in Iceland"), "I liikeee eeeeaaaaatiiiiiing iiiiiiiceeeeeeee creeeeeeeeeaaaaaaaaaam iiiiiiiiiiin Iiiiiiiiiiiiceeeeeeeeeeeeelaaaaaaaaaaaaaand");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function repeatVowels(str) {
|
||||
|
||||
return str;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function repeatVowels(str) {
|
||||
const vowels = "aeiouAEIOU";
|
||||
let count = 0;
|
||||
let result = "";
|
||||
|
||||
for (let char of str) {
|
||||
result += char;
|
||||
if (vowels.includes(char)) {
|
||||
result += char.repeat(count).toLowerCase();
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
```
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
---
|
||||
id: 68adce01c0e1144d0a902958
|
||||
title: "Challenge 26: IPv4 Validator"
|
||||
challengeType: 28
|
||||
dashedName: challenge-26
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string, determine if it is a valid IPv4 Address. A valid IPv4 address consists of four integer numbers separated by dots (`.`). Each number must satisfy the following conditions:
|
||||
|
||||
- It is between 0 and 255 inclusive.
|
||||
- It does not have leading zeros (e.g. 0 is allowed, 01 is not).
|
||||
- Only numeric characters are allowed.
|
||||
|
||||
# --hints--
|
||||
|
||||
`isValidIPv4("192.168.1.1")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isValidIPv4("192.168.1.1"));
|
||||
```
|
||||
|
||||
`isValidIPv4("0.0.0.0")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isValidIPv4("0.0.0.0"));
|
||||
```
|
||||
|
||||
`isValidIPv4("255.01.50.111")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isValidIPv4("255.01.50.111"));
|
||||
```
|
||||
|
||||
`isValidIPv4("255.00.50.111")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isValidIPv4("255.00.50.111"));
|
||||
```
|
||||
|
||||
`isValidIPv4("256.101.50.115")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isValidIPv4("256.101.50.115"));
|
||||
```
|
||||
|
||||
`isValidIPv4("192.168.101.")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isValidIPv4("192.168.101."));
|
||||
```
|
||||
|
||||
`isValidIPv4("192168145213")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isValidIPv4("192168145213"));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function isValidIPv4(ipv4) {
|
||||
|
||||
return ipv4;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function isValidIPv4(ipv4) {
|
||||
const parts = ipv4.split(".");
|
||||
|
||||
if (parts.length !== 4) return false;
|
||||
|
||||
for (let part of parts) {
|
||||
if (!/^\d+$/.test(part)) return false;
|
||||
|
||||
const num = Number(part);
|
||||
if (num < 0 || num > 255) return false;
|
||||
|
||||
if (part.length > 1 && part.startsWith("0")) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
---
|
||||
id: 68adce01c0e1144d0a90295a
|
||||
title: "Challenge 27: Matrix Rotate"
|
||||
challengeType: 28
|
||||
dashedName: challenge-27
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a matrix (an array of arrays), rotate the matrix 90 degrees clockwise and return it. For instance, given `[[1, 2], [3, 4]]`, which looks like this:
|
||||
|
||||
| 1 | 2 |
|
||||
|---|---|
|
||||
| 3 | 4 |
|
||||
|
||||
You should return `[[3, 1], [4, 2]]`, which looks like this:
|
||||
|
||||
| 3 | 1 |
|
||||
|---|---|
|
||||
| 4 | 2 |
|
||||
|
||||
# --hints--
|
||||
|
||||
`rotate([[1]])` should return `[[1]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(rotate([[1]]), [[1]]);
|
||||
```
|
||||
|
||||
`rotate([[1, 2], [3, 4]])` should return `[[3, 1], [4, 2]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(rotate([[1, 2], [3, 4]]), [[3, 1], [4, 2]]);
|
||||
```
|
||||
|
||||
`rotate([[1, 2, 3], [4, 5, 6], [7, 8, 9]])` should return `[[7, 4, 1], [8, 5, 2], [9, 6, 3]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(rotate([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), [[7, 4, 1], [8, 5, 2], [9, 6, 3]]);
|
||||
```
|
||||
|
||||
`rotate([[0, 1, 0], [1, 0, 1], [0, 0, 0]])` should return `[[0, 1, 0], [0, 0, 1], [0, 1, 0]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(rotate([[0, 1, 0], [1, 0, 1], [0, 0, 0]]), [[0, 1, 0], [0, 0, 1], [0, 1, 0]]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function rotate(matrix) {
|
||||
|
||||
return matrix;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function rotate(matrix) {
|
||||
const n = matrix.length;
|
||||
const result = Array.from({ length: n }, () => Array(n).fill(0));
|
||||
|
||||
for (let i = 0; i < n; i++) {
|
||||
for (let j = 0; j < n; j++) {
|
||||
result[j][n - 1 - i] = matrix[i][j];
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
```
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
---
|
||||
id: 68adce01c0e1144d0a90295c
|
||||
title: "Challenge 28: Roman Numeral Parser"
|
||||
challengeType: 28
|
||||
dashedName: challenge-28
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string representing a Roman numeral, return its integer value.
|
||||
|
||||
Roman numerals consist of the following symbols and values:
|
||||
|
||||
| Symbol | Value |
|
||||
|--------|-------|
|
||||
| I | 1 |
|
||||
| V | 5 |
|
||||
| X | 10 |
|
||||
| L | 50 |
|
||||
| C | 100 |
|
||||
| D | 500 |
|
||||
| M | 1000 |
|
||||
|
||||
- Numerals are read left to right. If a smaller numeral appears before a larger one, the value is subtracted. Otherwise, values are added.
|
||||
|
||||
# --hints--
|
||||
|
||||
`parseRomanNumeral("III")` should return `3`.
|
||||
|
||||
```js
|
||||
assert.equal(parseRomanNumeral("III"), 3);
|
||||
```
|
||||
|
||||
`parseRomanNumeral("IV")` should return `4`.
|
||||
|
||||
```js
|
||||
assert.equal(parseRomanNumeral("IV"), 4);
|
||||
```
|
||||
|
||||
`parseRomanNumeral("XXVI")` should return `26`.
|
||||
|
||||
```js
|
||||
assert.equal(parseRomanNumeral("XXVI"), 26);
|
||||
```
|
||||
|
||||
`parseRomanNumeral("XCIX")` should return `99`.
|
||||
|
||||
```js
|
||||
assert.equal(parseRomanNumeral("XCIX"), 99);
|
||||
```
|
||||
|
||||
`parseRomanNumeral("CDLX")` should return `460`.
|
||||
|
||||
```js
|
||||
assert.equal(parseRomanNumeral("CDLX"), 460);
|
||||
```
|
||||
|
||||
`parseRomanNumeral("DIV")` should return `504`.
|
||||
|
||||
```js
|
||||
assert.equal(parseRomanNumeral("DIV"), 504);
|
||||
```
|
||||
|
||||
`parseRomanNumeral("MMXXV")` should return `2025`.
|
||||
|
||||
```js
|
||||
assert.equal(parseRomanNumeral("MMXXV"), 2025);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function parseRomanNumeral(numeral) {
|
||||
|
||||
return numeral;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function parseRomanNumeral(numeral) {
|
||||
const romanMap = {
|
||||
I: 1,
|
||||
V: 5,
|
||||
X: 10,
|
||||
L: 50,
|
||||
C: 100,
|
||||
D: 500,
|
||||
M: 1000
|
||||
};
|
||||
|
||||
let total = 0;
|
||||
|
||||
for (let i = 0; i < numeral.length; i++) {
|
||||
const current = romanMap[numeral[i]];
|
||||
const next = romanMap[numeral[i + 1]];
|
||||
|
||||
if (next && current < next) {
|
||||
total -= current;
|
||||
} else {
|
||||
total += current;
|
||||
}
|
||||
}
|
||||
|
||||
return total;
|
||||
}
|
||||
```
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
---
|
||||
id: 68adce01c0e1144d0a90295e
|
||||
title: "Challenge 29: Acronym Builder"
|
||||
challengeType: 28
|
||||
dashedName: challenge-29
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string containing one or more words, return an acronym of the words using the following constraints:
|
||||
|
||||
- The acronym should consist of the first letter of each word capitalized, unless otherwise noted.
|
||||
- The acronym should ignore the first letter of these words unless they are the first word of the given string: `a`, `for`, `an`, `and`, `by`, and `of`.
|
||||
- The acronym letters should be returned in the order they are given.
|
||||
- The acronym should not contain any spaces.
|
||||
|
||||
# --hints--
|
||||
|
||||
`buildAcronym("Search Engine Optimization")` should return `"SEO"`.
|
||||
|
||||
```js
|
||||
assert.equal(buildAcronym("Search Engine Optimization"), "SEO");
|
||||
```
|
||||
|
||||
`buildAcronym("Frequently Asked Questions")` should return `"FAQ"`.
|
||||
|
||||
```js
|
||||
assert.equal(buildAcronym("Frequently Asked Questions"), "FAQ");
|
||||
```
|
||||
|
||||
`buildAcronym("National Aeronautics and Space Administration")` should return `"NASA"`.
|
||||
|
||||
```js
|
||||
assert.equal(buildAcronym("National Aeronautics and Space Administration"), "NASA");
|
||||
```
|
||||
|
||||
`buildAcronym("Federal Bureau of Investigation")` should return `"FBI"`.
|
||||
|
||||
```js
|
||||
assert.equal(buildAcronym("Federal Bureau of Investigation"), "FBI");
|
||||
```
|
||||
|
||||
`buildAcronym("For your information")` should return `"FYI"`.
|
||||
|
||||
```js
|
||||
assert.equal(buildAcronym("Light Amplification by Stimulated Emission of Radiation"), "LASER");
|
||||
```
|
||||
|
||||
`buildAcronym("By the way")` should return `"BTW"`.
|
||||
|
||||
```js
|
||||
assert.equal(buildAcronym("By the way"), "BTW");
|
||||
```
|
||||
|
||||
`buildAcronym("An unstoppable herd of waddling penguins overtakes the icy mountains and sings happily")` should return `"AUHWPOTIMSH"`.
|
||||
|
||||
```js
|
||||
assert.equal(buildAcronym("An unstoppable herd of waddling penguins overtakes the icy mountains and sings happily"), "AUHWPOTIMSH");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function buildAcronym(str) {
|
||||
|
||||
return str;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function buildAcronym(str) {
|
||||
const smallWords = ["a", "for", "an", "and", "by", "of"];
|
||||
const words = str.split(" ");
|
||||
let acronym = "";
|
||||
|
||||
for (let i = 0; i < words.length; i++) {
|
||||
const word = words[i];
|
||||
const lowerWord = word.toLowerCase();
|
||||
|
||||
if (i === 0 || !smallWords.includes(lowerWord)) {
|
||||
acronym += word[0].toUpperCase();
|
||||
}
|
||||
}
|
||||
|
||||
return acronym;
|
||||
}
|
||||
```
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
---
|
||||
id: 68af0687ef34c76c28ffa547
|
||||
title: "Challenge 30: Unique Characters"
|
||||
challengeType: 28
|
||||
dashedName: challenge-30
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string, determine if all the characters in the string are unique.
|
||||
|
||||
- Uppercase and lowercase letters should be considered different characters.
|
||||
|
||||
# --hints--
|
||||
|
||||
`allUnique("abc")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(allUnique("abc"));
|
||||
```
|
||||
|
||||
`allUnique("aA")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(allUnique("aA"));
|
||||
```
|
||||
|
||||
`allUnique("QwErTy123!@")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(allUnique("QwErTy123!@"));
|
||||
```
|
||||
|
||||
`allUnique("~!@#$%^&*()_+")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(allUnique("~!@#$%^&*()_+"));
|
||||
```
|
||||
|
||||
`allUnique("hello")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(allUnique("hello"));
|
||||
```
|
||||
|
||||
`allUnique("freeCodeCamp")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(allUnique("freeCodeCamp"));
|
||||
```
|
||||
|
||||
`allUnique("!@#*$%^&*()aA")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(allUnique("!@#*$%^&*()aA"));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function allUnique(str) {
|
||||
|
||||
return str;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function allUnique(str) {
|
||||
let seen = '';
|
||||
for (let char of str) {
|
||||
if (seen.includes(char)) {
|
||||
return false;
|
||||
}
|
||||
seen += char;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
```
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
---
|
||||
id: 68af0687ef34c76c28ffa549
|
||||
title: "Challenge 31: Array Diff"
|
||||
challengeType: 28
|
||||
dashedName: challenge-31
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given two arrays with strings values, return a new array containing all the values that appear in only one of the arrays.
|
||||
|
||||
- The returned array should be sorted in alphabetical order.
|
||||
|
||||
# --hints--
|
||||
|
||||
`arrayDiff(["apple", "banana"], ["apple", "banana", "cherry"])` should return `["cherry"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(arrayDiff(["apple", "banana"], ["apple", "banana", "cherry"]), ["cherry"]);
|
||||
```
|
||||
|
||||
`arrayDiff(["apple", "banana", "cherry"], ["apple", "banana"])` should return `["cherry"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(arrayDiff(["apple", "banana", "cherry"], ["apple", "banana"]), ["cherry"]);
|
||||
```
|
||||
|
||||
`arrayDiff(["one", "two", "three", "four", "six"], ["one", "three", "eight"])` should return `["eight", "four", "six", "two"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(arrayDiff(["one", "two", "three", "four", "six"], ["one", "three", "eight"]), ["eight", "four", "six", "two"]);
|
||||
```
|
||||
|
||||
`arrayDiff(["two", "four", "five", "eight"], ["one", "two", "three", "four", "seven", "eight"])` should return `["five", "one", "seven", "three"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(arrayDiff(["two", "four", "five", "eight"], ["one", "two", "three", "four", "seven", "eight"]), ["five", "one", "seven", "three"]);
|
||||
```
|
||||
|
||||
`arrayDiff(["I", "like", "freeCodeCamp"], ["I", "like", "rocks"])` should return `["freeCodeCamp", "rocks"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(arrayDiff(["I", "like", "freeCodeCamp"], ["I", "like", "rocks"]), ["freeCodeCamp", "rocks"]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function arrayDiff(arr1, arr2) {
|
||||
|
||||
return arr1;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function arrayDiff(arr1, arr2) {
|
||||
let unique1 = arr1.filter((v, i) => arr1.indexOf(v) === i);
|
||||
let unique2 = arr2.filter((v, i) => arr2.indexOf(v) === i);
|
||||
|
||||
let only1 = unique1.filter(v => !unique2.includes(v));
|
||||
let only2 = unique2.filter(v => !unique1.includes(v));
|
||||
|
||||
return [...only1, ...only2].sort();
|
||||
}
|
||||
```
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
---
|
||||
id: 68af0687ef34c76c28ffa54b
|
||||
title: "Challenge 32: Reverse Sentence"
|
||||
challengeType: 28
|
||||
dashedName: challenge-32
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string of words, return a new string with the words in reverse order. For example, the first word should be at the end of the returned string, and the last word should be at the beginning of the returned string.
|
||||
|
||||
- In the given string, words can be separated by one or more spaces.
|
||||
- The returned string should only have one space between words.
|
||||
|
||||
# --hints--
|
||||
|
||||
`reverseSentence("world hello")` should return `"hello world"`.
|
||||
|
||||
```js
|
||||
assert.equal(reverseSentence("world hello"), "hello world");
|
||||
```
|
||||
|
||||
`reverseSentence("push commit git")` should return `"git commit push"`.
|
||||
|
||||
```js
|
||||
assert.equal(reverseSentence("push commit git"), "git commit push");
|
||||
```
|
||||
|
||||
`reverseSentence("npm install sudo")` should return `"sudo install npm"`.
|
||||
|
||||
```js
|
||||
assert.equal(reverseSentence("npm install apt sudo"), "sudo apt install npm");
|
||||
```
|
||||
|
||||
`reverseSentence("import default function export")` should return `"export function default import"`.
|
||||
|
||||
```js
|
||||
assert.equal(reverseSentence("import default function export"), "export function default import");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function reverseSentence(sentence) {
|
||||
|
||||
return sentence;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function reverseSentence(sentence) {
|
||||
return sentence.split(/\s+/).reverse().join(" ");
|
||||
}
|
||||
```
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
---
|
||||
id: 68af0687ef34c76c28ffa54d
|
||||
title: "Challenge 33: Screen Time"
|
||||
challengeType: 28
|
||||
dashedName: challenge-33
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given an input array of seven integers, representing a week's time, where each integer is the amount of hours spent on your phone that day, determine if it is too much screen time based on these constraints:
|
||||
|
||||
- If any single day has 10 hours or more, it's too much.
|
||||
- If the average of any three days in a row is greater than or equal to 8 hours, it’s too much.
|
||||
- If the average of the seven days is greater than or equal to 6 hours, it's too much.
|
||||
|
||||
# --hints--
|
||||
|
||||
`tooMuchScreenTime([1, 2, 3, 4, 5, 6, 7])` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(tooMuchScreenTime([1, 2, 3, 4, 5, 6, 7]));
|
||||
```
|
||||
|
||||
`tooMuchScreenTime([7, 8, 8, 4, 2, 2, 3])` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(tooMuchScreenTime([7, 8, 8, 4, 2, 2, 3]));
|
||||
```
|
||||
|
||||
`tooMuchScreenTime([5, 6, 6, 6, 6, 6, 6])` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(tooMuchScreenTime([5, 6, 6, 6, 6, 6, 6]));
|
||||
```
|
||||
|
||||
`tooMuchScreenTime([1, 2, 3, 11, 1, 3, 4])` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(tooMuchScreenTime([1, 2, 3, 11, 1, 3, 4]));
|
||||
```
|
||||
|
||||
`tooMuchScreenTime([1, 2, 3, 10, 2, 1, 0])` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(tooMuchScreenTime([1, 2, 3, 10, 2, 1, 0]));
|
||||
```
|
||||
|
||||
`tooMuchScreenTime([3, 3, 5, 8, 8, 9, 4])` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(tooMuchScreenTime([3, 3, 5, 8, 8, 9, 4]));
|
||||
```
|
||||
|
||||
`tooMuchScreenTime([3, 9, 4, 8, 5, 7, 6])` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(tooMuchScreenTime([3, 9, 4, 8, 5, 7, 6]));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function tooMuchScreenTime(hours) {
|
||||
|
||||
return hours;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function tooMuchScreenTime(hours) {
|
||||
for (let h of hours) {
|
||||
if (h >= 10) return true;
|
||||
}
|
||||
|
||||
for (let i = 0; i <= 4; i++) {
|
||||
const avg3 = (hours[i] + hours[i+1] + hours[i+2]) / 3;
|
||||
if (avg3 >= 8) return true;
|
||||
}
|
||||
|
||||
const weeklyAvg = hours.reduce((sum, h) => sum + h, 0) / 7;
|
||||
if (weeklyAvg >= 6) return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
```
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
---
|
||||
id: 68af0687ef34c76c28ffa54f
|
||||
title: "Challenge 34: Missing Numbers"
|
||||
challengeType: 28
|
||||
dashedName: challenge-34
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given an array of integers from 1 to `n`, inclusive, return an array of all the missing integers between 1 and `n` (where `n` is the largest number in the given array).
|
||||
|
||||
- The given array may be unsorted and may contain duplicates.
|
||||
- The returned array should be in ascending order.
|
||||
- If no integers are missing, return an empty array.
|
||||
|
||||
# --hints--
|
||||
|
||||
`findMissingNumbers([1, 3, 5])` should return `[2, 4]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(findMissingNumbers([1, 3, 5]), [2, 4]);
|
||||
```
|
||||
|
||||
`findMissingNumbers([1, 2, 3, 4, 5])` should return `[]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(findMissingNumbers([1, 2, 3, 4, 5]), []);
|
||||
```
|
||||
|
||||
`findMissingNumbers([1, 10])` should return `[2, 3, 4, 5, 6, 7, 8, 9]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(findMissingNumbers([1, 10]), [2, 3, 4, 5, 6, 7, 8, 9]);
|
||||
```
|
||||
|
||||
`findMissingNumbers([10, 1, 10, 1, 10, 1])` should return `[2, 3, 4, 5, 6, 7, 8, 9]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(findMissingNumbers([10, 1, 10, 1, 10, 1]), [2, 3, 4, 5, 6, 7, 8, 9]);
|
||||
```
|
||||
|
||||
`findMissingNumbers([3, 1, 4, 1, 5, 9])` should return `[2, 6, 7, 8]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(findMissingNumbers([1, 2, 3, 4, 5]), []);
|
||||
```
|
||||
|
||||
`findMissingNumbers([1, 2, 3, 4, 5, 7, 8, 9, 10, 12, 6, 8, 9, 3, 2, 10, 7, 4])` should return `[11]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(findMissingNumbers([1, 2, 3, 4, 5, 7, 8, 9, 10, 12, 6, 8, 9, 3, 2, 10, 7, 4]), [11]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function findMissingNumbers(arr) {
|
||||
|
||||
return arr;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function findMissingNumbers(arr) {
|
||||
if (arr.length === 0) return [];
|
||||
|
||||
const n = Math.max(...arr);
|
||||
const set = new Set(arr);
|
||||
const result = [];
|
||||
|
||||
for (let i = 1; i <= n; i++) {
|
||||
if (!set.has(i)) {
|
||||
result.push(i);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
```
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
---
|
||||
id: 68b06e589bf227324381476f
|
||||
title: "Challenge 35: Word Frequency"
|
||||
challengeType: 28
|
||||
dashedName: challenge-35
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a paragraph, return an array of the three most frequently occurring words.
|
||||
|
||||
- Words in the paragraph will be separated by spaces.
|
||||
- Ignore case in the given paragraph. For example, treat `Hello` and `hello` as the same word.
|
||||
- Ignore punctuation in the given paragraph. Punctuation consists of commas (`,`), periods (`.`), and exclamation points (`!`).
|
||||
- The returned array should have all lowercase words.
|
||||
- The returned array should be in descending order with the most frequently occurring word first.
|
||||
|
||||
# --hints--
|
||||
|
||||
`getWords("Coding in Python is fun because coding Python allows for coding in Python easily while coding")` should return `["coding", "python", "in"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(getWords("Coding in Python is fun because coding Python allows for coding in Python easily while coding"), ["coding", "python", "in"]);
|
||||
```
|
||||
|
||||
`getWords("I like coding. I like testing. I love debugging!")` should return `["i", "like", "coding"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(getWords("I like coding. I like testing. I love debugging!"), ["i", "like", "coding"]);
|
||||
```
|
||||
|
||||
`getWords("Debug, test, deploy. Debug, debug, test, deploy. Debug, test, test, deploy!")` should return `["debug", "test", "deploy"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(getWords("Debug, test, deploy. Debug, debug, test, deploy. Debug, test, test, deploy!"), ["debug", "test", "deploy"]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function getWords(paragraph) {
|
||||
|
||||
return paragraph;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function getWords(paragraph) {
|
||||
const cleaned = paragraph.replace(/[.,!]/g, "").toLowerCase();
|
||||
const words = cleaned.split(/\s+/);
|
||||
|
||||
const freq = {};
|
||||
for (const word of words) {
|
||||
if (word) {
|
||||
freq[word] = (freq[word] || 0) + 1;
|
||||
}
|
||||
}
|
||||
|
||||
const sorted = Object.keys(freq).sort((a, b) => freq[b] - freq[a]);
|
||||
return sorted.slice(0, 3);
|
||||
}
|
||||
```
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
---
|
||||
id: 68b06e589bf2273243814771
|
||||
title: "Challenge 36: Thermostat Adjuster"
|
||||
challengeType: 28
|
||||
dashedName: challenge-36
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given the current temperature of a room and a target temperature, return a string indicating how to adjust the room temperature based on these constraints:
|
||||
|
||||
- Return `"heat"` if the current temperature is below the target.
|
||||
- Return `"cool"` if the current temperature is above the target.
|
||||
- Return `"hold"` if the current temperature is equal to the target.
|
||||
|
||||
# --hints--
|
||||
|
||||
`adjustThermostat(68, 72)` should return `"heat"`.
|
||||
|
||||
```js
|
||||
assert.equal(adjustThermostat(68, 72), "heat");
|
||||
```
|
||||
|
||||
`adjustThermostat(75, 72)` should return `"cool"`.
|
||||
|
||||
```js
|
||||
assert.equal(adjustThermostat(75, 72), "cool");
|
||||
```
|
||||
|
||||
`adjustThermostat(72, 72)` should return `"hold"`.
|
||||
|
||||
```js
|
||||
assert.equal(adjustThermostat(72, 72), "hold");
|
||||
```
|
||||
|
||||
`adjustThermostat(-20.5, -10.1)` should return `"heat"`.
|
||||
|
||||
```js
|
||||
assert.equal(adjustThermostat(-20.5, -10.1), "heat");
|
||||
```
|
||||
|
||||
`adjustThermostat(100, 99.9)` should return `"cool"`.
|
||||
|
||||
```js
|
||||
assert.equal(adjustThermostat(100, 99.9), "cool");
|
||||
```
|
||||
|
||||
`adjustThermostat(0.0, 0.0)` should return `"hold"`.
|
||||
|
||||
```js
|
||||
assert.equal(adjustThermostat(0.0, 0.0), "hold");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function adjustThermostat(temp, target) {
|
||||
|
||||
return temp;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function adjustThermostat(temp, target) {
|
||||
if (temp < target) {
|
||||
return "heat";
|
||||
} else if (temp > target) {
|
||||
return "cool";
|
||||
} else {
|
||||
return "hold";
|
||||
}
|
||||
}
|
||||
```
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
---
|
||||
id: 68b06e589bf2273243814773
|
||||
title: "Challenge 37: Sentence Capitalizer"
|
||||
challengeType: 28
|
||||
dashedName: challenge-37
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a paragraph, return a new paragraph where the first letter of each sentence is capitalized.
|
||||
|
||||
- All other characters should be preserved.
|
||||
- Sentences can end with a period (`.`), one or more question marks (`?`), or one or more exclamation points (`!`).
|
||||
|
||||
# --hints--
|
||||
|
||||
`capitalize("this is a simple sentence.")` should return `"This is a simple sentence."`.
|
||||
|
||||
```js
|
||||
assert.equal(capitalize("this is a simple sentence."), "This is a simple sentence.");
|
||||
```
|
||||
|
||||
`capitalize("hello world. how are you?")` should return `"Hello world. How are you?"`.
|
||||
|
||||
```js
|
||||
assert.equal(capitalize("hello world. how are you?"), "Hello world. How are you?");
|
||||
```
|
||||
|
||||
`capitalize("i did today's coding challenge... it was fun!!")` should return `"I did today's coding challenge... It was fun!!"`.
|
||||
|
||||
```js
|
||||
assert.equal(capitalize("i did today's coding challenge... it was fun!!"), "I did today's coding challenge... It was fun!!");
|
||||
```
|
||||
|
||||
`capitalize("crazy!!!strange???unconventional...sentences.")` should return `"Crazy!!!Strange???Unconventional...Sentences."`.
|
||||
|
||||
```js
|
||||
assert.equal(capitalize("crazy!!!strange???unconventional...sentences."), "Crazy!!!Strange???Unconventional...Sentences.");
|
||||
```
|
||||
|
||||
`capitalize("there's a space before this period . why is there a space before that period ?")` should return `"There's a space before this period . Why is there a space before that period ?"`.
|
||||
|
||||
```js
|
||||
assert.equal(capitalize("there's a space before this period . why is there a space before that period ?"), "There's a space before this period . Why is there a space before that period ?");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function capitalize(paragraph) {
|
||||
|
||||
return paragraph;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function capitalize(paragraph) {
|
||||
return paragraph.replace(/([.!?]+)(\s*)([a-z])/g, (match, punc, spaces, char) => {
|
||||
return punc + spaces + char.toUpperCase();
|
||||
})
|
||||
.replace(/^([a-z])/, (match, char) => char.toUpperCase());
|
||||
}
|
||||
```
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
---
|
||||
id: 68b06e589bf2273243814775
|
||||
title: "Challenge 38: Slug Generator"
|
||||
challengeType: 28
|
||||
dashedName: challenge-38
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string, return a URL-friendly version of the string using the following constraints:
|
||||
|
||||
- All letters should be lowercase.
|
||||
- All characters that are not letters, numbers, or spaces should be removed.
|
||||
- All spaces should be replaced with the URL-encoded space code `%20`.
|
||||
- Consecutive spaces should be replaced with a single `%20`.
|
||||
- The returned string should not have leading or trailing `%20`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`generateSlug("helloWorld")` should return `"helloworld"`.
|
||||
|
||||
```js
|
||||
assert.equal(generateSlug("helloWorld"), "helloworld");
|
||||
```
|
||||
|
||||
`generateSlug("hello world!")` should return `"hello%20world"`.
|
||||
|
||||
```js
|
||||
assert.equal(generateSlug("hello world!"), "hello%20world");
|
||||
```
|
||||
|
||||
`generateSlug(" hello-world ")` should return `"helloworld"`.
|
||||
|
||||
```js
|
||||
assert.equal(generateSlug(" hello-world "), "helloworld");
|
||||
```
|
||||
|
||||
`generateSlug("hello world")` should return `"hello%20world"`.
|
||||
|
||||
```js
|
||||
assert.equal(generateSlug("hello world"), "hello%20world");
|
||||
```
|
||||
|
||||
`generateSlug(" ?H^3-1*1]0! W[0%R#1]D ")` should return `"h3110%20w0r1d"`.
|
||||
|
||||
```js
|
||||
assert.equal(generateSlug(" ?H^3-1*1]0! W[0%R#1]D "), "h3110%20w0r1d");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function generateSlug(str) {
|
||||
|
||||
return str;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function generateSlug(str) {
|
||||
let cleaned = str.replace(/[^a-zA-Z0-9 ]+/g, "");
|
||||
cleaned = cleaned.replace(/\s+/g, " ").trim();
|
||||
return cleaned.toLowerCase().replace(/ /g, "%20");
|
||||
}
|
||||
```
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
---
|
||||
id: 68b06e589bf2273243814777
|
||||
title: "Challenge 39: Fill The Tank"
|
||||
challengeType: 28
|
||||
dashedName: challenge-39
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given the size of a fuel tank, the current fuel level, and the price per gallon, return the cost to fill the tank all the way.
|
||||
|
||||
- `tankSize` is the total capacity of the tank in gallons.
|
||||
- `fuelLevel` is the current amount of fuel in the tank in gallons.
|
||||
- `pricePerGallon` is the cost of one gallon of fuel.
|
||||
- The returned value should be rounded to two decimal places in the format: `"$d.dd"`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`costToFill(20, 0, 4.00)` should return `"$80.00"`.
|
||||
|
||||
```js
|
||||
assert.equal(costToFill(20, 0, 4.00), "$80.00");
|
||||
```
|
||||
|
||||
`costToFill(15, 10, 3.50)` should return `"$17.50"`.
|
||||
|
||||
```js
|
||||
assert.equal(costToFill(15, 10, 3.50), "$17.50");
|
||||
```
|
||||
|
||||
`costToFill(18, 9, 3.25)` should return `"$29.25"`.
|
||||
|
||||
```js
|
||||
assert.equal(costToFill(18, 9, 3.25), "$29.25");
|
||||
```
|
||||
|
||||
`costToFill(12, 12, 4.99)` should return `"$0.00"`.
|
||||
|
||||
```js
|
||||
assert.equal(costToFill(12, 12, 4.99), "$0.00");
|
||||
```
|
||||
|
||||
`costToFill(15, 9.5, 3.98)` should return `"$21.89"`.
|
||||
|
||||
```js
|
||||
assert.equal(costToFill(15, 9.5, 3.98), "$21.89");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function costToFill(tankSize, fuelLevel, pricePerGallon) {
|
||||
|
||||
return tankSize;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function costToFill(tankSize, fuelLevel, pricePerGallon) {
|
||||
let gallonsNeeded = tankSize - fuelLevel;
|
||||
let cost = gallonsNeeded * pricePerGallon;
|
||||
return `$${cost.toFixed(2)}`;
|
||||
}
|
||||
```
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
---
|
||||
id: 68b1f72371a5ac895ac70a02
|
||||
title: "Challenge 40: Photo Storage"
|
||||
challengeType: 28
|
||||
dashedName: challenge-40
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a photo size in megabytes (MB), and hard drive capacity in gigabytes (GB), return the number of photos the hard drive can store using the following constraints:
|
||||
|
||||
- 1 gigabyte equals 1000 megabytes.
|
||||
- Return the number of whole photos the drive can store.
|
||||
|
||||
# --hints--
|
||||
|
||||
`numberOfPhotos(1, 1)` should return `1000`.
|
||||
|
||||
```js
|
||||
assert.equal(numberOfPhotos(1, 1), 1000);
|
||||
```
|
||||
|
||||
`numberOfPhotos(2, 1)` should return `500`.
|
||||
|
||||
```js
|
||||
assert.equal(numberOfPhotos(2, 1), 500);
|
||||
```
|
||||
|
||||
`numberOfPhotos(4, 256)` should return `64000`.
|
||||
|
||||
```js
|
||||
assert.equal(numberOfPhotos(4, 256), 64000);
|
||||
```
|
||||
|
||||
`numberOfPhotos(3.5, 750)` should return `214285`.
|
||||
|
||||
```js
|
||||
assert.equal(numberOfPhotos(3.5, 750), 214285);
|
||||
```
|
||||
|
||||
`numberOfPhotos(3.5, 5.5)` should return `1571`.
|
||||
|
||||
```js
|
||||
assert.equal(numberOfPhotos(3.5, 5.5), 1571);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function numberOfPhotos(photoSizeMb, hardDriveSizeGb) {
|
||||
|
||||
return photoSizeMb;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function numberOfPhotos(photoSizeMb, driveSizeGb) {
|
||||
const driveSizeMb = driveSizeGb * 1000;
|
||||
return Math.floor(driveSizeMb / photoSizeMb);
|
||||
}
|
||||
```
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
---
|
||||
id: 68b1f72371a5ac895ac70a04
|
||||
title: "Challenge 41: File Storage"
|
||||
challengeType: 28
|
||||
dashedName: challenge-41
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a file size, a unit for the file size, and hard drive capacity in gigabytes (GB), return the number of files the hard drive can store using the following constraints:
|
||||
|
||||
- The unit for the file size can be bytes (`"B"`), kilobytes (`"KB"`), or megabytes (`"MB"`).
|
||||
- Return the number of whole files the drive can fit.
|
||||
- Use the following conversions:
|
||||
|
||||
| Unit | Equivalent |
|
||||
|:----:|:----------:|
|
||||
| 1 B | 1 B |
|
||||
| 1 KB | 1000 B |
|
||||
| 1 MB | 1000 KB |
|
||||
| 1 GB | 1000 MB |
|
||||
|
||||
For example, given `500`, `"KB"`, and `1` as arguments, determine how many 500 KB files can fit on a 1 GB hard drive.
|
||||
|
||||
# --hints--
|
||||
|
||||
`numberOfFiles(500, "KB", 1)` should return `2000`.
|
||||
|
||||
```js
|
||||
assert.equal(numberOfFiles(500, "KB", 1), 2000);
|
||||
```
|
||||
|
||||
`numberOfFiles(50000, "B", 1)` should return `20000`.
|
||||
|
||||
```js
|
||||
assert.equal(numberOfFiles(50000, "B", 1), 20000);
|
||||
```
|
||||
|
||||
`numberOfFiles(5, "MB", 1)` should return `200`.
|
||||
|
||||
```js
|
||||
assert.equal(numberOfFiles(5, "MB", 1), 200);
|
||||
```
|
||||
|
||||
`numberOfFiles(4096, "B", 1.5)` should return `366210`.
|
||||
|
||||
```js
|
||||
assert.equal(numberOfFiles(4096, "B", 1.5), 366210);
|
||||
```
|
||||
|
||||
`numberOfFiles(220.5, "KB", 100)` should return `453514`.
|
||||
|
||||
```js
|
||||
assert.equal(numberOfFiles(220.5, "KB", 100), 453514);
|
||||
```
|
||||
|
||||
`numberOfFiles(4.5, "MB", 750)` should return `166666`.
|
||||
|
||||
```js
|
||||
assert.equal(numberOfFiles(4.5, "MB", 750), 166666);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function numberOfFiles(fileSize, fileUnit, driveSizeGb) {
|
||||
|
||||
return fileSize;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function numberOfFiles(fileSize, fileUnit, driveSizeGb) {
|
||||
const driveSizeBytes = driveSizeGb * 1000 * 1000 * 1000;
|
||||
|
||||
let fileSizeBytes;
|
||||
if (fileUnit === "B") {
|
||||
fileSizeBytes = fileSize;
|
||||
} else if (fileUnit === "KB") {
|
||||
fileSizeBytes = fileSize * 1000;
|
||||
} else {
|
||||
fileSizeBytes = fileSize * 1000 * 1000;
|
||||
}
|
||||
|
||||
return Math.floor(driveSizeBytes / fileSizeBytes);
|
||||
}
|
||||
```
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
---
|
||||
id: 68b1f72371a5ac895ac70a06
|
||||
title: "Challenge 42: Video Storage"
|
||||
challengeType: 28
|
||||
dashedName: challenge-42
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a video size, a unit for the video size, a hard drive capacity, and a unit for the hard drive, return the number of videos the hard drive can store using the following constraints:
|
||||
|
||||
- The unit for the video size can be bytes (`"B"`), kilobytes (`"KB"`), megabytes (`"MB"`), or gigabytes (`"GB"`).
|
||||
- If not given one of the video units above, return `"Invalid video unit"`.
|
||||
- The unit of the hard drive capacity can be gigabytes (`"GB"`) or terabytes (`"TB"`).
|
||||
- If not given one of the hard drive units above, return `"Invalid drive unit"`.
|
||||
- Return the number of whole videos the drive can fit.
|
||||
- Use the following conversions:
|
||||
|
||||
| Unit | Equivalent |
|
||||
|:----:|:----------:|
|
||||
| 1 B | 1 B |
|
||||
| 1 KB | 1000 B |
|
||||
| 1 MB | 1000 KB |
|
||||
| 1 GB | 1000 MB |
|
||||
| 1 TB | 1000 GB |
|
||||
|
||||
For example, given `500`, `"MB"`, `100`, and `"GB"` as arguments, determine how many 500 MB videos can fit on a 100 GB hard drive.
|
||||
|
||||
# --hints--
|
||||
|
||||
`numberOfVideos(500, "MB", 100, "GB")` should return `200`.
|
||||
|
||||
```js
|
||||
assert.equal(numberOfVideos(500, "MB", 100, "GB"), 200);
|
||||
```
|
||||
|
||||
`numberOfVideos(1, "TB", 10, "TB")` should return `"Invalid video unit"`.
|
||||
|
||||
```js
|
||||
assert.equal(numberOfVideos(1, "TB", 10, "TB"), "Invalid video unit");
|
||||
```
|
||||
|
||||
`numberOfVideos(2000, "MB", 100000, "MB")` should return `"Invalid drive unit"`.
|
||||
|
||||
```js
|
||||
assert.equal(numberOfVideos(2000, "MB", 100000, "MB"), "Invalid drive unit");
|
||||
```
|
||||
|
||||
`numberOfVideos(500000, "KB", 2, "TB")` should return `4000`.
|
||||
|
||||
```js
|
||||
assert.equal(numberOfVideos(500000, "KB", 2, "TB"), 4000);
|
||||
```
|
||||
|
||||
`numberOfVideos(1.5, "GB", 2.2, "TB")` should return `1466`.
|
||||
|
||||
```js
|
||||
assert.equal(numberOfVideos(1.5, "GB", 2.2, "TB"), 1466);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function numberOfVideos(videoSize, videoUnit, driveSize, driveUnit) {
|
||||
|
||||
return videoSize;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function numberOfVideos(videoSize, videoUnit, driveSize, driveUnit) {
|
||||
const videoUnits = { "KB": 1000, "MB": 1000 * 1000, "GB": 1000 * 1000 * 1000 };
|
||||
const driveUnits = { "GB": 1000 * 1000 * 1000, "TB": 1000 * 1000 * 1000 * 1000 };
|
||||
|
||||
if (!videoUnits[videoUnit]) return "Invalid video unit";
|
||||
if (!driveUnits[driveUnit]) return "Invalid drive unit";
|
||||
|
||||
const videoBytes = videoSize * videoUnits[videoUnit];
|
||||
const driveBytes = driveSize * driveUnits[driveUnit];
|
||||
|
||||
return Math.floor(driveBytes / videoBytes);
|
||||
}
|
||||
```
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
---
|
||||
id: 68b1f72371a5ac895ac70a08
|
||||
title: "Challenge 43: Digits vs Letters"
|
||||
challengeType: 28
|
||||
dashedName: challenge-43
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string, return `"digits"` if the string has more digits than letters, `"letters"` if it has more letters than digits, and `"tie"` if it has the same amount of digits and letters.
|
||||
|
||||
- Digits consist of `0-9`.
|
||||
- Letters consist of `a-z` in upper or lower case.
|
||||
- Ignore any other characters.
|
||||
|
||||
# --hints--
|
||||
|
||||
`digitsOrLetters("abc123")` should return `"tie"`.
|
||||
|
||||
```js
|
||||
assert.equal(digitsOrLetters("abc123"), "tie");
|
||||
```
|
||||
|
||||
`digitsOrLetters("a1b2c3d")` should return `"letters"`.
|
||||
|
||||
```js
|
||||
assert.equal(digitsOrLetters("a1b2c3d"), "letters");
|
||||
```
|
||||
|
||||
`digitsOrLetters("1a2b3c4")` should return `"digits"`.
|
||||
|
||||
```js
|
||||
assert.equal(digitsOrLetters("1a2b3c4"), "digits");
|
||||
```
|
||||
|
||||
`digitsOrLetters("abc123!@#DEF")` should return `"letters"`.
|
||||
|
||||
```js
|
||||
assert.equal(digitsOrLetters("abc123!@#DEF"), "letters");
|
||||
```
|
||||
|
||||
`digitsOrLetters("H3110 W0R1D")` should return `"digits"`.
|
||||
|
||||
```js
|
||||
assert.equal(digitsOrLetters("H3110 W0R1D"), "digits");
|
||||
```
|
||||
|
||||
`digitsOrLetters("P455W0RD")` should return `"tie"`.
|
||||
|
||||
```js
|
||||
assert.equal(digitsOrLetters("P455W0RD"), "tie");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function digitsOrLetters(str) {
|
||||
|
||||
return str;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function digitsOrLetters(str) {
|
||||
let digitCount = 0;
|
||||
let letterCount = 0;
|
||||
|
||||
for (let char of str) {
|
||||
if (/[0-9]/.test(char)) digitCount++;
|
||||
else if (/[a-zA-Z]/.test(char)) letterCount++;
|
||||
}
|
||||
|
||||
if (digitCount > letterCount) return "digits";
|
||||
if (letterCount > digitCount) return "letters";
|
||||
return "tie";
|
||||
}
|
||||
```
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
---
|
||||
id: 68b1f72371a5ac895ac70a0a
|
||||
title: "Challenge 44: String Mirror"
|
||||
challengeType: 28
|
||||
dashedName: challenge-44
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given two strings, determine if the second string is a mirror of the first.
|
||||
|
||||
- A string is considered a mirror if it contains the same letters in reverse order.
|
||||
- Treat uppercase and lowercase letters as distinct.
|
||||
- Ignore all non-alphabetical characters.
|
||||
|
||||
# --hints--
|
||||
|
||||
`isMirror("helloworld", "helloworld")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isMirror("helloworld", "helloworld"));
|
||||
```
|
||||
|
||||
`isMirror("Hello World", "dlroW olleH")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isMirror("Hello World", "dlroW olleH"));
|
||||
```
|
||||
|
||||
`isMirror("RaceCar", "raCecaR")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isMirror("RaceCar", "raCecaR"));
|
||||
```
|
||||
|
||||
`isMirror("RaceCar", "RaceCar")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isMirror("RaceCar", "RaceCar"));
|
||||
```
|
||||
|
||||
`isMirror("Mirror", "rorrim")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isMirror("Mirror", "rorrim"));
|
||||
```
|
||||
|
||||
`isMirror("Hello World", "dlroW-olleH")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isMirror("Hello World", "dlroW-olleH"));
|
||||
```
|
||||
|
||||
`isMirror("Hello World", "!dlroW !olleH")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isMirror("Hello World", "!dlroW !olleH"));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function isMirror(str1, str2) {
|
||||
|
||||
return str1;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function isMirror(str1, str2) {
|
||||
const clean1 = str1.replace(/[^a-zA-Z]/g, "");
|
||||
const clean2 = str2.replace(/[^a-zA-Z]/g, "");
|
||||
return clean1.split("").reverse().join("") === clean2;
|
||||
}
|
||||
```
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
---
|
||||
id: 68b7687dded630607aceccab
|
||||
title: "Challenge 45: Perfect Square"
|
||||
challengeType: 28
|
||||
dashedName: challenge-45
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given an integer, determine if it is a perfect square.
|
||||
|
||||
- A number is a perfect square if you can multiply an integer by itself to achieve the number. For example, 9 is a perfect square because you can multiply 3 by itself to get it.
|
||||
|
||||
# --hints--
|
||||
|
||||
`isPerfectSquare(9)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isPerfectSquare(9));
|
||||
```
|
||||
|
||||
`isPerfectSquare(49)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isPerfectSquare(49));
|
||||
```
|
||||
|
||||
`isPerfectSquare(1)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isPerfectSquare(1));
|
||||
```
|
||||
|
||||
`isPerfectSquare(2)` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isPerfectSquare(2));
|
||||
```
|
||||
|
||||
`isPerfectSquare(99)` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isPerfectSquare(99));
|
||||
```
|
||||
|
||||
`isPerfectSquare(-9)` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isPerfectSquare(-9));
|
||||
```
|
||||
|
||||
`isPerfectSquare(0)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isPerfectSquare(0));
|
||||
```
|
||||
|
||||
`isPerfectSquare(25281)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isPerfectSquare(25281));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function isPerfectSquare(n) {
|
||||
|
||||
return n;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function isPerfectSquare(n) {
|
||||
if (n < 0) return false;
|
||||
const root = Math.floor(Math.sqrt(n));
|
||||
return root * root === n;
|
||||
}
|
||||
```
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
---
|
||||
id: 68b7687dded630607aceccad
|
||||
title: "Challenge 46: 2nd Largest"
|
||||
challengeType: 28
|
||||
dashedName: challenge-46
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given an array, return the second largest distinct number.
|
||||
|
||||
# --hints--
|
||||
|
||||
`secondLargest([1, 2, 3, 4])` should return `3`.
|
||||
|
||||
```js
|
||||
assert.equal(secondLargest([1, 2, 3, 4]), 3);
|
||||
```
|
||||
|
||||
`secondLargest([20, 139, 94, 67, 31])` should return `94`.
|
||||
|
||||
```js
|
||||
assert.equal(secondLargest([20, 139, 94, 67, 31]), 94);
|
||||
```
|
||||
|
||||
`secondLargest([2, 3, 4, 6, 6])` should return `4`.
|
||||
|
||||
```js
|
||||
assert.equal(secondLargest([2, 3, 4, 6, 6]), 4);
|
||||
```
|
||||
|
||||
`secondLargest([10, -17, 55.5, 44, 91, 0])` should return `55.5`.
|
||||
|
||||
```js
|
||||
assert.equal(secondLargest([10, -17, 55.5, 44, 91, 0]), 55.5);
|
||||
```
|
||||
|
||||
`secondLargest([1, 0, -1, 0, 1, 0, -1, 1, 0])` should return `0`.
|
||||
|
||||
```js
|
||||
assert.equal(secondLargest([1, 0, -1, 0, 1, 0, -1, 1, 0]), 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function secondLargest(arr) {
|
||||
|
||||
return arr;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function secondLargest(arr) {
|
||||
const unique = [...new Set(arr)];
|
||||
unique.sort((a, b) => b - a);
|
||||
return unique[1];
|
||||
}
|
||||
```
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
---
|
||||
id: 68b7687dded630607aceccaf
|
||||
title: "Challenge 47: Caught Speeding"
|
||||
challengeType: 28
|
||||
dashedName: challenge-47
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given an array of numbers representing the speed at which vehicles were observed traveling, and a number representing the speed limit, return an array with two items, the number of vehicles that were speeding, followed by the average amount beyond the speed limit of those vehicles.
|
||||
|
||||
- If there were no vehicles speeding, return `[0, 0]`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`speeding([50, 60, 55], 60)` should return `[0, 0]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(speeding([50, 60, 55], 60), [0, 0]);
|
||||
```
|
||||
|
||||
`speeding([58, 50, 60, 55], 55)` should return `[2, 4]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(speeding([58, 50, 60, 55], 55), [2, 4]);
|
||||
```
|
||||
|
||||
`speeding([61, 81, 74, 88, 65, 71, 68], 70)` should return `[4, 8.5]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(speeding([61, 81, 74, 88, 65, 71, 68], 70), [4, 8.5]);
|
||||
```
|
||||
|
||||
`speeding([100, 105, 95, 102], 100)` should return `[2, 3.5]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(speeding([100, 105, 95, 102], 100), [2, 3.5]);
|
||||
```
|
||||
|
||||
`speeding([40, 45, 44, 50, 112, 39], 55)` should return `[1, 57]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(speeding([40, 45, 44, 50, 112, 39], 55), [1, 57]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function speeding(speeds, limit) {
|
||||
|
||||
return speeds;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function speeding(speeds, limit) {
|
||||
let speeding = 0;
|
||||
let totalOver = 0;
|
||||
|
||||
for (let speed of speeds) {
|
||||
if (speed > limit) {
|
||||
speeding++;
|
||||
totalOver += (speed - limit);
|
||||
}
|
||||
}
|
||||
|
||||
if (speeding === 0) return [0, 0];
|
||||
|
||||
return [speeding, totalOver / speeding];
|
||||
}
|
||||
```
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
---
|
||||
id: 68b7687dded630607aceccb1
|
||||
title: "Challenge 48: Spam Detector"
|
||||
challengeType: 28
|
||||
dashedName: challenge-48
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a phone number in the format `"+A (BBB) CCC-DDDD"`, where each letter represents a digit as follows:
|
||||
|
||||
- `A` represents the country code and can be any number of digits.
|
||||
- `BBB` represents the area code and will always be three digits.
|
||||
- `CCC` and `DDDD` represent the local number and will always be three and four digits long, respectively.
|
||||
|
||||
Determine if it's a spam number based on the following criteria:
|
||||
|
||||
- The country code is greater than 2 digits long or doesn't begin with a zero (`0`).
|
||||
- The area code is greater than 900 or less than 200.
|
||||
- The sum of first three digits of the local number appears within last four digits of the local number.
|
||||
- The number has the same digit four or more times in a row (ignoring the formatting characters).
|
||||
|
||||
# --hints--
|
||||
|
||||
`isSpam("+0 (200) 234-0182")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isSpam("+0 (200) 234-0182"));
|
||||
```
|
||||
|
||||
`isSpam("+091 (555) 309-1922")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isSpam("+091 (555) 309-1922"));
|
||||
```
|
||||
|
||||
`isSpam("+1 (555) 435-4792")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isSpam("+1 (555) 435-4792"));
|
||||
```
|
||||
|
||||
`isSpam("+0 (955) 234-4364")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isSpam("+0 (955) 234-4364"));
|
||||
```
|
||||
|
||||
`isSpam("+0 (155) 131-6943")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isSpam("+0 (155) 131-6943"));
|
||||
```
|
||||
|
||||
`isSpam("+0 (555) 135-0192")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isSpam("+0 (555) 135-0192"));
|
||||
```
|
||||
|
||||
`isSpam("+0 (555) 564-1987")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isSpam("+0 (555) 564-1987"));
|
||||
```
|
||||
|
||||
`isSpam("+00 (555) 234-0182")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isSpam("+00 (555) 234-0182"));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function isSpam(number) {
|
||||
|
||||
return number;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function isSpam(number) {
|
||||
const match = number.match(/^\+(\d+)\s\((\d{3})\)\s(\d{3})-(\d{4})$/);
|
||||
const [, countryCode, areaCode, ccc, dddd] = match;
|
||||
const allDigits = countryCode + areaCode + ccc + dddd;
|
||||
|
||||
if (countryCode.length > 2 || !countryCode.startsWith("0")) return true;
|
||||
|
||||
const areaNum = parseInt(areaCode, 10);
|
||||
if (areaNum > 900 || areaNum < 200) return true;
|
||||
|
||||
const sumCCC = ccc.split("").reduce((a, b) => a + parseInt(b), 0);
|
||||
if (dddd.includes(sumCCC.toString())) return true;
|
||||
|
||||
if (/(\d)\1\1\1/.test(allDigits)) return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
```
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
---
|
||||
id: 68b7687dded630607aceccb3
|
||||
title: "Challenge 49: CSV Header Parser"
|
||||
challengeType: 28
|
||||
dashedName: challenge-49
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given the first line of a comma-separated values (CSV) file, return an array containing the headings.
|
||||
|
||||
- The first line of a CSV file contains headings separated by commas.
|
||||
- Remove any leading or trailing whitespace from each heading.
|
||||
|
||||
# --hints--
|
||||
|
||||
`getHeadings("name,age,city")` should return `["name", "age", "city"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(getHeadings("name,age,city"), ["name", "age", "city"]);
|
||||
```
|
||||
|
||||
`getHeadings("first name,last name,phone")` should return `["first name", "last name", "phone"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(getHeadings("first name,last name,phone"), ["first name", "last name", "phone"]);
|
||||
```
|
||||
|
||||
`getHeadings("username , email , signup date ")` should return `["username", "email", "signup date"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(getHeadings("username , email , signup date "), ["username", "email", "signup date"]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function getHeadings(csv) {
|
||||
|
||||
return csv;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function getHeadings(csv) {
|
||||
return csv
|
||||
.split(",")
|
||||
.map(h => h.trim());
|
||||
}
|
||||
```
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
---
|
||||
id: 68b7cadffed0e75a517da66f
|
||||
title: "Challenge 50: Longest Word"
|
||||
challengeType: 28
|
||||
dashedName: challenge-50
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a sentence, return the longest word in the sentence.
|
||||
|
||||
- Ignore periods (`.`) when determining word length.
|
||||
- If multiple words are ties for the longest, return the first one that occurs.
|
||||
|
||||
# --hints--
|
||||
|
||||
`getLongestWord("coding is fun")` should return `"coding"`.
|
||||
|
||||
```js
|
||||
assert.equal(getLongestWord("coding is fun"), "coding");
|
||||
```
|
||||
|
||||
`getLongestWord("Coding challenges are fun and educational.")` should return `"educational"`.
|
||||
|
||||
```js
|
||||
assert.equal(getLongestWord("Coding challenges are fun and educational."), "educational");
|
||||
```
|
||||
|
||||
`getLongestWord("This sentence has multiple long words.")` should return `"sentence"`.
|
||||
|
||||
```js
|
||||
assert.equal(getLongestWord("This sentence has multiple long words."), "sentence");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function getLongestWord(sentence) {
|
||||
|
||||
return sentence;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function getLongestWord(sentence) {
|
||||
const words = sentence.split(' ');
|
||||
|
||||
let longest = '';
|
||||
for (let word of words) {
|
||||
const cleanWord = word.replace(/\./g, '');
|
||||
if (cleanWord.length > longest.length) {
|
||||
longest = cleanWord;
|
||||
}
|
||||
}
|
||||
|
||||
return longest;
|
||||
}
|
||||
```
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
---
|
||||
id: 68b7cadffed0e75a517da671
|
||||
title: "Challenge 51: Phone Number Formatter"
|
||||
challengeType: 28
|
||||
dashedName: challenge-51
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string of eleven digits, return the string as a phone number in this format: `"+D (DDD) DDD-DDDD"`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`formatNumber("05552340182")` should return `"+0 (555) 234-0182"`.
|
||||
|
||||
```js
|
||||
assert.equal(formatNumber("05552340182"), "+0 (555) 234-0182");
|
||||
```
|
||||
|
||||
`formatNumber("15554354792")` should return `"+1 (555) 435-4792"`.
|
||||
|
||||
```js
|
||||
assert.equal(formatNumber("15554354792"), "+1 (555) 435-4792");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function formatNumber(number) {
|
||||
|
||||
return number;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function formatNumber(number) {
|
||||
const country = number[0];
|
||||
const area = number.slice(1, 4);
|
||||
const prefix = number.slice(4, 7);
|
||||
const line = number.slice(7);
|
||||
|
||||
return `+${country} (${area}) ${prefix}-${line}`;
|
||||
}
|
||||
```
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
---
|
||||
id: 68b7cadffed0e75a517da673
|
||||
title: "Challenge 52: Binary to Decimal"
|
||||
challengeType: 28
|
||||
dashedName: challenge-52
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string representing a binary number, return its decimal equivalent as a number.
|
||||
|
||||
A binary number uses only the digits `0` and `1` to represent any number. To convert binary to decimal, multiply each digit by a power of `2` and add them together. Start by multiplying the rightmost digit by `2^0`, the next digit to the left by `2^1`, and so on. Once all digits have been multiplied by a power of `2`, add the result together.
|
||||
|
||||
For example, the binary number `101` equals `5` in decimal because:
|
||||
|
||||
```mathml
|
||||
1 * 2^2 + 0 * 2^1 + 1 * 2^0 = 4 + 0 + 1 = 5
|
||||
```
|
||||
|
||||
# --hints--
|
||||
|
||||
`toDecimal("101")` should return `5`.
|
||||
|
||||
```js
|
||||
assert.equal(toDecimal("101"), 5);
|
||||
```
|
||||
|
||||
`toDecimal("1010")` should return `10`.
|
||||
|
||||
```js
|
||||
assert.equal(toDecimal("1010"), 10);
|
||||
```
|
||||
|
||||
`toDecimal("10010")` should return `18`.
|
||||
|
||||
```js
|
||||
assert.equal(toDecimal("10010"), 18);
|
||||
```
|
||||
|
||||
`toDecimal("1010101")` should return `85`.
|
||||
|
||||
```js
|
||||
assert.equal(toDecimal("1010101"), 85);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function toDecimal(binary) {
|
||||
|
||||
return binary;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function toDecimal(binary) {
|
||||
let decimal = 0;
|
||||
for (let i = 0; i < binary.length; i++) {
|
||||
const bit = parseInt(binary[binary.length - 1 - i], 10);
|
||||
decimal += bit * Math.pow(2, i);
|
||||
}
|
||||
return decimal;
|
||||
}
|
||||
```
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
---
|
||||
id: 68b7cadffed0e75a517da675
|
||||
title: "Challenge 53: Decimal to Binary"
|
||||
challengeType: 28
|
||||
dashedName: challenge-53
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a non-negative integer, return its binary representation as a string.
|
||||
|
||||
A binary number uses only the digits `0` and `1` to represent any number. To convert a decimal number to binary, repeatedly divide the number by `2` and record the remainder. Repeat until the number is zero. Read the remainders last recorded to first. For example, to convert `12` to binary:
|
||||
|
||||
```mathml
|
||||
12 ÷ 2 = 6 remainder 0
|
||||
6 ÷ 2 = 3 remainder 0
|
||||
3 ÷ 2 = 1 remainder 1
|
||||
1 ÷ 2 = 0 remainder 1
|
||||
```
|
||||
|
||||
`12` in binary is `1100`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`toBinary(5)` should return `"101"`.
|
||||
|
||||
```js
|
||||
assert.equal(toBinary(5), "101");
|
||||
```
|
||||
|
||||
`toBinary(12)` should return `"1100"`.
|
||||
|
||||
```js
|
||||
assert.equal(toBinary(12), "1100");
|
||||
```
|
||||
|
||||
`toBinary(50)` should return `"110010"`.
|
||||
|
||||
```js
|
||||
assert.equal(toBinary(50), "110010");
|
||||
```
|
||||
|
||||
`toBinary(99)` should return `"1100011"`.
|
||||
|
||||
```js
|
||||
assert.equal(toBinary(99), "1100011");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function toBinary(decimal) {
|
||||
|
||||
return decimal;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function toBinary(decimal) {
|
||||
if (decimal === 0) return "0";
|
||||
let binary = "";
|
||||
while (decimal > 0) {
|
||||
binary = (decimal % 2) + binary;
|
||||
decimal = Math.floor(decimal / 2);
|
||||
}
|
||||
return binary;
|
||||
}
|
||||
```
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
---
|
||||
id: 68b7cadffed0e75a517da677
|
||||
title: "Challenge 54: P@ssw0rd Str3ngth!"
|
||||
challengeType: 28
|
||||
dashedName: challenge-54
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a password string, return `"weak"`, `"medium"`, or `"strong"` based on the strength of the password.
|
||||
|
||||
A password is evaluated according to the following rules:
|
||||
|
||||
- It is at least 8 characters long.
|
||||
- It contains both uppercase and lowercase letters.
|
||||
- It contains at least one number.
|
||||
- It contains at least one special character from this set: `!`, `@`, `#`, `$`, `%`, `^`, `&`, or `*`.
|
||||
|
||||
Return `"weak"` if the password meets fewer than two of the rules.
|
||||
Return `"medium"` if the password meets 2 or 3 of the rules.
|
||||
Return `"strong"` if the password meets all 4 rules.
|
||||
|
||||
# --hints--
|
||||
|
||||
`checkStrength("123456")` should return `"weak"`.
|
||||
|
||||
```js
|
||||
assert.equal(checkStrength("123456"), "weak");
|
||||
```
|
||||
|
||||
`checkStrength("pass!!!")` should return `"weak"`.
|
||||
|
||||
```js
|
||||
assert.equal(checkStrength("pass!!!"), "weak");
|
||||
```
|
||||
|
||||
`checkStrength("Qwerty")` should return `"weak"`.
|
||||
|
||||
```js
|
||||
assert.equal(checkStrength("Qwerty"), "weak");
|
||||
```
|
||||
|
||||
`checkStrength("PASSWORD")` should return `"weak"`.
|
||||
|
||||
```js
|
||||
assert.equal(checkStrength("PASSWORD"), "weak");
|
||||
```
|
||||
|
||||
`checkStrength("PASSWORD!")` should return `"medium"`.
|
||||
|
||||
```js
|
||||
assert.equal(checkStrength("PASSWORD!"), "medium");
|
||||
```
|
||||
|
||||
`checkStrength("PassWord%^!")` should return `"medium"`.
|
||||
|
||||
```js
|
||||
assert.equal(checkStrength("PassWord%^!"), "medium");
|
||||
```
|
||||
|
||||
`checkStrength("qwerty12345")` should return `"medium"`.
|
||||
|
||||
```js
|
||||
assert.equal(checkStrength("qwerty12345"), "medium");
|
||||
```
|
||||
|
||||
`checkStrength("S3cur3P@ssw0rd")` should return `"strong"`.
|
||||
|
||||
```js
|
||||
assert.equal(checkStrength("S3cur3P@ssw0rd"), "strong");
|
||||
```
|
||||
|
||||
`checkStrength("C0d3&Fun!")` should return `"strong"`.
|
||||
|
||||
```js
|
||||
assert.equal(checkStrength("C0d3&Fun!"), "strong");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function checkStrength(password) {
|
||||
|
||||
return password;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function checkStrength(password) {
|
||||
let rulesMet = 0;
|
||||
|
||||
if (password.length >= 8) rulesMet++;
|
||||
if (/[a-z]/.test(password) && /[A-Z]/.test(password)) rulesMet++;
|
||||
if (/\d/.test(password)) rulesMet++;
|
||||
if (/[!@#$%^&*]/.test(password)) rulesMet++;
|
||||
|
||||
if (rulesMet < 2) return "weak";
|
||||
if (rulesMet < 4) return "medium";
|
||||
return "strong";
|
||||
}
|
||||
```
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
---
|
||||
id: 68c1a929005bf54d342aa8d2
|
||||
title: "Challenge 55: Space Week Day 1: Stellar Classification"
|
||||
challengeType: 28
|
||||
dashedName: challenge-55
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
October 4th marks the beginning of World Space Week. The next seven days will bring you astronomy-themed coding challenges.
|
||||
|
||||
For today's challenge, you are given the surface temperature of a star in Kelvin (K) and need to determine its stellar classification based on the following ranges:
|
||||
|
||||
- `"O"`: 30,000 K or higher
|
||||
- `"B"`: 10,000 K - 29,999 K
|
||||
- `"A"`: 7,500 K - 9,999 K
|
||||
- `"F"`: 6,000 K - 7,499 K
|
||||
- `"G"`: 5,200 K - 5,999 K
|
||||
- `"K"`: 3,700 K - 5,199 K
|
||||
- `"M"`: 0 K - 3,699 K
|
||||
|
||||
- Return the classification of the given star.
|
||||
|
||||
# --hints--
|
||||
|
||||
`classification(5778)` should return `"G"`.
|
||||
|
||||
```js
|
||||
assert.equal(classification(5778), "G");
|
||||
```
|
||||
|
||||
`classification(2400)` should return `"M"`.
|
||||
|
||||
```js
|
||||
assert.equal(classification(2400), "M");
|
||||
```
|
||||
|
||||
`classification(9999)` should return `"A"`.
|
||||
|
||||
```js
|
||||
assert.equal(classification(9999), "A");
|
||||
```
|
||||
|
||||
`classification(3700)` should return `"K"`.
|
||||
|
||||
```js
|
||||
assert.equal(classification(3700), "K");
|
||||
```
|
||||
|
||||
`classification(3699)` should return `"M"`.
|
||||
|
||||
```js
|
||||
assert.equal(classification(3699), "M");
|
||||
```
|
||||
|
||||
`classification(210000)` should return `"O"`.
|
||||
|
||||
```js
|
||||
assert.equal(classification(210000), "O");
|
||||
```
|
||||
|
||||
`classification(6000)` should return `"F"`.
|
||||
|
||||
```js
|
||||
assert.equal(classification(6000), "F");
|
||||
```
|
||||
|
||||
`classification(11432)` should return `"B"`.
|
||||
|
||||
```js
|
||||
assert.equal(classification(11432), "B");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function classification(temp) {
|
||||
|
||||
return temp;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function classification(temp) {
|
||||
if (temp >= 30000) return "O";
|
||||
if (temp >= 10000) return "B";
|
||||
if (temp >= 7500) return "A";
|
||||
if (temp >= 6000) return "F";
|
||||
if (temp >= 5200) return "G";
|
||||
if (temp >= 3700) return "K";
|
||||
return "M";
|
||||
}
|
||||
```
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
---
|
||||
id: 68c1a929005bf54d342aa8d3
|
||||
title: "Challenge 56: Space Week Day 2: Exoplanet Search"
|
||||
challengeType: 28
|
||||
dashedName: challenge-56
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
For the second day of Space Week, you are given a string where each character represents the luminosity reading of a star. Determine if the readings have detected an exoplanet using the transit method. The transit method is when a planet passes in front of a star, reducing its observed luminosity.
|
||||
|
||||
- Luminosity readings only comprise of characters `0-9` and `A-Z` where each reading corresponds to the following numerical values:
|
||||
- Characters `0-9` correspond to luminosity levels `0-9`.
|
||||
- Characters `A-Z` correspond to luminosity levels `10-35`.
|
||||
|
||||
A star is considered to have an exoplanet if any single reading is less than or equal to 80% of the average of all readings. For example, if the average luminosity of a star is 10, it would be considered to have a exoplanet if any single reading is 8 or less.
|
||||
|
||||
# --hints--
|
||||
|
||||
`hasExoplanet("665544554")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(hasExoplanet("665544554"));
|
||||
```
|
||||
|
||||
`hasExoplanet("FGFFCFFGG")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(hasExoplanet("FGFFCFFGG"));
|
||||
```
|
||||
|
||||
`hasExoplanet("MONOPLONOMONPLNOMPNOMP")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(hasExoplanet("MONOPLONOMONPLNOMPNOMP"));
|
||||
```
|
||||
|
||||
`hasExoplanet("FREECODECAMP")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(hasExoplanet("FREECODECAMP"));
|
||||
```
|
||||
|
||||
`hasExoplanet("9AB98AB9BC98A")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(hasExoplanet("9AB98AB9BC98A"));
|
||||
```
|
||||
|
||||
`hasExoplanet("ZXXWYZXYWYXZEGZXWYZXYGEE")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(hasExoplanet("ZXXWYZXYWYXZEGZXWYZXYGEE"));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function hasExoplanet(readings) {
|
||||
|
||||
return readings;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function hasExoplanet(readings) {
|
||||
let total = 0;
|
||||
const values = readings.split('').map(c => parseInt(c, 36));
|
||||
|
||||
total = values.reduce((sum, v) => sum + v, 0);
|
||||
const average = total / values.length;
|
||||
const threshold = average * 0.8;
|
||||
|
||||
return values.some(v => v <= threshold);
|
||||
}
|
||||
```
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
---
|
||||
id: 68c1a929005bf54d342aa8d4
|
||||
title: "Challenge 57: Space Week Day 3: Phone Home"
|
||||
challengeType: 28
|
||||
dashedName: challenge-57
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
For day three of Space Week, you are given an array of numbers representing distances (in kilometers) between yourself, satellites, and your home planet in a communication route. Determine how long it will take a message sent through the route to reach its destination planet using the following constraints:
|
||||
|
||||
- The first value in the array is the distance from your location to the first satellite.
|
||||
- Each subsequent value, except for the last, is the distance to the next satellite.
|
||||
- The last value in the array is the distance from the previous satellite to your home planet.
|
||||
- The message travels at 300,000 km/s.
|
||||
- Each satellite the message **passes through** adds a 0.5 second transmission delay.
|
||||
- Return a number rounded to 4 decimal places, with trailing zeros removed.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sendMessage([300000, 300000])` should return `2.5`.
|
||||
|
||||
```js
|
||||
assert.equal(sendMessage([300000, 300000]), 2.5);
|
||||
```
|
||||
|
||||
`sendMessage([384400, 384400])` should return `3.0627`.
|
||||
|
||||
```js
|
||||
assert.equal(sendMessage([384400, 384400]), 3.0627);
|
||||
```
|
||||
|
||||
`sendMessage([54600000, 54600000])` should return `364.5`.
|
||||
|
||||
```js
|
||||
assert.equal(sendMessage([54600000, 54600000]), 364.5);
|
||||
```
|
||||
|
||||
`sendMessage([1000000, 500000000, 1000000])` should return `1674.3333`.
|
||||
|
||||
```js
|
||||
assert.equal(sendMessage([1000000, 500000000, 1000000]), 1674.3333);
|
||||
```
|
||||
|
||||
`sendMessage([10000, 21339, 50000, 31243, 10000])` should return `2.4086`.
|
||||
|
||||
```js
|
||||
assert.equal(sendMessage([10000, 21339, 50000, 31243, 10000]), 2.4086);
|
||||
```
|
||||
|
||||
`sendMessage([802101, 725994, 112808, 3625770, 481239])` should return `21.1597`.
|
||||
|
||||
```js
|
||||
assert.equal(sendMessage([802101, 725994, 112808, 3625770, 481239]), 21.1597);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function sendMessage(route) {
|
||||
|
||||
return route;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function sendMessage(route) {
|
||||
let totalDistance = route.reduce((a, d) => a += d, 0);
|
||||
|
||||
const delay = (route.length - 1) * 0.5
|
||||
const time = totalDistance / 300000
|
||||
const total = time + delay;
|
||||
return Number(total.toFixed(4))
|
||||
}
|
||||
```
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
---
|
||||
id: 68c1a929005bf54d342aa8d5
|
||||
title: "Challenge 58: Space Week Day 4: Landing Spot"
|
||||
challengeType: 28
|
||||
dashedName: challenge-58
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In day four of Space Week, you are given a matrix of numbers (an array of arrays), representing potential landing spots for your rover. Find the safest landing spot based on the following rules:
|
||||
|
||||
- Each spot in the matrix will contain a number from `0-9`, inclusive.
|
||||
- Any `0` represents a potential landing spot.
|
||||
- Any number other than `0` is too dangerous to land. The higher the number, the more dangerous.
|
||||
- The safest spot is defined as the `0` cell whose surrounding cells (up to 4 neighbors, ignore diagonals) have the lowest total danger.
|
||||
- Ignore out-of-bounds neighbors (corners and edges just have fewer neighbors).
|
||||
- Return the indices of the safest landing spot. There will always only be one safest spot.
|
||||
|
||||
For instance, given:
|
||||
|
||||
```js
|
||||
[
|
||||
[1, 0],
|
||||
[2, 0]
|
||||
]
|
||||
```
|
||||
|
||||
Return `[0, 1]`, the indices for the `0` in the first array.
|
||||
|
||||
# --hints--
|
||||
|
||||
`findLandingSpot([[1, 0], [2, 0]])` should return `[0, 1]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(findLandingSpot([[1, 0], [2, 0]]), [0, 1]);
|
||||
```
|
||||
|
||||
`findLandingSpot([[9, 0, 3], [7, 0, 4], [8, 0, 5]])` should return `[1, 1]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(findLandingSpot([[9, 0, 3], [7, 0, 4], [8, 0, 5]]), [1, 1]);
|
||||
```
|
||||
|
||||
`findLandingSpot([[1, 2, 1], [0, 0, 2], [3, 0, 0]])` should return `[2, 2]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(findLandingSpot([[1, 2, 1], [0, 0, 2], [3, 0, 0]]), [2, 2]);
|
||||
```
|
||||
|
||||
`findLandingSpot([[9, 6, 0, 8], [7, 1, 1, 0], [3, 0, 3, 9], [8, 6, 0, 9]])` should return `[2, 1]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(findLandingSpot([[9, 6, 0, 8], [7, 1, 1, 0], [3, 0, 3, 9], [8, 6, 0, 9]]), [2, 1]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function findLandingSpot(matrix) {
|
||||
|
||||
return matrix;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function findLandingSpot(matrix) {
|
||||
let bestSpot = null;
|
||||
let lowestNeighborSum = Infinity;
|
||||
|
||||
for (let i = 0; i < matrix.length; i++) {
|
||||
for (let j = 0; j < matrix[i].length; j++) {
|
||||
|
||||
if (matrix[i][j] === 0) {
|
||||
let currentNeighborSum = 0;
|
||||
|
||||
if (i > 0) currentNeighborSum += matrix[i - 1][j];
|
||||
if (j < matrix[i].length - 1) currentNeighborSum += matrix[i][j + 1];
|
||||
if (i < matrix.length - 1) currentNeighborSum += matrix[i + 1][j];
|
||||
if (j > 0) currentNeighborSum += matrix[i][j - 1];
|
||||
|
||||
if (currentNeighborSum < lowestNeighborSum) {
|
||||
lowestNeighborSum = currentNeighborSum;
|
||||
bestSpot = [i, j];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return bestSpot;
|
||||
}
|
||||
```
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
---
|
||||
id: 68c1a929005bf54d342aa8d6
|
||||
title: "Challenge 59: Space Week Day 5: Goldilocks Zone"
|
||||
challengeType: 28
|
||||
dashedName: challenge-59
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
For the fifth day of Space Week, you will calculate the "Goldilocks zone" of a star - the region around a star where conditions are "just right" for liquid water to exist.
|
||||
|
||||
Given the mass of a star, return an array with the start and end distances of its Goldilocks Zone in Astronomical Units.
|
||||
|
||||
To calculate the Goldilocks Zone:
|
||||
|
||||
1. Find the luminosity of the star by raising its mass to the power of 3.5.
|
||||
2. The start of the zone is 0.95 times the square root of its luminosity.
|
||||
3. The end of the zone is 1.37 times the square root of its luminosity.
|
||||
|
||||
- Return the distances rounded to two decimal places.
|
||||
|
||||
For example, given `1` as a mass, return `[0.95, 1.37]`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`goldilocksZone(1)` should return `[0.95, 1.37]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(goldilocksZone(1), [0.95, 1.37]);
|
||||
```
|
||||
|
||||
`goldilocksZone(0.5)` should return `[0.28, 0.41]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(goldilocksZone(0.5), [0.28, 0.41]);
|
||||
```
|
||||
|
||||
`goldilocksZone(6)` should return `[21.85, 31.51]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(goldilocksZone(6), [21.85, 31.51]);
|
||||
```
|
||||
|
||||
`goldilocksZone(3.7)` should return `[9.38, 13.52]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(goldilocksZone(3.7), [9.38, 13.52]);
|
||||
```
|
||||
|
||||
`goldilocksZone(20)` should return `[179.69, 259.13]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(goldilocksZone(20), [179.69, 259.13]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function goldilocksZone(mass) {
|
||||
|
||||
return mass;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function goldilocksZone(mass) {
|
||||
const luminosity = Math.pow(mass, 3.5);
|
||||
const start = 0.95 * Math.sqrt(luminosity);
|
||||
const end = 1.37 * Math.sqrt(luminosity);
|
||||
return [Number(start.toFixed(2)), Number(end.toFixed(2))];
|
||||
}
|
||||
```
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
---
|
||||
id: 68c497f3aaefc9fd9f1b0e24
|
||||
title: "Challenge 60: Space Week Day 6: Moon Phase"
|
||||
challengeType: 28
|
||||
dashedName: challenge-60
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
For day six of Space Week, you will be given a date in the format `"YYYY-MM-DD"` and need to determine the phase of the moon for that day using the following rules:
|
||||
|
||||
Use a simplified lunar cycle of 28 days, divided into four equal phases:
|
||||
|
||||
- `"New"`: days 1 - 7
|
||||
- `"Waxing"`: days 8 - 14
|
||||
- `"Full"`: days 15 - 21
|
||||
- `"Waning"`: days 22 - 28
|
||||
|
||||
After day 28, the cycle repeats with day 1, a new moon.
|
||||
|
||||
- Use `"2000-01-06"` as a reference new moon (day 1 of the cycle) to determine the phase of the given day.
|
||||
- You will not be given any dates before the reference date.
|
||||
- Return the correct phase as a string.
|
||||
|
||||
**Note:** Day 1 represents the day of the new moon, meaning 0 days have passed since the last new moon.
|
||||
|
||||
# --hints--
|
||||
|
||||
`moonPhase("2000-01-12")` should return `"New"`.
|
||||
|
||||
```js
|
||||
assert.equal(moonPhase("2000-01-12"), "New");
|
||||
```
|
||||
|
||||
`moonPhase("2000-01-13")` should return `"Waxing"`.
|
||||
|
||||
```js
|
||||
assert.equal(moonPhase("2000-01-13"), "Waxing");
|
||||
```
|
||||
|
||||
`moonPhase("2014-10-15")` should return `"Full"`.
|
||||
|
||||
```js
|
||||
assert.equal(moonPhase("2014-10-15"), "Full");
|
||||
```
|
||||
|
||||
`moonPhase("2012-10-21")` should return `"Waning"`.
|
||||
|
||||
```js
|
||||
assert.equal(moonPhase("2012-10-21"), "Waning");
|
||||
```
|
||||
|
||||
`moonPhase("2022-12-14")` should return `"New"`.
|
||||
|
||||
```js
|
||||
assert.equal(moonPhase("2022-12-14"), "New");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function moonPhase(dateString) {
|
||||
|
||||
return dateString;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function moonPhase(dateString) {
|
||||
const ONE_DAY_IN_MS = 1000 * 60 * 60 * 24;
|
||||
const refDate = new Date("2000-01-06");
|
||||
const targetDate = new Date(dateString);
|
||||
const diffMs = targetDate - refDate;
|
||||
const diffDays = diffMs / ONE_DAY_IN_MS;
|
||||
const phaseDay = (diffDays % 28 + 1);
|
||||
|
||||
if (phaseDay <= 7) {
|
||||
return "New";
|
||||
} else if (phaseDay <= 14) {
|
||||
return "Waxing";
|
||||
} else if (phaseDay <= 21) {
|
||||
return "Full"
|
||||
} else {
|
||||
return "Waning";
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
---
|
||||
id: 68c497f3aaefc9fd9f1b0e25
|
||||
title: "Challenge 61: Space Week Day 7: Launch Fuel"
|
||||
challengeType: 28
|
||||
dashedName: challenge-61
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
For the final day of Space Week, you will be given the mass in kilograms (kg) of a payload you want to send to orbit. Determine the amount of fuel needed to send your payload to orbit using the following rules:
|
||||
|
||||
- Rockets require 1 kg of fuel per 5 kg of mass they must lift.
|
||||
- Fuel itself has mass. So when you add fuel, the mass to lift goes up, which requires more fuel, which increases the mass, and so on.
|
||||
- To calculate the total fuel needed: start with the payload mass, calculate the fuel needed for that, add that fuel to the total mass, and calculate again. Repeat this process until the additional fuel required is less than 1 kg, then stop.
|
||||
- Ignore the mass of the rocket itself. Only compute fuel needed to lift the payload and its own fuel.
|
||||
|
||||
For example, given a payload mass of 50 kg, you would need 10 kg of fuel to lift it (payload / 5), which increases the total mass to 60 kg, which needs 12 kg to lift (2 additional kg), which increases the total mass to 62 kg, which needs 12.4 kg to lift - 0.4 additional kg - which is less 1 additional kg, so we stop here. The total mass to lift is 62.4 kg, 50 of which is the initial payload and 12.4 of fuel.
|
||||
|
||||
- Return the amount of fuel needed rounded to one decimal place.
|
||||
|
||||
# --hints--
|
||||
|
||||
`launchFuel(50)` should return `12.4`.
|
||||
|
||||
```js
|
||||
assert.equal(launchFuel(50), 12.4);
|
||||
```
|
||||
|
||||
`launchFuel(500)` should return `124.8`.
|
||||
|
||||
```js
|
||||
assert.equal(launchFuel(500), 124.8);
|
||||
```
|
||||
|
||||
`launchFuel(243)` should return `60.7`.
|
||||
|
||||
```js
|
||||
assert.equal(launchFuel(243), 60.7);
|
||||
```
|
||||
|
||||
`launchFuel(11000)` should return `2749.8`.
|
||||
|
||||
```js
|
||||
assert.equal(launchFuel(11000), 2749.8);
|
||||
```
|
||||
|
||||
`launchFuel(6214)` should return `1553.4`.
|
||||
|
||||
```js
|
||||
assert.equal(launchFuel(6214), 1553.4);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function launchFuel(payload) {
|
||||
|
||||
return payload;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function launchFuel(payload) {
|
||||
let totalMass = payload;
|
||||
let additionalFuel = totalMass / 5;
|
||||
let totalFuel = additionalFuel;
|
||||
|
||||
while (additionalFuel >= 1) {
|
||||
totalMass += additionalFuel;
|
||||
additionalFuel = (totalMass / 5) - totalFuel;
|
||||
totalFuel += additionalFuel;
|
||||
}
|
||||
|
||||
return Number(totalFuel.toFixed(1));
|
||||
}
|
||||
```
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
---
|
||||
id: 68c497f3aaefc9fd9f1b0e26
|
||||
title: "Challenge 62: Hex to Decimal"
|
||||
challengeType: 28
|
||||
dashedName: challenge-62
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string representing a hexadecimal number (base 16), return its decimal (base 10) value as an integer.
|
||||
|
||||
Hexadecimal is a number system that uses 16 digits:
|
||||
|
||||
- `0-9` represent values `0` through `9`.
|
||||
- `A-F` represent values `10` through `15`.
|
||||
|
||||
Here's a partial conversion table:
|
||||
|
||||
| Hexadecimal | Decimal |
|
||||
|:-----------:|:-------:|
|
||||
| 0 | 0 |
|
||||
| 1 | 1 |
|
||||
| ... | ... |
|
||||
| 9 | 9 |
|
||||
| A | 10 |
|
||||
| ... | ... |
|
||||
| F | 15 |
|
||||
| 10 | 16 |
|
||||
| ... | ... |
|
||||
| 9F | 159 |
|
||||
| A0 | 160 |
|
||||
| ... | ... |
|
||||
| FF | 255 |
|
||||
| 100 | 256 |
|
||||
|
||||
- The string will only contain characters `0–9` and `A–F`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`hexToDecimal("A")` should return `10`.
|
||||
|
||||
```js
|
||||
assert.equal(hexToDecimal("A"), 10);
|
||||
```
|
||||
|
||||
`hexToDecimal("15")` should return `21`.
|
||||
|
||||
```js
|
||||
assert.equal(hexToDecimal("15"), 21);
|
||||
```
|
||||
|
||||
`hexToDecimal("2E")` should return `46`.
|
||||
|
||||
```js
|
||||
assert.equal(hexToDecimal("2E"), 46);
|
||||
```
|
||||
|
||||
`hexToDecimal("FF")` should return `255`.
|
||||
|
||||
```js
|
||||
assert.equal(hexToDecimal("FF"), 255);
|
||||
```
|
||||
|
||||
`hexToDecimal("A3F")` should return `2623`.
|
||||
|
||||
```js
|
||||
assert.equal(hexToDecimal("A3F"), 2623);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function hexToDecimal(hex) {
|
||||
|
||||
return hex;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function hexToDecimal(hex) {
|
||||
|
||||
return parseInt(hex, 16);
|
||||
}
|
||||
```
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
---
|
||||
id: 68cae5b538ff798bbd4da001
|
||||
title: "Challenge 63: Battle of Words"
|
||||
challengeType: 28
|
||||
dashedName: challenge-63
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given two sentences representing your team and an opposing team, where each word from your team battles the corresponding word from the opposing team, determine which team wins using the following rules:
|
||||
|
||||
- The given sentences will always contain the same number of words.
|
||||
- Words are separated by a single space and will only contain letters.
|
||||
- The value of each word is the sum of its letters.
|
||||
- Letters `a` to `z` correspond to the values `1` through `26`. For example, `a` is `1`, and `z` is `26`.
|
||||
- A capital letter doubles the value of the letter. For example, `A` is `2`, and `Z` is `52`.
|
||||
- Words battle in order: the first word of your team battles the first word of the opposing team, and so on.
|
||||
- A word wins if its value is greater than the opposing word's value.
|
||||
- The team with more winning words is the winner.
|
||||
|
||||
Return `"We win"` if your team is the winner, `"We lose"` if your team loses, and `"Draw"` if both teams have the same number of wins.
|
||||
|
||||
# --hints--
|
||||
|
||||
`battle("hello world", "hello word")` should return `"We win"`.
|
||||
|
||||
```js
|
||||
assert.equal(battle("hello world", "hello word"), "We win");
|
||||
```
|
||||
|
||||
`battle("Hello world", "hello world")` should return `"We win"`.
|
||||
|
||||
```js
|
||||
assert.equal(battle("Hello world", "hello world"), "We win");
|
||||
```
|
||||
|
||||
`battle("lorem ipsum", "kitty ipsum")` should return `"We lose"`.
|
||||
|
||||
```js
|
||||
assert.equal(battle("lorem ipsum", "kitty ipsum"), "We lose");
|
||||
```
|
||||
|
||||
`battle("hello world", "world hello")` should return `"Draw"`.
|
||||
|
||||
```js
|
||||
assert.equal(battle("hello world", "world hello"), "Draw");
|
||||
```
|
||||
|
||||
`battle("git checkout", "git switch")` should return `"We win"`.
|
||||
|
||||
```js
|
||||
assert.equal(battle("git checkout", "git switch"), "We win");
|
||||
```
|
||||
|
||||
`battle("Cheeseburger with fries", "Cheeseburger with Fries")` should return `"We lose"`.
|
||||
|
||||
```js
|
||||
assert.equal(battle("Cheeseburger with fries", "Cheeseburger with Fries"), "We lose");
|
||||
```
|
||||
|
||||
`battle("We must never surrender", "Our team must win")` should return `"Draw"`.
|
||||
|
||||
```js
|
||||
assert.equal(battle("We must never surrender", "Our team must win"), "Draw");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function battle(ourTeam, opponent) {
|
||||
|
||||
return ourTeam;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function getCharacterValue(char) {
|
||||
const lowerCaseValue = char.toLowerCase().charCodeAt(0) - 96;
|
||||
return char >= 'A' && char <= 'Z' ? lowerCaseValue * 2 : lowerCaseValue;
|
||||
}
|
||||
|
||||
function getWordValue(word) {
|
||||
let wordValue = 0;
|
||||
for (let i=0; i<word.length; i++) {
|
||||
wordValue += getCharacterValue(word[i])
|
||||
}
|
||||
|
||||
return wordValue;
|
||||
}
|
||||
|
||||
function battle(ourTeam, opponent) {
|
||||
const myWords = ourTeam.split(' ');
|
||||
const opponentWords = opponent.split(' ');
|
||||
|
||||
let myWins = 0, opponentWins = 0;
|
||||
|
||||
for (let i=0; i<myWords.length; i++) {
|
||||
const myWordValue = getWordValue(myWords[i]);
|
||||
const opponentWordValue = getWordValue(opponentWords[i])
|
||||
|
||||
if (myWordValue > opponentWordValue) myWins++;
|
||||
if (opponentWordValue > myWordValue) opponentWins++;
|
||||
}
|
||||
|
||||
if (myWins > opponentWins) return 'We win';
|
||||
if (opponentWins > myWins) return 'We lose';
|
||||
return 'Draw';
|
||||
}
|
||||
```
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
---
|
||||
id: 68cae5b538ff798bbd4da002
|
||||
title: "Challenge 64: 24 to 12"
|
||||
challengeType: 28
|
||||
dashedName: challenge-64
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string representing a time of the day in the 24-hour format of `"HHMM"`, return the time in its equivalent 12-hour format of `"H:MM AM"` or `"H:MM PM"`.
|
||||
|
||||
- The given input will always be a four-digit string in 24-hour time format, from `"0000"` to `"2359"`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`to12("1124")` should return `"11:24 AM"`.
|
||||
|
||||
```js
|
||||
assert.equal(to12("1124"), "11:24 AM");
|
||||
```
|
||||
|
||||
`to12("0900")` should return `"9:00 AM"`.
|
||||
|
||||
```js
|
||||
assert.equal(to12("0900"), "9:00 AM");
|
||||
```
|
||||
|
||||
`to12("1455")` should return `"2:55 PM"`.
|
||||
|
||||
```js
|
||||
assert.equal(to12("1455"), "2:55 PM");
|
||||
```
|
||||
|
||||
`to12("2346")` should return `"11:46 PM"`.
|
||||
|
||||
```js
|
||||
assert.equal(to12("2346"), "11:46 PM");
|
||||
```
|
||||
|
||||
`to12("0030")` should return `"12:30 AM"`.
|
||||
|
||||
```js
|
||||
assert.equal(to12("0030"), "12:30 AM");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function to12(time) {
|
||||
|
||||
return time;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function convertHours(hours) {
|
||||
if (hours === 0) return 12;
|
||||
if (hours > 12) return hours - 12;
|
||||
return hours;
|
||||
}
|
||||
|
||||
function to12(time) {
|
||||
const hours = parseInt(time.slice(0, 2), 10);
|
||||
const minutes = time.slice(2);
|
||||
const period = hours < 12 ? 'AM' : 'PM';
|
||||
|
||||
return `${convertHours(hours)}:${minutes} ${period}`;
|
||||
}
|
||||
```
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
---
|
||||
id: 68cae5b538ff798bbd4da003
|
||||
title: "Challenge 65: String Count"
|
||||
challengeType: 28
|
||||
dashedName: challenge-65
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given two strings, determine how many times the second string appears in the first.
|
||||
|
||||
- The pattern string can overlap in the first string. For example, `"aaa"` contains `"aa"` twice. The first two `a`'s and the second two.
|
||||
|
||||
# --hints--
|
||||
|
||||
`count('abcdefg', 'def')` should return `1`.
|
||||
|
||||
```js
|
||||
assert.equal(count('abcdefg', 'def'), 1);
|
||||
```
|
||||
|
||||
`count('hello', 'world')` should return `0`.
|
||||
|
||||
```js
|
||||
assert.equal(count('hello', 'world'), 0);
|
||||
```
|
||||
|
||||
`count('mississippi', 'iss')` should return `2`.
|
||||
|
||||
```js
|
||||
assert.equal(count('mississippi', 'iss'), 2);
|
||||
```
|
||||
|
||||
`count('she sells seashells by the seashore', 'sh')` should return `3`.
|
||||
|
||||
```js
|
||||
assert.equal(count('she sells seashells by the seashore', 'sh'), 3);
|
||||
```
|
||||
|
||||
`count('101010101010101010101', '101')` should return `10`.
|
||||
|
||||
```js
|
||||
assert.equal(count('101010101010101010101', '101'), 10);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function count(text, pattern) {
|
||||
|
||||
return text;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function count(text, pattern) {
|
||||
let occurrences = 0;
|
||||
|
||||
for (let i = 0; i <= text.length - pattern.length; i++) {
|
||||
if (text.slice(i, i + pattern.length) === pattern) {
|
||||
occurrences++;
|
||||
}
|
||||
}
|
||||
|
||||
return occurrences;
|
||||
}
|
||||
```
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
---
|
||||
id: 68cae5b538ff798bbd4da004
|
||||
title: "Challenge 66: HTML Tag Stripper"
|
||||
challengeType: 28
|
||||
dashedName: challenge-66
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string of HTML code, remove the tags and return the plain text content.
|
||||
|
||||
- The input string will contain only valid HTML.
|
||||
- HTML tags may be nested.
|
||||
- Remove the tags and any attributes.
|
||||
|
||||
For example, `'<a href="#">Click here</a>'` should return `"Click here"`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`stripTags('<a href="#">Click here</a>')` should return `"Click here"`.
|
||||
|
||||
```js
|
||||
assert.equal(stripTags('<a href="#">Click here</a>'), "Click here");
|
||||
```
|
||||
|
||||
`stripTags('<p class="center">Hello <b>World</b>!</p>')` should return `"Hello World!"`.
|
||||
|
||||
```js
|
||||
assert.equal(stripTags('<p class="center">Hello <b>World</b>!</p>'), "Hello World!");
|
||||
```
|
||||
|
||||
`stripTags('<img src="cat.jpg" alt="Cat">')` should return an empty string (`""`).
|
||||
|
||||
```js
|
||||
assert.equal(stripTags('<img src="cat.jpg" alt="Cat">'), "");
|
||||
```
|
||||
|
||||
`stripTags('<main id="main"><section class="section">section</section><section class="section">section</section></main>')` should return `sectionsection`.
|
||||
|
||||
```js
|
||||
assert.equal(stripTags('<main id="main"><section class="section">section</section><section class="section">section</section></main>'), "sectionsection");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function stripTags(html) {
|
||||
|
||||
return html;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function stripTags(html) {
|
||||
return html.replace(/<[^>]*>/g, '');
|
||||
}
|
||||
```
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
---
|
||||
id: 68cae5b538ff798bbd4da005
|
||||
title: "Challenge 67: Email Validator"
|
||||
challengeType: 28
|
||||
dashedName: challenge-67
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string, determine if it is a valid email address using the following constraints:
|
||||
|
||||
- It must contain exactly one `@` symbol.
|
||||
- The local part (before the `@`):
|
||||
- Can only contain letters (`a-z`, `A-Z`), digits (`0-9`), dots (`.`), underscores (`_`), or hyphens (`-`).
|
||||
- Cannot start or end with a dot.
|
||||
- The domain part (after the `@`):
|
||||
- Must contain at least one dot.
|
||||
- Must end with a dot followed by at least two letters.
|
||||
- Neither the local or domain part can have two dots in a row.
|
||||
|
||||
# --hints--
|
||||
|
||||
`validate("a@b.cd")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(validate("a@b.cd"));
|
||||
```
|
||||
|
||||
`validate("hell.-w.rld@example.com")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(validate("hell.-w.rld@example.com"));
|
||||
```
|
||||
|
||||
`validate(".b@sh.rc")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(validate(".b@sh.rc"));
|
||||
```
|
||||
|
||||
`validate("example@test.c0")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(validate("example@test.c0"));
|
||||
```
|
||||
|
||||
`validate("freecodecamp.org")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(validate("freecodecamp.org"));
|
||||
```
|
||||
|
||||
`validate("develop.ment_user@c0D!NG.R.CKS")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(validate("develop.ment_user@c0D!NG.R.CKS"));
|
||||
```
|
||||
|
||||
`validate("hello.@wo.rld")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(validate("hello.@wo.rld"));
|
||||
```
|
||||
|
||||
`validate("hello@world..com")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(validate("hello@world..com"));
|
||||
```
|
||||
|
||||
`validate("develop..ment_user@c0D!NG.R.CKS")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(validate("develop..ment_user@c0D!NG.R.CKS"));
|
||||
```
|
||||
|
||||
`validate("git@commit@push.io")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(validate("git@commit@push.io"));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function validate(email) {
|
||||
|
||||
return email;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function validate(email) {
|
||||
if (email.includes('..')) return false;
|
||||
|
||||
const parts = email.split('@');
|
||||
if (parts.length !== 2) return false;
|
||||
|
||||
const [local, domain] = parts;
|
||||
|
||||
if (local.startsWith('.') || local.endsWith('.')) return false;
|
||||
if (!/^[a-zA-Z0-9._-]+$/.test(local)) return false;
|
||||
if (!domain.includes('.')) return false;
|
||||
|
||||
const tld = domain.split('.').pop();
|
||||
if (tld.length < 2 || !/^[a-zA-Z]+$/.test(tld)) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
---
|
||||
id: 68cae5b538ff798bbd4da006
|
||||
title: "Challenge 68: Credit Card Masker"
|
||||
challengeType: 28
|
||||
dashedName: challenge-68
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string of credit card numbers, return a masked version of it using the following constraints:
|
||||
|
||||
- The string will contain four sets of four digits (`0-9`), with all sets being separated by a single space, or a single hyphen (`-`).
|
||||
- Replace all numbers, except the last four, with an asterisk (`*`).
|
||||
- Leave the remaining characters unchanged.
|
||||
|
||||
For example, given `"4012-8888-8888-1881"` return `"****-****-****-1881"`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`mask("4012-8888-8888-1881")` should return `"****-****-****-1881"`.
|
||||
|
||||
```js
|
||||
assert.equal(mask("4012-8888-8888-1881"), "****-****-****-1881");
|
||||
```
|
||||
|
||||
`mask("5105 1051 0510 5100")` should return `"**** **** **** 5100"`.
|
||||
|
||||
```js
|
||||
assert.equal(mask("5105 1051 0510 5100"), "**** **** **** 5100");
|
||||
```
|
||||
|
||||
`mask("6011 1111 1111 1117")` should return `"**** **** **** 1117"`.
|
||||
|
||||
```js
|
||||
assert.equal(mask("6011 1111 1111 1117"), "**** **** **** 1117");
|
||||
```
|
||||
|
||||
`mask("2223-0000-4845-0010")` should return `"****-****-****-0010"`.
|
||||
|
||||
```js
|
||||
assert.equal(mask("2223-0000-4845-0010"), "****-****-****-0010");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function mask(card) {
|
||||
|
||||
return card;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function mask(card) {
|
||||
const split = card.split(card.includes('-') ? '-' : ' ');
|
||||
|
||||
return card.includes('-') ?
|
||||
`****-****-****-${split[3]}` :
|
||||
`**** **** **** ${split[3]}`;
|
||||
}
|
||||
```
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
---
|
||||
id: 68cae5b538ff798bbd4da007
|
||||
title: "Challenge 69: Missing Socks"
|
||||
challengeType: 28
|
||||
dashedName: challenge-69
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given an integer representing the number of pairs of socks you started with, and another integer representing how many wash cycles you have gone through, return the number of complete pairs of socks you currently have using the following constraints:
|
||||
|
||||
- Every 2 wash cycles, you lose a single sock.
|
||||
- Every 3 wash cycles, you find a single missing sock.
|
||||
- Every 5 wash cycles, a single sock is worn out and must be thrown away.
|
||||
- Every 10 wash cycles, you buy a pair of socks.
|
||||
- You can never have less than zero total socks.
|
||||
- Rules can overlap. For example, on wash cycle 10, you will lose a single sock, throw away a single sock, and buy a new pair of socks.
|
||||
- Return the number of complete pairs of socks.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sockPairs(2, 5)` should return `1`.
|
||||
|
||||
```js
|
||||
assert.equal(sockPairs(2, 5), 1);
|
||||
```
|
||||
|
||||
`sockPairs(1, 2)` should return `0`.
|
||||
|
||||
```js
|
||||
assert.equal(sockPairs(1, 2), 0);
|
||||
```
|
||||
|
||||
`sockPairs(5, 11)` should return `4`.
|
||||
|
||||
```js
|
||||
assert.equal(sockPairs(5, 11), 4);
|
||||
```
|
||||
|
||||
`sockPairs(6, 25)` should return `3`.
|
||||
|
||||
```js
|
||||
assert.equal(sockPairs(6, 25), 3);
|
||||
```
|
||||
|
||||
`sockPairs(1, 8)` should return `0`.
|
||||
|
||||
```js
|
||||
assert.equal(sockPairs(1, 8), 0);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function sockPairs(pairs, cycles) {
|
||||
|
||||
return pairs;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function sockPairs(pairs, cycles) {
|
||||
let socks = pairs * 2;
|
||||
|
||||
for (let i = 1; i <= cycles; i++) {
|
||||
if (i % 2 === 0) socks -= 1;
|
||||
if (i % 3 === 0) socks += 1;
|
||||
if (i % 5 === 0) socks -= 1;
|
||||
if (i % 10 === 0) socks += 2;
|
||||
|
||||
if (socks < 0) socks = 0;
|
||||
}
|
||||
|
||||
return Math.floor(socks / 2);
|
||||
}
|
||||
```
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
---
|
||||
id: 68cae5b538ff798bbd4da008
|
||||
title: "Challenge 70: HTML Attribute Extractor"
|
||||
challengeType: 28
|
||||
dashedName: challenge-70
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string of a valid HTML element, return the attributes of the element using the following criteria:
|
||||
|
||||
- You will only be given one element.
|
||||
- Attributes will be in the format: `attribute="value"`.
|
||||
- Return an array of strings with each attribute property and value, separated by a comma, in this format: `["attribute1, value1", "attribute2, value2"]`.
|
||||
- Return attributes in the order they are given.
|
||||
- If no attributes are found, return an empty array.
|
||||
|
||||
# --hints--
|
||||
|
||||
`extractAttributes('<span class="red"></span>')` should return `["class, red"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(extractAttributes('<span class="red"></span>'), ["class, red"]);
|
||||
```
|
||||
|
||||
`extractAttributes('<meta charset="UTF-8" />')` should return `["charset, UTF-8"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(extractAttributes('<meta charset="UTF-8" />'), ["charset, UTF-8"]);
|
||||
```
|
||||
|
||||
`extractAttributes("<p>Lorem ipsum dolor sit amet</p>")` should return `[]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(extractAttributes("<p>Lorem ipsum dolor sit amet</p>"), []);
|
||||
```
|
||||
|
||||
`extractAttributes('<input name="email" type="email" required="true" />')` should return `["name, email", "type, email", "required, true"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(extractAttributes('<input name="email" type="email" required="true" />'), ["name, email", "type, email", "required, true"]);
|
||||
```
|
||||
|
||||
`extractAttributes('<button id="submit" class="btn btn-primary">Submit</button>')` should return `["id, submit", "class, btn btn-primary"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(extractAttributes('<button id="submit" class="btn btn-primary">Submit</button>'), ["id, submit", "class, btn btn-primary"]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function extractAttributes(element) {
|
||||
|
||||
return element;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function extractAttributes(element) {
|
||||
const regex = /(\w[\w-]*)="([^"]*)"/g;
|
||||
const result = [];
|
||||
let match;
|
||||
|
||||
while ((match = regex.exec(element)) !== null) {
|
||||
const attr = match[1];
|
||||
const val = match[2];
|
||||
result.push(`${attr}, ${val}`);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
```
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
---
|
||||
id: 68cae5b538ff798bbd4da009
|
||||
title: "Challenge 71: Tip Calculator"
|
||||
challengeType: 28
|
||||
dashedName: challenge-71
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given the price of your meal and a custom tip percent, return an array with three tip values; 15%, 20%, and the custom amount.
|
||||
|
||||
- Prices will be given in the format: `"$N.NN"`.
|
||||
- Custom tip percents will be given in this format: `"25%"`.
|
||||
- Return amounts in the same `"$N.NN"` format, rounded to two decimal places.
|
||||
|
||||
For example, given a `"$10.00"` meal price, and a `"25%"` custom tip value, return `["$1.50", "$2.00", "$2.50"]`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`calculateTips("$10.00", "25%")` should return `["$1.50", "$2.00", "$2.50"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(calculateTips("$10.00", "25%"), ["$1.50", "$2.00", "$2.50"]);
|
||||
```
|
||||
|
||||
`calculateTips("$89.67", "26%")` should return `["$13.45", "$17.93", "$23.31"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(calculateTips("$89.67", "26%"), ["$13.45", "$17.93", "$23.31"]);
|
||||
```
|
||||
|
||||
`calculateTips("$19.85", "9%")` should return `["$2.98", "$3.97", "$1.79"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(calculateTips("$19.85", "9%"), ["$2.98", "$3.97", "$1.79"]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function calculateTips(mealPrice, customTip) {
|
||||
|
||||
return mealPrice;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function calculateTips(mealPrice, customTip) {
|
||||
const meal = parseFloat(mealPrice.slice(1));
|
||||
const customPercent = parseFloat(customTip.slice(0, -1));
|
||||
const tips = [15, 20, customPercent];
|
||||
|
||||
return tips.map(percent => {
|
||||
const amount = (meal * percent / 100).toFixed(2);
|
||||
return `$${amount}`;
|
||||
});
|
||||
}
|
||||
```
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
---
|
||||
id: 68cae5b538ff798bbd4da00a
|
||||
title: "Challenge 72: Thermostat Adjuster 2"
|
||||
challengeType: 28
|
||||
dashedName: challenge-72
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given the current temperature of a room in Fahrenheit and a target temperature in Celsius, return a string indicating how to adjust the room temperature based on these constraints:
|
||||
|
||||
- Return `"Heat: X degrees Fahrenheit"` if the current temperature is below the target. With `X` being the number of degrees in Fahrenheit to heat the room to reach the target, rounded to 1 decimal place.
|
||||
- Return `"Cool: X degrees Fahrenheit"` if the current temperature is above the target. With `X` being the number of degrees in Fahrenheit to cool the room to reach the target, rounded to 1 decimal place.
|
||||
- Return `"Hold"` if the current temperature is equal to the target.
|
||||
|
||||
To convert Celsius to Fahrenheit, multiply the Celsius temperature by 1.8 and add 32 to the result (`F = (C * 1.8) + 32`).
|
||||
|
||||
# --hints--
|
||||
|
||||
`adjustThermostat(32, 0)` should return `"Hold"`.
|
||||
|
||||
```js
|
||||
assert.equal(adjustThermostat(32, 0), "Hold");
|
||||
```
|
||||
|
||||
`adjustThermostat(70, 25)` should return `"Heat: 7.0 degrees Fahrenheit"`.
|
||||
|
||||
```js
|
||||
assert.equal(adjustThermostat(70, 25), "Heat: 7.0 degrees Fahrenheit");
|
||||
```
|
||||
|
||||
`adjustThermostat(72, 18)` should return `"Cool: 7.6 degrees Fahrenheit"`.
|
||||
|
||||
```js
|
||||
assert.equal(adjustThermostat(72, 18), "Cool: 7.6 degrees Fahrenheit");
|
||||
```
|
||||
|
||||
`adjustThermostat(212, 100)` should return `"Hold"`.
|
||||
|
||||
```js
|
||||
assert.equal(adjustThermostat(212, 100), "Hold");
|
||||
```
|
||||
|
||||
`adjustThermostat(59, 22)` should return `"Heat: 12.6 degrees Fahrenheit"`.
|
||||
|
||||
```js
|
||||
assert.equal(adjustThermostat(59, 22), "Heat: 12.6 degrees Fahrenheit");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function adjustThermostat(currentF, targetC) {
|
||||
|
||||
return currentF;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function adjustThermostat(currentF, targetC) {
|
||||
const targetF = targetC * 1.8 + 32;
|
||||
const diff = Math.abs(targetF - currentF).toFixed(1);
|
||||
|
||||
if (currentF < targetF) {
|
||||
return `Heat: ${diff} degrees Fahrenheit`;
|
||||
} else if (currentF > targetF) {
|
||||
return `Cool: ${diff} degrees Fahrenheit`;
|
||||
} else {
|
||||
return "Hold"
|
||||
}
|
||||
}
|
||||
```
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
---
|
||||
id: 68d2ba1468508398389487ce
|
||||
title: "Challenge 73: Speak Wisely, You Must"
|
||||
challengeType: 28
|
||||
dashedName: challenge-73
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a sentence, return a version of it that sounds like advice from a wise teacher using the following rules:
|
||||
|
||||
- Words are separated by a single space.
|
||||
- Find the first occurrence of one of the following words in the sentence: `"have"`, `"must"`, `"are"`, `"will"`, `"can"`.
|
||||
- Move all words before and including that word to the end of the sentence and:
|
||||
- Preserve the order of the words when you move them.
|
||||
- Make them all lowercase.
|
||||
- And add a comma and space before them.
|
||||
- Capitalize the first letter of the new first word of the sentence.
|
||||
- All given sentences will end with a single punctuation mark. Keep the original punctuation of the sentence and move it to the end of the new sentence.
|
||||
- Return the new sentence, make sure there's a single space between each word and no spaces at the beginning or end of the sentence.
|
||||
|
||||
For example, given `"You must speak wisely."` return `"Speak wisely, you must."`
|
||||
|
||||
# --hints--
|
||||
|
||||
`wiseSpeak("You must speak wisely.")` should return `"Speak wisely, you must."`
|
||||
|
||||
```js
|
||||
assert.equal(wiseSpeak("You must speak wisely."), "Speak wisely, you must.");
|
||||
```
|
||||
|
||||
`wiseSpeak("You can do it!")` should return `"Do it, you can!"`
|
||||
|
||||
```js
|
||||
assert.equal(wiseSpeak("You can do it!"), "Do it, you can!");
|
||||
```
|
||||
|
||||
`wiseSpeak("Do you think you will complete this?")` should return `"Complete this, do you think you will?"`
|
||||
|
||||
```js
|
||||
assert.equal(wiseSpeak("Do you think you will complete this?"), "Complete this, do you think you will?");
|
||||
```
|
||||
|
||||
`wiseSpeak("All your base are belong to us.")` should return `"Belong to us, all your base are."`
|
||||
|
||||
```js
|
||||
assert.equal(wiseSpeak("All your base are belong to us."), "Belong to us, all your base are.");
|
||||
```
|
||||
|
||||
`wiseSpeak("You have much to learn.")` should return `"Much to learn, you have."`
|
||||
|
||||
```js
|
||||
assert.equal(wiseSpeak("You have much to learn."), "Much to learn, you have.");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function wiseSpeak(sentence) {
|
||||
|
||||
return sentence;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function wiseSpeak(sentence) {
|
||||
const triggers = ["have", "must", "are", "will", "can"];
|
||||
const punctuation = sentence[sentence.length - 1];
|
||||
const words = sentence.split(" ");
|
||||
|
||||
const triggerIndex = words.findIndex(w => triggers.includes(w));
|
||||
|
||||
const toMove = words.slice(0, triggerIndex + 1).map(w => w.toLowerCase());
|
||||
const remaining = words.slice(triggerIndex + 1);
|
||||
|
||||
const newStart = remaining.map((w, i) => {
|
||||
return i === 0 ? w[0].toUpperCase() + w.slice(1) :
|
||||
i === remaining.length - 1 ? w.slice(0, w.length - 1) : w;
|
||||
})
|
||||
|
||||
return newStart.join(" ") + ", " + toMove.join(" ") + punctuation;
|
||||
}
|
||||
```
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
---
|
||||
id: 68d2ba1468508398389487cf
|
||||
title: "Challenge 74: Favorite Songs"
|
||||
challengeType: 28
|
||||
dashedName: challenge-74
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Remember iPods? The first model came out 24 years ago today, on Oct. 23, 2001.
|
||||
|
||||
Given an array of song objects representing your iPod playlist, return an array with the titles of the two most played songs, with the most played song first.
|
||||
|
||||
- Each object will have a `"title"` property (string), and a `"plays"` property (integer).
|
||||
|
||||
# --hints--
|
||||
|
||||
`favoriteSongs([{"title": "Sync or Swim", "plays": 3}, {"title": "Byte Me", "plays": 1}, {"title": "Earbud Blues", "plays": 2} ])` should return `["Sync or Swim", "Earbud Blues"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(favoriteSongs([{"title": "Sync or Swim", "plays": 3}, {"title": "Byte Me", "plays": 1}, {"title": "Earbud Blues", "plays": 2} ]), ["Sync or Swim", "Earbud Blues"]);
|
||||
```
|
||||
|
||||
`favoriteSongs([{"title": "Skip Track", "plays": 98}, {"title": "99 Downloads", "plays": 99}, {"title": "Clickwheel Love", "plays": 100} ])` should return `["Clickwheel Love", "99 Downloads"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(favoriteSongs([{"title": "Skip Track", "plays": 98}, {"title": "99 Downloads", "plays": 99}, {"title": "Clickwheel Love", "plays": 100} ]), ["Clickwheel Love", "99 Downloads"]);
|
||||
```
|
||||
|
||||
`favoriteSongs([{"title": "Song A", "plays": 42}, {"title": "Song B", "plays": 99}, {"title": "Song C", "plays": 75} ])` should return `["Song B", "Song C"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(favoriteSongs([{"title": "Song A", "plays": 42}, {"title": "Song B", "plays": 99}, {"title": "Song C", "plays": 75} ]), ["Song B", "Song C"]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function favoriteSongs(playlist) {
|
||||
|
||||
return playlist;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function favoriteSongs(playlist) {
|
||||
const sorted = [...playlist].sort((a, b) => b.plays - a.plays);
|
||||
return sorted.slice(0, 2).map(song => song.title);
|
||||
}
|
||||
```
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
---
|
||||
id: 68d2ba1468508398389487d0
|
||||
title: "Challenge 75: Hidden Treasure"
|
||||
challengeType: 28
|
||||
dashedName: challenge-75
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a 2D array representing a map of the ocean floor that includes a hidden treasure, and an array with the coordinates (`[row, column]`) for the next dive of your treasure search, return `"Empty"`, `"Found"`, or `"Recovered"` using the following rules:
|
||||
|
||||
- The given 2D array will contain exactly one unrecovered treasure, which will occupy multiple cells.
|
||||
- Each cell in the 2D array will contain one of the following values:
|
||||
- `"-"`: No treasure.
|
||||
- `"O"`: A part of the treasure that has not been found.
|
||||
- `"X"`: A part of the treasure that has already been found.
|
||||
|
||||
- If the dive location has no treasure, return `"Empty"`.
|
||||
- If the dive location finds treasure, but at least one other part of the treasure remains unfound, return `"Found"`.
|
||||
- If the dive location finds the last unfound part of the treasure, return `"Recovered"`.
|
||||
|
||||
For example, given:
|
||||
|
||||
```json
|
||||
[
|
||||
[ "-", "X"],
|
||||
[ "-", "X"],
|
||||
[ "-", "O"]
|
||||
]
|
||||
```
|
||||
|
||||
And `[2, 1]` for the coordinates of the dive location, return `"Recovered"` because the dive found the last unfound part of the treasure.
|
||||
|
||||
# --hints--
|
||||
|
||||
`dive([[ "-", "X"], [ "-", "X"], [ "-", "O"]], [2, 1])` should return `"Recovered"`.
|
||||
|
||||
```js
|
||||
assert.equal(dive([[ "-", "X"], [ "-", "X"], [ "-", "O"]], [2, 1]), "Recovered");
|
||||
```
|
||||
|
||||
`dive([[ "-", "X"], [ "-", "X"], [ "-", "O"]], [2, 0])` should return `"Empty"`.
|
||||
|
||||
```js
|
||||
assert.equal(dive([[ "-", "X"], [ "-", "X"], [ "-", "O"]], [2, 0]), "Empty");
|
||||
```
|
||||
|
||||
`dive([[ "-", "X"], [ "-", "O"], [ "-", "O"]], [1, 1])` should return `"Found"`.
|
||||
|
||||
```js
|
||||
assert.equal(dive([[ "-", "X"], [ "-", "O"], [ "-", "O"]], [1, 1]), "Found");
|
||||
```
|
||||
|
||||
`dive([[ "-", "-", "-"], [ "X", "O", "X"], [ "-", "-", "-"]], [1, 2])` should return `"Found"`.
|
||||
|
||||
```js
|
||||
assert.equal(dive([[ "-", "-", "-"], [ "X", "O", "X"], [ "-", "-", "-"]], [1, 2]), "Found");
|
||||
```
|
||||
|
||||
`dive([[ "-", "-", "-"], [ "-", "-", "-"], [ "O", "X", "X"]], [2, 0])` should return `"Recovered"`.
|
||||
|
||||
```js
|
||||
assert.equal(dive([[ "-", "-", "-"], [ "-", "-", "-"], [ "O", "X", "X"]], [2, 0]), "Recovered");
|
||||
```
|
||||
|
||||
`dive([[ "-", "-", "-"], [ "-", "-", "-"], [ "O", "X", "X"]], [1, 2])` should return `"Empty"`.
|
||||
|
||||
```js
|
||||
assert.equal(dive([[ "-", "-", "-"], [ "-", "-", "-"], [ "O", "X", "X"]], [1, 2]), "Empty");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function dive(map, coordinates) {
|
||||
|
||||
return map;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function dive(map, coordinates) {
|
||||
const [row, col] = coordinates;
|
||||
const target = map[row][col];
|
||||
|
||||
if (target === "-") {
|
||||
return "Empty";
|
||||
}
|
||||
|
||||
if (target === "O") {
|
||||
for (let r = 0; r < map.length; r++) {
|
||||
for (let c = 0; c < map[r].length; c++) {
|
||||
if ((r !== row || c !== col) && map[r][c] === "O") {
|
||||
return "Found";
|
||||
}
|
||||
}
|
||||
}
|
||||
return "Recovered";
|
||||
}
|
||||
|
||||
return "Found";
|
||||
}
|
||||
```
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
---
|
||||
id: 68d30845cc08266018fc46bc
|
||||
title: "Challenge 76: Complementary DNA"
|
||||
challengeType: 28
|
||||
dashedName: challenge-76
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string representing a DNA sequence, return its complementary strand using the following rules:
|
||||
|
||||
- DNA consists of the letters `"A"`, `"C"`, `"G"`, and `"T"`.
|
||||
- The letters `"A"` and `"T"` complement each other.
|
||||
- The letters `"C"` and `"G"` complement each other.
|
||||
|
||||
For example, given `"ACGT"`, return `"TGCA"`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`complementaryDNA("ACGT")` should return `"TGCA"`.
|
||||
|
||||
```js
|
||||
assert.equal(complementaryDNA("ACGT"), "TGCA");
|
||||
```
|
||||
|
||||
`complementaryDNA("ATGCGTACGTTAGC")` should return `"TACGCATGCAATCG"`.
|
||||
|
||||
```js
|
||||
assert.equal(complementaryDNA("ATGCGTACGTTAGC"), "TACGCATGCAATCG");
|
||||
```
|
||||
|
||||
`complementaryDNA("GGCTTACGATCGAAG")` should return `"CCGAATGCTAGCTTC"`.
|
||||
|
||||
```js
|
||||
assert.equal(complementaryDNA("GGCTTACGATCGAAG"), "CCGAATGCTAGCTTC");
|
||||
```
|
||||
|
||||
`complementaryDNA("GATCTAGCTAGGCTAGCTAG")` should return `"CTAGATCGATCCGATCGATC"`.
|
||||
|
||||
```js
|
||||
assert.equal(complementaryDNA("GATCTAGCTAGGCTAGCTAG"), "CTAGATCGATCCGATCGATC");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function complementaryDNA(strand) {
|
||||
|
||||
return strand;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function complementaryDNA(strand) {
|
||||
const complements = { A: "T", T: "A", C: "G", G: "C" };
|
||||
return strand
|
||||
.split("")
|
||||
.map(c => complements[c])
|
||||
.join("");
|
||||
}
|
||||
```
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
---
|
||||
id: 68d30845cc08266018fc46bd
|
||||
title: "Challenge 77: Duration Formatter"
|
||||
challengeType: 28
|
||||
dashedName: challenge-77
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given an integer number of seconds, return a string representing the same duration in the format `"H:MM:SS"`, where `"H"` is the number of hours, `"MM"` is the number of minutes, and `"SS"` is the number of seconds. Return the time using the following rules:
|
||||
|
||||
- Seconds: Should always be two digits.
|
||||
- Minutes: Should omit leading zeros when they aren't needed. Use `"0"` if the duration is less than one minute.
|
||||
- Hours: Should be included only if they're greater than zero.
|
||||
|
||||
# --hints--
|
||||
|
||||
`format(500)` should return `"8:20"`.
|
||||
|
||||
```js
|
||||
assert.equal(format(500), "8:20");
|
||||
```
|
||||
|
||||
`format(4000)` should return `"1:06:40"`.
|
||||
|
||||
```js
|
||||
assert.equal(format(4000), "1:06:40");
|
||||
```
|
||||
|
||||
`format(1)` should return `"0:01"`.
|
||||
|
||||
```js
|
||||
assert.equal(format(1), "0:01");
|
||||
```
|
||||
|
||||
`format(5555)` should return `"1:32:35"`.
|
||||
|
||||
```js
|
||||
assert.equal(format(5555), "1:32:35");
|
||||
```
|
||||
|
||||
`format(99999)` should return `"27:46:39"`.
|
||||
|
||||
```js
|
||||
assert.equal(format(99999), "27:46:39");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function format(seconds) {
|
||||
|
||||
return seconds;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function format(seconds) {
|
||||
const h = Math.floor(seconds / 3600);
|
||||
const m = Math.floor((seconds % 3600) / 60);
|
||||
const s = seconds % 60;
|
||||
|
||||
const secondsStr = s.toString().padStart(2, "0");
|
||||
const minutesStr = m.toString();
|
||||
|
||||
if (h > 0) {
|
||||
const hoursStr = h.toString();
|
||||
return `${hoursStr}:${minutesStr.padStart(2, "0")}:${secondsStr}`;
|
||||
} else {
|
||||
return `${minutesStr}:${secondsStr}`;
|
||||
}
|
||||
}
|
||||
```
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
---
|
||||
id: 68d30845cc08266018fc46be
|
||||
title: "Challenge 78: Integer Sequence"
|
||||
challengeType: 28
|
||||
dashedName: challenge-78
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a positive integer, return a string with all of the integers from `1` up to, and including, the given number, in numerical order.
|
||||
|
||||
For example, given `5`, return `"12345"`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sequence(5)` should return `"12345"`.
|
||||
|
||||
```js
|
||||
assert.equal(sequence(5), "12345");
|
||||
```
|
||||
|
||||
`sequence(10)` should return `"12345678910"`.
|
||||
|
||||
```js
|
||||
assert.equal(sequence(10), "12345678910");
|
||||
```
|
||||
|
||||
`sequence(1)` should return `"1"`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(sequence(1), "1");
|
||||
```
|
||||
|
||||
`sequence(27)` should return `"123456789101112131415161718192021222324252627"`.
|
||||
|
||||
```js
|
||||
assert.equal(sequence(27), "123456789101112131415161718192021222324252627");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function sequence(n) {
|
||||
|
||||
return n;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function sequence(n) {
|
||||
let result = "";
|
||||
for (let i = 1; i <= n; i++) {
|
||||
result += i;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
```
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
---
|
||||
id: 68d30fc57588d97fd3027b30
|
||||
title: "Challenge 79: Navigator"
|
||||
challengeType: 28
|
||||
dashedName: challenge-79
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
On October 28, 1994, Netscape Navigator was released, helping millions explore the early web.
|
||||
|
||||
Given an array of browser commands you executed on Netscape Navigator, return the current page you are on after executing all the commands using the following rules:
|
||||
|
||||
- You always start on the `"Home"` page, which will not be included in the commands array.
|
||||
- Valid commands are:
|
||||
- `"Visit Page"`: Where `"Page"` is the name of the page you are visiting. For example, `"Visit About"` takes you to the `"About"` page. When you visit a new page, make sure to discard any forward history you have.
|
||||
- `"Back"`: Takes you to the previous page in your history or stays on the current page if there isn't one.
|
||||
- `"Forward"`: Takes you forward in the history to the page you came from or stays on the current page if there isn't one.
|
||||
|
||||
For example, given `["Visit About Us", "Back", "Forward"]`, return `"About Us"`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`navigate(["Visit About Us", "Back", "Forward"])` should return `"About Us"`.
|
||||
|
||||
```js
|
||||
assert.equal(navigate(["Visit About Us", "Back", "Forward"]), "About Us");
|
||||
```
|
||||
|
||||
`navigate(["Forward"])` should return `"Home"`.
|
||||
|
||||
```js
|
||||
assert.equal(navigate(["Forward"]), "Home");
|
||||
```
|
||||
|
||||
`navigate(["Back"])` should return `"Home"`.
|
||||
|
||||
```js
|
||||
assert.equal(navigate(["Back"]), "Home");
|
||||
```
|
||||
|
||||
`navigate(["Visit About Us", "Visit Gallery"])` should return `"Gallery"`.
|
||||
|
||||
```js
|
||||
assert.equal(navigate(["Visit About Us", "Visit Gallery"]), "Gallery");
|
||||
```
|
||||
|
||||
`navigate(["Visit About Us", "Visit Gallery", "Back", "Back"])` should return `"Home"`.
|
||||
|
||||
```js
|
||||
assert.equal(navigate(["Visit About Us", "Visit Gallery", "Back", "Back"]), "Home");
|
||||
```
|
||||
|
||||
`navigate(["Visit About", "Visit Gallery", "Back", "Visit Contact", "Forward"])` should return `"Contact"`.
|
||||
|
||||
```js
|
||||
assert.equal(navigate(["Visit About", "Visit Gallery", "Back", "Visit Contact", "Forward"]), "Contact");
|
||||
```
|
||||
|
||||
`navigate(["Visit About Us", "Visit Visit Us", "Forward", "Visit Contact Us", "Back"])` should return `"Visit Us"`.
|
||||
|
||||
```js
|
||||
assert.equal(navigate(["Visit About Us", "Visit Visit Us", "Forward", "Visit Contact Us", "Back"]), "Visit Us");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function navigate(commands) {
|
||||
|
||||
return commands;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function navigate(commands) {
|
||||
const history = ["Home"];
|
||||
let currentPageIndex = 0;
|
||||
|
||||
for (const command of commands) {
|
||||
if (command.startsWith("Visit")) {
|
||||
history.splice(currentPageIndex + 1);
|
||||
history.push(command.slice(6));
|
||||
currentPageIndex++;
|
||||
} else if(command === "Back" && currentPageIndex > 0) {
|
||||
currentPageIndex--;
|
||||
} else if (command === "Forward" && currentPageIndex < history.length - 1) {
|
||||
currentPageIndex++;
|
||||
}
|
||||
}
|
||||
|
||||
return history[currentPageIndex];
|
||||
}
|
||||
```
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
---
|
||||
id: 68e39ed6106dac2f0a98fd62
|
||||
title: "Challenge 80: Email Sorter"
|
||||
challengeType: 28
|
||||
dashedName: challenge-80
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
On October 29, 1971, the first email ever was sent, introducing the `username@domain` format we still use. Now, there are billions of email addresses.
|
||||
|
||||
In this challenge, you are given a list of email addresses and need to sort them alphabetically by domain name first (the part after the `@`), and username second (the part before the `@`).
|
||||
|
||||
- Sorting should be case-insensitive.
|
||||
- If more than one email has the same domain, sort them by their username.
|
||||
- Return an array of the sorted addresses.
|
||||
- Returned addresses should retain their original case.
|
||||
|
||||
For example, given `["jill@mail.com", "john@example.com", "jane@example.com"]`, return `["jane@example.com", "john@example.com", "jill@mail.com"]`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sort(["jill@mail.com", "john@example.com", "jane@example.com"])` should return `["jane@example.com", "john@example.com", "jill@mail.com"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(sort(["jill@mail.com", "john@example.com", "jane@example.com"]), ["jane@example.com", "john@example.com", "jill@mail.com"]);
|
||||
```
|
||||
|
||||
`sort(["bob@mail.com", "alice@zoo.com", "carol@mail.com"])` should return `["bob@mail.com", "carol@mail.com", "alice@zoo.com"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(sort(["bob@mail.com", "alice@zoo.com", "carol@mail.com"]), ["bob@mail.com", "carol@mail.com", "alice@zoo.com"]);
|
||||
```
|
||||
|
||||
`sort(["user@z.com", "user@y.com", "user@x.com"])` should return `["user@x.com", "user@y.com", "user@z.com"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(sort(["user@z.com", "user@y.com", "user@x.com"]), ["user@x.com", "user@y.com", "user@z.com"]);
|
||||
```
|
||||
|
||||
`sort(["sam@MAIL.com", "amy@mail.COM", "bob@Mail.com"])` should return `["amy@mail.COM", "bob@Mail.com", "sam@MAIL.com"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(sort(["sam@MAIL.com", "amy@mail.COM", "bob@Mail.com"]), ["amy@mail.COM", "bob@Mail.com", "sam@MAIL.com"]);
|
||||
```
|
||||
|
||||
`sort(["simon@beta.com", "sammy@alpha.com", "Sarah@Alpha.com", "SAM@ALPHA.com", "Simone@Beta.com", "sara@alpha.com"])` should return `["SAM@ALPHA.com", "sammy@alpha.com", "sara@alpha.com", "Sarah@Alpha.com", "simon@beta.com", "Simone@Beta.com"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(sort(["simon@beta.com", "sammy@alpha.com", "Sarah@Alpha.com", "SAM@ALPHA.com", "Simone@Beta.com", "sara@alpha.com"]), ["SAM@ALPHA.com", "sammy@alpha.com", "sara@alpha.com", "Sarah@Alpha.com", "simon@beta.com", "Simone@Beta.com"]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function sort(emails) {
|
||||
|
||||
return emails;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function sort(emails) {
|
||||
return emails.slice().sort((a, b) => {
|
||||
const [userA, domainA] = a.split('@');
|
||||
const [userB, domainB] = b.split('@');
|
||||
|
||||
const domainCompare = domainA.toLowerCase().localeCompare(domainB.toLowerCase());
|
||||
if (domainCompare !== 0) return domainCompare;
|
||||
|
||||
return userA.toLowerCase().localeCompare(userB.toLowerCase());
|
||||
});
|
||||
}
|
||||
```
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
---
|
||||
id: 68e39ed6106dac2f0a98fd63
|
||||
title: "Challenge 81: Nth Prime"
|
||||
challengeType: 28
|
||||
dashedName: challenge-81
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
A prime number is a positive integer greater than 1 that is divisible only by 1 and itself. The first five prime numbers are `2`, `3`, `5`, `7`, and `11`.
|
||||
|
||||
Given a positive integer `n`, return the `n`th prime number. For example, given `5` return the 5th prime number: `11`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`nthPrime(5)` should return `11`.
|
||||
|
||||
```js
|
||||
assert.equal(nthPrime(5), 11);
|
||||
```
|
||||
|
||||
`nthPrime(10)` should return `29`.
|
||||
|
||||
```js
|
||||
assert.equal(nthPrime(10), 29);
|
||||
```
|
||||
|
||||
`nthPrime(16)` should return `53`.
|
||||
|
||||
```js
|
||||
assert.equal(nthPrime(16), 53);
|
||||
```
|
||||
|
||||
`nthPrime(99)` should return `523`.
|
||||
|
||||
```js
|
||||
assert.equal(nthPrime(99), 523);
|
||||
```
|
||||
|
||||
`nthPrime(1000)` should return `7919`.
|
||||
|
||||
```js
|
||||
assert.equal(nthPrime(1000), 7919);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function nthPrime(n) {
|
||||
|
||||
return n;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function nthPrime(n) {
|
||||
const primes = [];
|
||||
let num = 2;
|
||||
|
||||
while (primes.length < n) {
|
||||
let isPrime = true;
|
||||
for (let i = 2; i * i <= num; i++) {
|
||||
if (num % i === 0) {
|
||||
isPrime = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (isPrime) primes.push(num);
|
||||
num++;
|
||||
}
|
||||
|
||||
return primes[n - 1];
|
||||
}
|
||||
```
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
---
|
||||
id: 68e39ed6106dac2f0a98fd64
|
||||
title: "Challenge 82: SpOoKy~CaSe"
|
||||
challengeType: 28
|
||||
dashedName: challenge-82
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string representing a variable name, convert it to "spooky case" using the following constraints:
|
||||
|
||||
- Replace all underscores (`_`), and hyphens (`-`) with a tilde (`~`).
|
||||
- Capitalize the first letter of the string, and every other letter after that. Ignore the tilde character when counting. Make all other letters lowercase.
|
||||
|
||||
For example, given `hello_world`, return `HeLlO~wOrLd`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`spookify("hello_world")` should return `"HeLlO~wOrLd"`.
|
||||
|
||||
```js
|
||||
assert.equal(spookify("hello_world"), "HeLlO~wOrLd");
|
||||
```
|
||||
|
||||
`spookify("Spooky_Case")` should return `"SpOoKy~CaSe"`.
|
||||
|
||||
```js
|
||||
assert.equal(spookify("Spooky_Case"), "SpOoKy~CaSe");
|
||||
```
|
||||
|
||||
`spookify("TRICK-or-TREAT")` should return `"TrIcK~oR~tReAt"`.
|
||||
|
||||
```js
|
||||
assert.equal(spookify("TRICK-or-TREAT"), "TrIcK~oR~tReAt");
|
||||
```
|
||||
|
||||
`spookify("c_a-n_d-y_-b-o_w_l")` should return `"C~a~N~d~Y~~b~O~w~L"`.
|
||||
|
||||
```js
|
||||
assert.equal(spookify("c_a-n_d-y_-b-o_w_l"), "C~a~N~d~Y~~b~O~w~L");
|
||||
```
|
||||
|
||||
`spookify("thE_hAUntEd-hOUsE-Is-fUll_Of_ghOsts")` should return `"ThE~hAuNtEd~HoUsE~iS~fUlL~oF~gHoStS"`.
|
||||
|
||||
```js
|
||||
assert.equal(spookify("thE_hAUntEd-hOUsE-Is-fUll_Of_ghOsts"), "ThE~hAuNtEd~HoUsE~iS~fUlL~oF~gHoStS");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function spookify(boo) {
|
||||
|
||||
return boo;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function spookify(boo) {
|
||||
const replaced = boo.replace(/[_-]/g, "~");
|
||||
|
||||
let result = "";
|
||||
let capitalize = true;
|
||||
|
||||
for (let char of replaced) {
|
||||
if (char === "~") {
|
||||
result += char;
|
||||
} else {
|
||||
result += capitalize ? char.toUpperCase() : char.toLowerCase();
|
||||
capitalize = !capitalize;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
```
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
---
|
||||
id: 68e39ed6106dac2f0a98fd65
|
||||
title: "Challenge 83: Signature Validation"
|
||||
challengeType: 28
|
||||
dashedName: challenge-83
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a message string, a secret key string, and a signature number, determine if the signature is valid using this encoding method:
|
||||
|
||||
- Letters in the message and secret key have these values:
|
||||
- `a` to `z` have values `1` to `26` respectively.
|
||||
- `A` to `Z` have values `27` to `52` respectively.
|
||||
- All other characters have no value.
|
||||
- Compute the signature by taking the sum of the message plus the sum of the secret key.
|
||||
|
||||
For example, given the message `"foo"` and the secret key `"bar"`, the signature would be `57`:
|
||||
|
||||
```md
|
||||
f (6) + o (15) + o (15) = 36
|
||||
b (2) + a (1) + r (18) = 21
|
||||
36 + 21 = 57
|
||||
```
|
||||
|
||||
Check if the computed signature matches the provided signature.
|
||||
|
||||
# --hints--
|
||||
|
||||
`verify("foo", "bar", 57)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(verify("foo", "bar", 57));
|
||||
```
|
||||
|
||||
`verify("foo", "bar", 54)` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(verify("foo", "bar", 54));
|
||||
```
|
||||
|
||||
`verify("freeCodeCamp", "Rocks", 238)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(verify("freeCodeCamp", "Rocks", 238));
|
||||
```
|
||||
|
||||
`verify("Is this valid?", "No", 210)` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(verify("Is this valid?", "No", 210));
|
||||
```
|
||||
|
||||
`verify("Is this valid?", "Yes", 233)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(verify("Is this valid?", "Yes", 233));
|
||||
```
|
||||
|
||||
`verify("Check out the freeCodeCamp podcast,", "in the mobile app", 514)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(verify("Check out the freeCodeCamp podcast,", "in the mobile app", 514));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function verify(message, key, signature) {
|
||||
|
||||
return message;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function verify(message, key, signature) {
|
||||
function charValue(ch) {
|
||||
if (ch >= 'a' && ch <= 'z') return ch.charCodeAt(0) - 'a'.charCodeAt(0) + 1;
|
||||
if (ch >= 'A' && ch <= 'Z') return ch.charCodeAt(0) - 'A'.charCodeAt(0) + 27;
|
||||
return 0;
|
||||
}
|
||||
|
||||
function computeSum(str) {
|
||||
let sum = 0;
|
||||
for (let ch of str) {
|
||||
sum += charValue(ch);
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
const total = computeSum(message) + computeSum(key);
|
||||
return total === signature;
|
||||
}
|
||||
```
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
---
|
||||
id: 68e39ed6106dac2f0a98fd66
|
||||
title: "Challenge 84: Infected"
|
||||
challengeType: 28
|
||||
dashedName: challenge-84
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
On November 2nd, 1988, the first major internet worm was released, infecting about 10% of computers connected to the internet after only a day.
|
||||
|
||||
In this challenge, you are given a number of days that have passed since an internet worm was released, and you need to determine how many computers are infected using the following rules:
|
||||
|
||||
- On day 0, the first computer is infected.
|
||||
- Each subsequent day, the number of infected computers doubles.
|
||||
- Every 3rd day, a patch is applied after the virus spreads and reduces the number of infected computers by 20%. Round the number of patched computers up to the nearest whole number.
|
||||
|
||||
For example, on:
|
||||
|
||||
- Day 0: 1 total computer is infected.
|
||||
- Day 1: 2 total computers are infected.
|
||||
- Day 2: 4 total computers are infected.
|
||||
- Day 3: 8 total computers are infected. Then, apply the patch: 8 infected * 20% = 1.6 patched. Round 1.6 up to 2. 8 computers infected - 2 patched = 6 total computers infected after day 3.
|
||||
|
||||
Return the number of total infected computers after the given amount of days have passed.
|
||||
|
||||
# --hints--
|
||||
|
||||
`infected(1)` should return `2`.
|
||||
|
||||
```js
|
||||
assert.equal(infected(1), 2);
|
||||
```
|
||||
|
||||
`infected(3)` should return `6`.
|
||||
|
||||
```js
|
||||
assert.equal(infected(3), 6);
|
||||
```
|
||||
|
||||
`infected(8)` should return `152`.
|
||||
|
||||
```js
|
||||
assert.equal(infected(8), 152);
|
||||
```
|
||||
|
||||
`infected(17)` should return `39808`.
|
||||
|
||||
```js
|
||||
assert.equal(infected(17), 39808);
|
||||
```
|
||||
|
||||
`infected(25)` should return `5217638`.
|
||||
|
||||
```js
|
||||
assert.equal(infected(25), 5217638);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function infected(days) {
|
||||
|
||||
return days;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function infected(days) {
|
||||
let infected = 1;
|
||||
|
||||
for (let day = 1; day <= days; day++) {
|
||||
infected *= 2;
|
||||
|
||||
if (day % 3 === 0) {
|
||||
let patched = Math.ceil(infected * 0.2);
|
||||
infected -= patched;
|
||||
}
|
||||
}
|
||||
|
||||
return infected;
|
||||
}
|
||||
```
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
---
|
||||
id: 68ee9e3066cfd4eb2328e8a4
|
||||
title: "Challenge 85: Word Counter"
|
||||
challengeType: 28
|
||||
dashedName: challenge-85
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a sentence string, return the number of words that are in the sentence.
|
||||
|
||||
- Words are any sequence of non-space characters and are separated by a single space.
|
||||
|
||||
# --hints--
|
||||
|
||||
`countWords("Hello world")` should return `2`.
|
||||
|
||||
```js
|
||||
assert.equal(countWords("Hello world"), 2);
|
||||
```
|
||||
|
||||
`countWords("The quick brown fox jumps over the lazy dog.")` should return `9`.
|
||||
|
||||
```js
|
||||
assert.equal(countWords("The quick brown fox jumps over the lazy dog."), 9);
|
||||
```
|
||||
|
||||
`countWords("I like coding challenges!")` should return `4`.
|
||||
|
||||
```js
|
||||
assert.equal(countWords("I like coding challenges!"), 4);
|
||||
```
|
||||
|
||||
`countWords("Complete the challenge in JavaScript and Python.")` should return `7`.
|
||||
|
||||
```js
|
||||
assert.equal(countWords("Complete the challenge in JavaScript and Python."), 7);
|
||||
```
|
||||
|
||||
`countWords("The missing semi-colon crashed the entire internet.")` should return `7`.
|
||||
|
||||
```js
|
||||
assert.equal(countWords("The missing semi-colon crashed the entire internet."), 7);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function countWords(sentence) {
|
||||
|
||||
return sentence;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function countWords(sentence) {
|
||||
|
||||
return sentence.split(' ').length;
|
||||
}
|
||||
```
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
---
|
||||
id: 68ee9e3066cfd4eb2328e8a5
|
||||
title: "Challenge 86: Image Search"
|
||||
challengeType: 28
|
||||
dashedName: challenge-86
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
On November 4th, 2001, Google launched its image search, allowing people to find images using search terms. In this challenge, you will imitate the image search.
|
||||
|
||||
Given an array of image names and a search term, return an array of image names containing the search term.
|
||||
|
||||
- Ignore the case when matching the search terms.
|
||||
- Return the images in the same order they appear in the input array.
|
||||
|
||||
# --hints--
|
||||
|
||||
`imageSearch(["dog.png", "cat.jpg", "parrot.jpeg"], "dog")` should return `["dog.png"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(imageSearch(["dog.png", "cat.jpg", "parrot.jpeg"], "dog"), ["dog.png"]);
|
||||
```
|
||||
|
||||
`imageSearch(["Sunset.jpg", "Beach.png", "sunflower.jpeg"], "sun")` should return `["Sunset.jpg", "sunflower.jpeg"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(imageSearch(["Sunset.jpg", "Beach.png", "sunflower.jpeg"], "sun"), ["Sunset.jpg", "sunflower.jpeg"]);
|
||||
```
|
||||
|
||||
`imageSearch(["Moon.png", "sun.jpeg", "stars.png"], "PNG")` should return `["Moon.png", "stars.png"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(imageSearch(["Moon.png", "sun.jpeg", "stars.png"], "PNG"), ["Moon.png", "stars.png"]);
|
||||
```
|
||||
|
||||
`imageSearch(["cat.jpg", "dogToy.jpeg", "kitty-cat.png", "catNip.jpeg", "franken_cat.gif"], "Cat")` should return `["cat.jpg", "kitty-cat.png", "catNip.jpeg", "franken_cat.gif"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(imageSearch(["cat.jpg", "dogToy.jpeg", "kitty-cat.png", "catNip.jpeg", "franken_cat.gif"], "Cat"), ["cat.jpg", "kitty-cat.png", "catNip.jpeg", "franken_cat.gif"]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function imageSearch(images, term) {
|
||||
|
||||
return images;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function imageSearch(images, term) {
|
||||
const lowerTerm = term.toLowerCase();
|
||||
return images.filter(img => img.toLowerCase().includes(lowerTerm));
|
||||
}
|
||||
```
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
---
|
||||
id: 68ee9e3066cfd4eb2328e8a6
|
||||
title: "Challenge 87: Matrix Builder"
|
||||
challengeType: 28
|
||||
dashedName: challenge-87
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given two integers (a number of rows and a number of columns), return a matrix (an array of arrays) filled with zeros (`0`) of the given size.
|
||||
|
||||
For example, given `2` and `3`, return:
|
||||
|
||||
```json
|
||||
[
|
||||
[0, 0, 0],
|
||||
[0, 0, 0]
|
||||
]
|
||||
```
|
||||
|
||||
# --hints--
|
||||
|
||||
`buildMatrix(2, 3)` should return `[[0, 0, 0], [0, 0, 0]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(buildMatrix(2, 3), [[0, 0, 0], [0, 0, 0]]);
|
||||
```
|
||||
|
||||
`buildMatrix(3, 2)` should return `[[0, 0], [0, 0], [0, 0]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(buildMatrix(3, 2), [[0, 0], [0, 0], [0, 0]]);
|
||||
```
|
||||
|
||||
`buildMatrix(4, 3)` should return `[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(buildMatrix(4, 3), [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]);
|
||||
```
|
||||
|
||||
`buildMatrix(9, 1)` should return `[[0], [0], [0], [0], [0], [0], [0], [0], [0]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(buildMatrix(9, 1), [[0], [0], [0], [0], [0], [0], [0], [0], [0]]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function buildMatrix(rows, cols) {
|
||||
|
||||
return rows;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function buildMatrix(rows, cols) {
|
||||
const matrix = [];
|
||||
for (let i = 0; i < rows; i++) {
|
||||
const row = new Array(cols).fill(0);
|
||||
matrix.push(row);
|
||||
}
|
||||
return matrix;
|
||||
}
|
||||
```
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
---
|
||||
id: 68ee9e3066cfd4eb2328e8a7
|
||||
title: "Challenge 88: Weekday Finder"
|
||||
challengeType: 28
|
||||
dashedName: challenge-88
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string date in the format `YYYY-MM-DD`, return the day of the week.
|
||||
|
||||
Valid return days are:
|
||||
|
||||
- `"Sunday"`
|
||||
- `"Monday"`
|
||||
- `"Tuesday"`
|
||||
- `"Wednesday"`
|
||||
- `"Thursday"`
|
||||
- `"Friday"`
|
||||
- `"Saturday"`
|
||||
|
||||
Be sure to ignore time zones.
|
||||
|
||||
# --hints--
|
||||
|
||||
`getWeekday("2025-11-06")` should return `Thursday`.
|
||||
|
||||
```js
|
||||
assert.equal(getWeekday("2025-11-06"), "Thursday");
|
||||
```
|
||||
|
||||
`getWeekday("1999-12-31")` should return `Friday`.
|
||||
|
||||
```js
|
||||
assert.equal(getWeekday("1999-12-31"), "Friday");
|
||||
```
|
||||
|
||||
`getWeekday("1111-11-11")` should return `Saturday`.
|
||||
|
||||
```js
|
||||
assert.equal(getWeekday("1111-11-11"), "Saturday");
|
||||
```
|
||||
|
||||
`getWeekday("2112-12-21")` should return `Wednesday`.
|
||||
|
||||
```js
|
||||
assert.equal(getWeekday("2112-12-21"), "Wednesday");
|
||||
```
|
||||
|
||||
`getWeekday("2345-10-01")` should return `Monday`.
|
||||
|
||||
```js
|
||||
assert.equal(getWeekday("2345-10-01"), "Monday");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function getWeekday(dateString) {
|
||||
|
||||
return dateString;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function getWeekday(dateString) {
|
||||
const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
|
||||
const [year, month, day] = dateString.split("-").map(Number);
|
||||
const date = new Date(Date.UTC(year, month - 1, day));
|
||||
|
||||
return days[date.getUTCDay()];
|
||||
}
|
||||
```
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
---
|
||||
id: 68ee9e3066cfd4eb2328e8a8
|
||||
title: "Challenge 89: Counting Cards"
|
||||
challengeType: 28
|
||||
dashedName: challenge-89
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
A standard deck of playing cards has 13 unique cards in each suit. Given an integer representing the number of cards to pick from the deck, return the number of unique combinations of cards you can pick.
|
||||
|
||||
- Order does not matter. Picking card A then card B is the same as picking card B then card A.
|
||||
|
||||
For example, given `52`, return `1`. There's only one combination of 52 cards to pick from a 52 card deck. And given `2`, return `1326`, There's 1326 card combinations you can end up with when picking 2 cards from the deck.
|
||||
|
||||
# --hints--
|
||||
|
||||
`combinations(52)` should return `1`.
|
||||
|
||||
```js
|
||||
assert.equal(combinations(52), 1);
|
||||
```
|
||||
|
||||
`combinations(1)` should return `52`.
|
||||
|
||||
```js
|
||||
assert.equal(combinations(1), 52);
|
||||
```
|
||||
|
||||
`combinations(2)` should return `1326`.
|
||||
|
||||
```js
|
||||
assert.equal(combinations(2), 1326);
|
||||
```
|
||||
|
||||
`combinations(5)` should return `2598960`.
|
||||
|
||||
```js
|
||||
assert.equal(combinations(5), 2598960);
|
||||
```
|
||||
|
||||
`combinations(10)` should return `15820024220`.
|
||||
|
||||
```js
|
||||
assert.equal(combinations(10), 15820024220);
|
||||
```
|
||||
|
||||
`combinations(50)` should return `1326`.
|
||||
|
||||
```js
|
||||
assert.equal(combinations(50), 1326);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function combinations(cards) {
|
||||
|
||||
return cards;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function combinations(cards) {
|
||||
const n = 52;
|
||||
|
||||
function factorial(x) {
|
||||
let result = 1;
|
||||
for (let i = 2; i <= x; i++) {
|
||||
result *= i;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
return factorial(n) / (factorial(cards) * factorial(n - cards));
|
||||
}
|
||||
```
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
---
|
||||
id: 68f6587287ad1f4ad39b0c7c
|
||||
title: "Challenge 90: Character Limit"
|
||||
challengeType: 28
|
||||
dashedName: challenge-90
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In this challenge, you are given a string and need to determine if it fits in a social media post. Return the following strings based on the rules given:
|
||||
|
||||
- `"short post"` if it fits within a 40-character limit.
|
||||
- `"long post"` if it's greater than 40 characters and fits within an 80-character limit.
|
||||
- `"invalid post"` if it's too long to fit within either limit.
|
||||
|
||||
# --hints--
|
||||
|
||||
`canPost("Hello world")` should return `"short post"`.
|
||||
|
||||
```js
|
||||
assert.equal(canPost("Hello world"), "short post");
|
||||
```
|
||||
|
||||
`canPost("This is a longer message but still under eighty characters.")` should return `"long post"`.
|
||||
|
||||
```js
|
||||
assert.equal(canPost("This is a longer message but still under eighty characters."), "long post");
|
||||
```
|
||||
|
||||
`canPost("This message is too long to fit into either of the character limits for a social media post.")` should return `"invalid post"`.
|
||||
|
||||
```js
|
||||
assert.equal(canPost("This message is too long to fit into either of the character limits for a social media post."), "invalid post");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function canPost(message) {
|
||||
|
||||
return message;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function canPost(message) {
|
||||
if (message.length <= 40) {
|
||||
return "short post"
|
||||
} else if (message.length <= 80) {
|
||||
return "long post"
|
||||
} else {
|
||||
return "invalid post"
|
||||
}
|
||||
}
|
||||
```
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
---
|
||||
id: 68f6587287ad1f4ad39b0c7d
|
||||
title: "Challenge 91: Word Search"
|
||||
challengeType: 28
|
||||
dashedName: challenge-91
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a matrix (an array of arrays) of single letters and a word to find, return the start and end indices of the word in the matrix.
|
||||
|
||||
- The given matrix will be filled with all lowercase letters (`a-z`).
|
||||
- The word to find will always be in the matrix exactly once.
|
||||
- The word to find will always be in a straight line in one of these directions:
|
||||
- left to right
|
||||
- right to left
|
||||
- top to bottom
|
||||
- bottom to top
|
||||
|
||||
For example, given the matrix:
|
||||
|
||||
```md
|
||||
[
|
||||
["a", "c", "t"],
|
||||
["t", "a", "t"],
|
||||
["c", "t", "c"]
|
||||
]
|
||||
```
|
||||
|
||||
And the word `"cat"`, return:
|
||||
|
||||
```md
|
||||
[[0, 1], [2, 1]]
|
||||
```
|
||||
|
||||
Where `[0, 1]` are the indices for the `"c"` (start of the word), and `[2, 1]` are the indices for the `"t"` (end of the word).
|
||||
|
||||
# --hints--
|
||||
|
||||
`findWord([["a", "c", "t"], ["t", "a", "t"], ["c", "t", "c"]], "cat")` should return `[[0, 1], [2, 1]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(findWord([["a", "c", "t"], ["t", "a", "t"], ["c", "t", "c"]], "cat"), [[0, 1], [2, 1]]);
|
||||
```
|
||||
|
||||
`findWord([["d", "o", "g"], ["o", "g", "d"], ["d", "g", "o"]], "dog")` should return `[[0, 0], [0, 2]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(findWord([["d", "o", "g"], ["o", "g", "d"], ["d", "g", "o"]], "dog"), [[0, 0], [0, 2]]);
|
||||
```
|
||||
|
||||
`findWord([["h", "i", "s", "h"], ["i", "s", "f", "s"], ["f", "s", "i", "i"], ["s", "h", "i", "f"]], "fish")` should return `[[3, 3], [0, 3]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(findWord([["h", "i", "s", "h"], ["i", "s", "f", "s"], ["f", "s", "i", "i"], ["s", "h", "i", "f"]], "fish"), [[3, 3], [0, 3]]);
|
||||
```
|
||||
|
||||
`findWord([["f", "x", "o", "x"], ["o", "x", "o", "f"], ["f", "o", "f", "x"], ["f", "x", "x", "o"]], "fox")` should return `[[1, 3], [1, 1]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(findWord([["f", "x", "o", "x"], ["o", "x", "o", "f"], ["f", "o", "f", "x"], ["f", "x", "x", "o"]], "fox"), [[1, 3], [1, 1]]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function findWord(matrix, word) {
|
||||
|
||||
return matrix;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function findWord(matrix, word) {
|
||||
const rows = matrix.length;
|
||||
const cols = matrix[0].length;
|
||||
const len = word.length;
|
||||
|
||||
const directions = [
|
||||
[0, 1],
|
||||
[0, -1],
|
||||
[1, 0],
|
||||
[-1, 0]
|
||||
];
|
||||
|
||||
for (let r = 0; r < rows; r++) {
|
||||
for (let c = 0; c < cols; c++) {
|
||||
for (let [dr, dc] of directions) {
|
||||
let match = true;
|
||||
for (let i = 0; i < len; i++) {
|
||||
const nr = r + dr * i;
|
||||
const nc = c + dc * i;
|
||||
if (nr < 0 || nr >= rows || nc < 0 || nc >= cols || matrix[nr][nc] !== word[i]) {
|
||||
match = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (match) {
|
||||
return [
|
||||
[r, c],
|
||||
[r + dr * (len - 1), c + dc * (len - 1)]
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
---
|
||||
id: 68f6587287ad1f4ad39b0c7e
|
||||
title: "Challenge 92: Extension Extractor"
|
||||
challengeType: 28
|
||||
dashedName: challenge-92
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string representing a filename, return the extension of the file.
|
||||
|
||||
- The extension is the part of the filename that comes after the last period (`.`).
|
||||
- If the filename does not contain a period or ends with a period, return `"none"`.
|
||||
- The extension should be returned as-is, preserving case.
|
||||
|
||||
# --hints--
|
||||
|
||||
`getExtension("document.txt")` should return `"txt"`.
|
||||
|
||||
```js
|
||||
assert.equal(getExtension("document.txt"), "txt");
|
||||
```
|
||||
|
||||
`getExtension("README")` should return `"none"`.
|
||||
|
||||
```js
|
||||
assert.equal(getExtension("README"), "none");
|
||||
```
|
||||
|
||||
`getExtension("image.PNG")` should return `"PNG"`.
|
||||
|
||||
```js
|
||||
assert.equal(getExtension("image.PNG"), "PNG");
|
||||
```
|
||||
|
||||
`getExtension(".gitignore")` should return `"gitignore"`.
|
||||
|
||||
```js
|
||||
assert.equal(getExtension(".gitignore"), "gitignore");
|
||||
```
|
||||
|
||||
`getExtension("archive.tar.gz")` should return `"gz"`.
|
||||
|
||||
```js
|
||||
assert.equal(getExtension("archive.tar.gz"), "gz");
|
||||
```
|
||||
|
||||
`getExtension("final.draft.")` should return `"none"`.
|
||||
|
||||
```js
|
||||
assert.equal(getExtension("final.draft."), "none");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function getExtension(filename) {
|
||||
|
||||
return filename;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function getExtension(filename) {
|
||||
const lastDot = filename.lastIndexOf('.');
|
||||
|
||||
if (lastDot === -1 || lastDot === filename.length - 1) {
|
||||
return "none";
|
||||
}
|
||||
|
||||
return filename.slice(lastDot + 1);
|
||||
}
|
||||
```
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
---
|
||||
id: 68f6587287ad1f4ad39b0c7f
|
||||
title: "Challenge 93: Vowels and Consonants"
|
||||
challengeType: 28
|
||||
dashedName: challenge-93
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string, return an array with the number of vowels and number of consonants in the string.
|
||||
|
||||
- Vowels consist of `a`, `e`, `i`, `o`, `u` in any case.
|
||||
- Consonants consist of all other letters in any case.
|
||||
- Ignore any non-letter characters.
|
||||
|
||||
For example, given `"Hello World"`, return `[3, 7]`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`count("Hello World")` should return `[3, 7]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(count("Hello World"), [3, 7]);
|
||||
```
|
||||
|
||||
`count("JavaScript")` should return `[3, 7]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(count("JavaScript"), [3, 7]);
|
||||
```
|
||||
|
||||
`count("Python")` should return `[1, 5]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(count("Python"), [1, 5]);
|
||||
```
|
||||
|
||||
`count("freeCodeCamp")` should return `[5, 7]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(count("freeCodeCamp"), [5, 7]);
|
||||
```
|
||||
|
||||
`count("Hello, World!")` should return `[3, 7]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(count("Hello, World!"), [3, 7]);
|
||||
```
|
||||
|
||||
`count("The quick brown fox jumps over the lazy dog.")` should return `[11, 24]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(count("The quick brown fox jumps over the lazy dog."), [11, 24]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function count(str) {
|
||||
|
||||
return str;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function count(str) {
|
||||
const vowels = 'aeiou';
|
||||
const consonants = 'bcdfghjklmnpqrstvwxyz';
|
||||
let v = 0, c = 0;
|
||||
|
||||
for (let i=0; i<str.length; i++) {
|
||||
if (vowels.includes(str[i].toLowerCase())) {
|
||||
v++;
|
||||
}
|
||||
if (consonants.includes(str[i].toLowerCase())) {
|
||||
c++;
|
||||
}
|
||||
}
|
||||
|
||||
return [v, c];
|
||||
}
|
||||
```
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
---
|
||||
id: 68f6587287ad1f4ad39b0c80
|
||||
title: "Challenge 94: Email Signature Generator"
|
||||
challengeType: 28
|
||||
dashedName: challenge-94
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given strings for a person's name, title, and company, return an email signature as a single string using the following rules:
|
||||
|
||||
- The name should appear first, preceded by a prefix that depends on the first letter of the name. For names starting with (case-insensitive):
|
||||
- `A-I`: Use `>>` as the prefix.
|
||||
- `J-R`: Use `--` as the prefix.
|
||||
- `S-Z`: Use `::` as the prefix.
|
||||
- A comma and space (`, `) should follow the name.
|
||||
- The title and company should follow the comma and space, separated by `" at "` (with spaces around it).
|
||||
|
||||
For example, given `"Quinn Waverly"`, `"Founder and CEO"`, and `"TechCo"` return `"--Quinn Waverly, Founder and CEO at TechCo"`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`generateSignature("Quinn Waverly", "Founder and CEO", "TechCo")` should return `"--Quinn Waverly, Founder and CEO at TechCo"`.
|
||||
|
||||
```js
|
||||
assert.equal(generateSignature("Quinn Waverly", "Founder and CEO", "TechCo"), "--Quinn Waverly, Founder and CEO at TechCo");
|
||||
```
|
||||
|
||||
`generateSignature("Alice Reed", "Engineer", "TechCo")` should return `">>Alice Reed, Engineer at TechCo"`.
|
||||
|
||||
```js
|
||||
assert.equal(generateSignature("Alice Reed", "Engineer", "TechCo"), ">>Alice Reed, Engineer at TechCo");
|
||||
```
|
||||
|
||||
`generateSignature("Tina Vaughn", "Developer", "example.com")` should return `"::Tina Vaughn, Developer at example.com"`.
|
||||
|
||||
```js
|
||||
assert.equal(generateSignature("Tina Vaughn", "Developer", "example.com"), "::Tina Vaughn, Developer at example.com");
|
||||
```
|
||||
|
||||
`generateSignature("B. B.", "Product Tester", "AcmeCorp")` should return `">>B. B., Product Tester at AcmeCorp"`.
|
||||
|
||||
```js
|
||||
assert.equal(generateSignature("B. B.", "Product Tester", "AcmeCorp"), ">>B. B., Product Tester at AcmeCorp");
|
||||
```
|
||||
|
||||
`generateSignature("windstorm", "Cloud Architect", "Atmospheronics")` should return `"::windstorm, Cloud Architect at Atmospheronics"`.
|
||||
|
||||
```js
|
||||
assert.equal(generateSignature("windstorm", "Cloud Architect", "Atmospheronics"), "::windstorm, Cloud Architect at Atmospheronics");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function generateSignature(name, title, company) {
|
||||
|
||||
return name;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function generateSignature(name, title, company) {
|
||||
const firstLetter = name[0].toUpperCase();
|
||||
let prefix;
|
||||
if ("ABCDEFGHI".includes(firstLetter)) {
|
||||
prefix = ">>";
|
||||
} else if ("JKLMNOPQR".includes(firstLetter)) {
|
||||
prefix = "--";
|
||||
} else {
|
||||
prefix = "::";
|
||||
}
|
||||
|
||||
return `${prefix}${name}, ${title} at ${company}`;
|
||||
}
|
||||
```
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
---
|
||||
id: 68f6587287ad1f4ad39b0c81
|
||||
title: "Challenge 95: Array Shift"
|
||||
challengeType: 28
|
||||
dashedName: challenge-95
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given an array and an integer representing how many positions to shift the array, return the shifted array.
|
||||
|
||||
- A positive integer shifts the array to the left.
|
||||
- A negative integer shifts the array to the right.
|
||||
- The shift wraps around the array.
|
||||
|
||||
For example, given `[1, 2, 3]` and `1`, shift the array 1 to the left, returning `[2, 3, 1]`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`shiftArray([1, 2, 3], 1)` should return `[2, 3, 1]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(shiftArray([1, 2, 3], 1), [2, 3, 1]);
|
||||
```
|
||||
|
||||
`shiftArray([1, 2, 3], -1)` should return `[3, 1, 2]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(shiftArray([1, 2, 3], -1), [3, 1, 2]);
|
||||
```
|
||||
|
||||
`shiftArray(["alpha", "bravo", "charlie"], 5)` should return `["charlie", "alpha", "bravo"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(shiftArray(["alpha", "bravo", "charlie"], 5), ["charlie", "alpha", "bravo"]);
|
||||
```
|
||||
|
||||
`shiftArray(["alpha", "bravo", "charlie"], -11)` should return `["bravo", "charlie", "alpha"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(shiftArray(["alpha", "bravo", "charlie"], -11), ["bravo", "charlie", "alpha"]);
|
||||
```
|
||||
|
||||
`shiftArray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 15)` should return `[5, 6, 7, 8, 9, 0, 1, 2, 3, 4]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(shiftArray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 15), [5, 6, 7, 8, 9, 0, 1, 2, 3, 4]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function shiftArray(arr, n) {
|
||||
|
||||
return arr;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function shiftArray(arr, n) {
|
||||
const len = arr.length;
|
||||
n = n % len;
|
||||
if (n < 0) n += len;
|
||||
|
||||
return arr.slice(n).concat(arr.slice(0, n));
|
||||
}
|
||||
```
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
---
|
||||
id: 68f6587287ad1f4ad39b0c82
|
||||
title: "Challenge 96: Is It the Weekend?"
|
||||
challengeType: 28
|
||||
dashedName: challenge-96
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a date in the format `"YYYY-MM-DD"`, return the number of days left until the weekend.
|
||||
|
||||
- The weekend starts on Saturday.
|
||||
- If the given date is Saturday or Sunday, return `"It's the weekend!"`.
|
||||
- Otherwise, return `"X days until the weekend."`, where `X` is the number of days until Saturday.
|
||||
- If `X` is `1`, use `"day"` (singular) instead of `"days"` (plural).
|
||||
- Make sure the calculation ignores your local timezone.
|
||||
|
||||
# --hints--
|
||||
|
||||
`daysUntilWeekend("2025-11-14")` should return `"1 day until the weekend."`.
|
||||
|
||||
```js
|
||||
assert.equal(daysUntilWeekend("2025-11-14"), "1 day until the weekend.");
|
||||
```
|
||||
|
||||
`daysUntilWeekend("2025-01-01")` should return `"3 days until the weekend."`.
|
||||
|
||||
```js
|
||||
assert.equal(daysUntilWeekend("2025-01-01"), "3 days until the weekend.");
|
||||
```
|
||||
|
||||
`daysUntilWeekend("2025-12-06")` should return `"It's the weekend!"`.
|
||||
|
||||
```js
|
||||
assert.equal(daysUntilWeekend("2025-12-06"), "It's the weekend!");
|
||||
```
|
||||
|
||||
`daysUntilWeekend("2026-01-27")` should return `"4 days until the weekend."`.
|
||||
|
||||
```js
|
||||
assert.equal(daysUntilWeekend("2026-01-27"), "4 days until the weekend.");
|
||||
```
|
||||
|
||||
`daysUntilWeekend("2026-09-07")` should return `"5 days until the weekend."`.
|
||||
|
||||
```js
|
||||
assert.equal(daysUntilWeekend("2026-09-07"), "5 days until the weekend.");
|
||||
```
|
||||
|
||||
`daysUntilWeekend("2026-11-29")` should return `"It's the weekend!"`.
|
||||
|
||||
```js
|
||||
assert.equal(daysUntilWeekend("2026-11-29"), "It's the weekend!");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function daysUntilWeekend(dateString) {
|
||||
|
||||
return dateString;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function daysUntilWeekend(dateString) {
|
||||
const [year, month, day] = dateString.split("-").map(Number);
|
||||
const date = new Date(Date.UTC(year, month - 1, day));
|
||||
|
||||
const dayOfWeek = date.getUTCDay();
|
||||
|
||||
if (dayOfWeek === 6 || dayOfWeek === 0) {
|
||||
return "It's the weekend!";
|
||||
}
|
||||
|
||||
const daysUntilSaturday = (6 - dayOfWeek);
|
||||
return `${daysUntilSaturday} day${daysUntilSaturday === 1 ? "" : "s"} until the weekend.`;
|
||||
}
|
||||
```
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
---
|
||||
id: 68f6587287ad1f4ad39b0c83
|
||||
title: "Challenge 97: GCD"
|
||||
challengeType: 28
|
||||
dashedName: challenge-97
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given two positive integers, return their greatest common divisor (GCD).
|
||||
|
||||
- The GCD of two integers is the largest number that divides evenly into both numbers without leaving a remainder.
|
||||
|
||||
For example, the divisors of `4` are `1`, `2`, and `4`. The divisors of `6` are `1`, `2`, `3`, and `6`. So given `4` and `6`, return `2`, the largest number that appears in both sets of divisors.
|
||||
|
||||
# --hints--
|
||||
|
||||
`gcd(4, 6)` should return `2`.
|
||||
|
||||
```js
|
||||
assert.equal(gcd(4, 6), 2);
|
||||
```
|
||||
|
||||
`gcd(20, 15)` should return `5`.
|
||||
|
||||
```js
|
||||
assert.equal(gcd(20, 15), 5);
|
||||
```
|
||||
|
||||
`gcd(13, 17)` should return `1`.
|
||||
|
||||
```js
|
||||
assert.equal(gcd(13, 17), 1);
|
||||
```
|
||||
|
||||
`gcd(654, 456)` should return `6`.
|
||||
|
||||
```js
|
||||
assert.equal(gcd(654, 456), 6);
|
||||
```
|
||||
|
||||
`gcd(3456, 4320)` should return `864`.
|
||||
|
||||
```js
|
||||
assert.equal(gcd(3456, 4320), 864);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function gcd(x, y) {
|
||||
|
||||
return x;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function gcd(x, y) {
|
||||
while (y !== 0) {
|
||||
const temp = y;
|
||||
y = x % y;
|
||||
x = temp;
|
||||
}
|
||||
return x;
|
||||
}
|
||||
```
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
---
|
||||
id: 68f6587287ad1f4ad39b0c84
|
||||
title: "Challenge 98: Rectangle Count"
|
||||
challengeType: 28
|
||||
dashedName: challenge-98
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given two positive integers representing the width and height of a rectangle, determine how many rectangles can fit in the given one.
|
||||
|
||||
- Only count rectangles with integer width and height.
|
||||
|
||||
For example, given `1` and `3`, return `6`. Three 1x1 rectangles, two 1x2 rectangles, and one 1x3 rectangle.
|
||||
|
||||
# --hints--
|
||||
|
||||
`countRectangles(1, 3)` should return `6`.
|
||||
|
||||
```js
|
||||
assert.equal(countRectangles(1, 3), 6);
|
||||
```
|
||||
|
||||
`countRectangles(3, 2)` should return `18`.
|
||||
|
||||
```js
|
||||
assert.equal(countRectangles(3, 2), 18);
|
||||
```
|
||||
|
||||
`countRectangles(1, 2)` should return `3`.
|
||||
|
||||
```js
|
||||
assert.equal(countRectangles(1, 2), 3);
|
||||
```
|
||||
|
||||
`countRectangles(5, 4)` should return `150`.
|
||||
|
||||
```js
|
||||
assert.equal(countRectangles(5, 4), 150);
|
||||
```
|
||||
|
||||
`countRectangles(11, 19)` should return `12540`.
|
||||
|
||||
```js
|
||||
assert.equal(countRectangles(11, 19), 12540);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function countRectangles(width, height) {
|
||||
|
||||
return width;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function countRectangles(width, height) {
|
||||
let count = 0;
|
||||
|
||||
for (let w = 1; w <= width; w++) {
|
||||
for (let h = 1; h <= height; h++) {
|
||||
count += (width - w + 1) * (height - h + 1);
|
||||
}
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
```
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
---
|
||||
id: 68f6587287ad1f4ad39b0c85
|
||||
title: "Challenge 99: Fingerprint Test"
|
||||
challengeType: 28
|
||||
dashedName: challenge-99
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given two strings representing fingerprints, determine if they are a match using the following rules:
|
||||
|
||||
- Each fingerprint will consist only of lowercase letters (`a-z`).
|
||||
- Two fingerprints are considered a match if:
|
||||
- They are the same length.
|
||||
- The number of differing characters does not exceed 10% of the fingerprint length.
|
||||
|
||||
# --hints--
|
||||
|
||||
`isMatch("helloworld", "helloworld")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isMatch("helloworld", "helloworld"));
|
||||
```
|
||||
|
||||
`isMatch("helloworld", "helloworlds")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isMatch("helloworld", "helloworlds"));
|
||||
```
|
||||
|
||||
`isMatch("helloworld", "jelloworld")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isMatch("helloworld", "jelloworld"));
|
||||
```
|
||||
|
||||
`isMatch("thequickbrownfoxjumpsoverthelazydog", "thequickbrownfoxjumpsoverthelazydog")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isMatch("thequickbrownfoxjumpsoverthelazydog", "thequickbrownfoxjumpsoverthelazydog"));
|
||||
```
|
||||
|
||||
`isMatch("theslickbrownfoxjumpsoverthelazydog", "thequickbrownfoxjumpsoverthehazydog")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isMatch("theslickbrownfoxjumpsoverthelazydog", "thequickbrownfoxjumpsoverthehazydog"));
|
||||
```
|
||||
|
||||
`isMatch("thequickbrownfoxjumpsoverthelazydog", "thequickbrownfoxjumpsoverthehazycat")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isMatch("thequickbrownfoxjumpsoverthelazydog", "thequickbrownfoxjumpsoverthehazycat"));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function isMatch(fingerprintA, fingerprintB) {
|
||||
|
||||
return fingerprintA;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function isMatch(fingerprintA, fingerprintB) {
|
||||
if (fingerprintA.length !== fingerprintB.length) return false;
|
||||
|
||||
const length = fingerprintA.length;
|
||||
let mismatches = 0;
|
||||
|
||||
for (let i = 0; i < length; i++) {
|
||||
if (fingerprintA[i] !== fingerprintB[i]) {
|
||||
mismatches++;
|
||||
if (mismatches > length * 0.1) return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
---
|
||||
id: 68ffb91507a5b645769328c3
|
||||
title: "Challenge 100: 100 Characters"
|
||||
challengeType: 28
|
||||
dashedName: challenge-100
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Welcome to the 100th Daily Coding Challenge!
|
||||
|
||||
Given a string, repeat its characters until the result is exactly 100 characters long. If your repetitions go over 100 characters, trim the extra so it's exactly 100.
|
||||
|
||||
# --hints--
|
||||
|
||||
`oneHundred("One hundred ")` should return `"One hundred One hundred One hundred One hundred One hundred One hundred One hundred One hundred One "`.
|
||||
|
||||
```js
|
||||
assert.equal(oneHundred("One hundred "), "One hundred One hundred One hundred One hundred One hundred One hundred One hundred One hundred One ");
|
||||
```
|
||||
|
||||
`oneHundred("freeCodeCamp ")` should return `"freeCodeCamp freeCodeCamp freeCodeCamp freeCodeCamp freeCodeCamp freeCodeCamp freeCodeCamp freeCodeC"`.
|
||||
|
||||
```js
|
||||
assert.equal(oneHundred("freeCodeCamp "), "freeCodeCamp freeCodeCamp freeCodeCamp freeCodeCamp freeCodeCamp freeCodeCamp freeCodeCamp freeCodeC");
|
||||
```
|
||||
|
||||
`oneHundred("daily challenges ")` should return `"daily challenges daily challenges daily challenges daily challenges daily challenges daily challenge"`.
|
||||
|
||||
```js
|
||||
assert.equal(oneHundred("daily challenges "), "daily challenges daily challenges daily challenges daily challenges daily challenges daily challenge");
|
||||
```
|
||||
|
||||
`oneHundred("!")` should return `"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"`.
|
||||
|
||||
```js
|
||||
assert.equal(oneHundred("!"), "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function oneHundred(chars) {
|
||||
|
||||
return chars;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function oneHundred(chars) {
|
||||
let result = "";
|
||||
let i = 0;
|
||||
|
||||
while (result.length < 100) {
|
||||
result += chars[i % chars.length];
|
||||
i++;
|
||||
}
|
||||
|
||||
return result.slice(0, 100);
|
||||
}
|
||||
```
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user