feat(curriculum): daily challenges 144-160 (#64530)

This commit is contained in:
Tom
2025-12-18 11:55:50 -06:00
committed by GitHub
parent de75200db7
commit c71e83831f
37 changed files with 3062 additions and 1 deletions

View File

@@ -0,0 +1,84 @@
---
id: 69306364df283fcaff2e1ad5
title: "Challenge 144: Resolution Streak"
challengeType: 28
dashedName: challenge-144
---
# --description--
Given an array of arrays, where each sub-array represents a day of your resolution activities and contains three integers: the number of steps walked that day, the minutes of screen time that day, and the number of pages read that day; determine if you are keeping your resolutions.
- The first sub-array is day 1, and second day 2, and so on.
A day is considered successful if all three of the following goals are met:
- You walked at least 10,000 steps.
- You had no more than 120 minutes of screen time.
- You read at least five pages.
If all of the given days are successful, return `"Resolution on track: N day streak."` Where `N` is the number of successful days.
If one or more days is not a success, return `"Resolution failed on day X: N day streak."`. Where `X` is the day number of the first unsuccessful day, and `N` is the number of successful days before the first unsuccessful day.
# --hints--
`resolutionStreak([[10500, 75, 15], [11000, 90, 10], [10650, 100, 9]])` should return `"Resolution on track: 3 day streak."`
```js
assert.equal(resolutionStreak([[10500, 75, 15], [11000, 90, 10], [10650, 100, 9]]), "Resolution on track: 3 day streak.");
```
`resolutionStreak([[10000, 120, 5], [10950, 121, 11]])` should return `"Resolution failed on day 2: 1 day streak."`
```js
assert.equal(resolutionStreak([[10000, 120, 5], [10950, 121, 11]]), "Resolution failed on day 2: 1 day streak.");
```
`resolutionStreak([[15000, 110, 8], [12300, 60, 13], [10100, 120, 4], [9000, 125, 4]])` should return `"Resolution failed on day 3: 2 day streak."`
```js
assert.equal(resolutionStreak([[15000, 110, 8], [12300, 60, 13], [10100, 120, 4], [9000, 125, 4]]), "Resolution failed on day 3: 2 day streak.");
```
`resolutionStreak([[11600, 76, 13], [12556, 64, 26], [10404, 32, 59], [9999, 44, 124], [7508, 23, 167], [10900, 80, 0]])` should return `"Resolution failed on day 4: 3 day streak."`
```js
assert.equal(resolutionStreak([[11600, 76, 13], [12556, 64, 26], [10404, 32, 59], [9999, 44, 124], [7508, 23, 167], [10900, 80, 0]]), "Resolution failed on day 4: 3 day streak.");
```
`resolutionStreak([[10500, 75, 15], [11000, 90, 10], [10650, 100, 9], [10200, 60, 10], [10678, 87, 9], [12431, 67, 13], [10444, 107, 19], [10111, 95, 5], [10000, 120, 7], [11980, 101, 8]])` should return `"Resolution on track: 10 day streak."`
```js
assert.equal(resolutionStreak([[10500, 75, 15], [11000, 90, 10], [10650, 100, 9], [10200, 60, 10], [10678, 87, 9], [12431, 67, 13], [10444, 107, 19], [10111, 95, 5], [10000, 120, 7], [11980, 101, 8]]), "Resolution on track: 10 day streak.");
```
# --seed--
## --seed-contents--
```js
function resolutionStreak(days) {
return days;
}
```
# --solutions--
```js
function resolutionStreak(days) {
let streak = 0;
for (let i = 0; i < days.length; i++) {
const [steps, screen, pages] = days[i];
if (steps >= 10000 && screen <= 120 && pages >= 5) {
streak++;
} else {
return `Resolution failed on day ${i + 1}: ${streak} day streak.`;
}
}
return `Resolution on track: ${streak} day streak.`;
}
```

View File

@@ -0,0 +1,75 @@
---
id: 69306364df283fcaff2e1ad6
title: "Challenge 145: Nth Fibonacci Number"
challengeType: 28
dashedName: challenge-145
---
# --description--
Given an integer `n`, return the `n`th number in the fibonacci sequence.
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. The first 10 numbers in the sequence are `0`, `1`, `1`, `2`, `3`, `5`, `8`, `13`, `21`, `34`.
# --hints--
`nthFibonacci(4)` should return `2`.
```js
assert.equal(nthFibonacci(4), 2);
```
`nthFibonacci(10)` should return `34`.
```js
assert.equal(nthFibonacci(10), 34);
```
`nthFibonacci(15)` should return `377`.
```js
assert.equal(nthFibonacci(15), 377);
```
`nthFibonacci(40)` should return `63245986`.
```js
assert.equal(nthFibonacci(40), 63245986);
```
`nthFibonacci(75)` should return `1304969544928657`.
```js
assert.equal(nthFibonacci(75), 1304969544928657);
```
# --seed--
## --seed-contents--
```js
function nthFibonacci(n) {
return n;
}
```
# --solutions--
```js
function nthFibonacci(n) {
if (n === 1) return 0;
if (n === 2) return 1;
let a = 0;
let b = 1;
for (let i = 3; i <= n; i++) {
const next = a + b;
a = b;
b = next;
}
return b;
}
```

View File

@@ -0,0 +1,107 @@
---
id: 69306364df283fcaff2e1ad7
title: "Challenge 146: Left-Handed Seat at the Table"
challengeType: 28
dashedName: challenge-146
---
# --description--
Given a 4x2 matrix (array of arrays) representing the seating arrangement for a meal, determine how many seats a left-handed person can sit at.
- A left-handed person cannot sit where a right-handed person would be in the seat to the immediate left of them.
In the given matrix:
- An `"R"` is a seat occupied by a right-handed person.
- An `"L"` is a seat occupied by a left-handed person.
- An `"U"` is an unoccupied seat.
- Only unoccupied seats are available to sit at.
- The seats in the top row are facing "down", and the seats in the bottom row are facing "up" (like a table), so left and right are relative to the seat's orientation.
- Corner seats only have one seat next to them.
For example, in the given matrix:
```json
[
["U", "R", "U", "L"],
["U", "R", "R", "R"]
]
```
The top-left seat is cannot be sat in because there's a right-handed person to the left. The other two open seats can be sat in because there isn't a right-handed person to the left.
# --hints--
`findLeftHandedSeats([["U", "R", "U", "L"], ["U", "R", "R", "R"]])` should return `2`.
```js
assert.equal(findLeftHandedSeats([["U", "R", "U", "L"], ["U", "R", "R", "R"]]), 2);
```
`findLeftHandedSeats([["U", "U", "U", "U"], ["U", "U", "U", "U"]])` should return `8`.
```js
assert.equal(findLeftHandedSeats([["U", "U", "U", "U"], ["U", "U", "U", "U"]]), 8);
```
`findLeftHandedSeats([["U", "R", "U", "R"], ["L", "R", "R", "U"]])` should return `0`.
```js
assert.equal(findLeftHandedSeats([["U", "R", "U", "R"], ["L", "R", "R", "U"]]), 0);
```
`findLeftHandedSeats([["L", "U", "R", "R"], ["L", "U", "R", "R"]])` should return `1`.
```js
assert.equal(findLeftHandedSeats([["L", "U", "R", "R"], ["L", "U", "R", "R"]]), 1);
```
`findLeftHandedSeats([["U", "R", "U", "U"], ["U", "U", "L", "U"]])` should return `5`.
```js
assert.equal(findLeftHandedSeats([["U", "R", "U", "U"], ["U", "U", "L", "U"]]), 5);
```
# --seed--
## --seed-contents--
```js
function findLeftHandedSeats(table) {
return table;
}
```
# --solutions--
```js
function findLeftHandedSeats(table) {
let availableSeats = 0;
const [topRow, bottomRow] = table;
for (let i=0; i<topRow.length; i++) {
if (topRow[i] === 'U') {
if (i === 3) {
availableSeats++;
} else if (topRow[i+1] !== 'R') {
availableSeats++;
}
}
}
for (let i=0; i<bottomRow.length; i++) {
if (bottomRow[i] === 'U') {
if (i === 0) {
availableSeats++;
} else if (bottomRow[i-1] !== 'R') {
availableSeats++;
}
}
}
return availableSeats;
}
```

View File

@@ -0,0 +1,79 @@
---
id: 69306364df283fcaff2e1ad8
title: "Challenge 147: Leap Year Calculator"
challengeType: 28
dashedName: challenge-147
---
# --description--
Given an integer year, determine whether it is a leap year.
A year is a leap year if it satisfies the following rules:
- The year is evenly divisible by 4, and
- The year is not evenly divisible by 100, unless
- The year is evenly divisible by 400.
# --hints--
`isLeapYear(2024)` should return `true`.
```js
assert.isTrue(isLeapYear(2024));
```
`isLeapYear(2023)` should return `false`.
```js
assert.isFalse(isLeapYear(2023));
```
`isLeapYear(2100)` should return `false`.
```js
assert.isFalse(isLeapYear(2100));
```
`isLeapYear(2000)` should return `true`.
```js
assert.isTrue(isLeapYear(2000));
```
`isLeapYear(1999)` should return `false`.
```js
assert.isFalse(isLeapYear(1999));
```
`isLeapYear(2040)` should return `true`.
```js
assert.isTrue(isLeapYear(2040));
```
`isLeapYear(2026)` should return `false`.
```js
assert.isFalse(isLeapYear(2026));
```
# --seed--
## --seed-contents--
```js
function isLeapYear(year) {
return year;
}
```
# --solutions--
```js
function isLeapYear(year) {
return ((year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0))
}
```

View File

@@ -0,0 +1,77 @@
---
id: 69306364df283fcaff2e1ad9
title: "Challenge 148: Tire Pressure"
challengeType: 28
dashedName: challenge-148
---
# --description--
Given an array with four numbers representing the tire pressures in psi of the four tires in your vehicle, and another array of two numbers representing the minimum and maximum pressure for your tires in bar, return an array of four strings describing each tire's status.
- 1 bar equal 14.5038 psi.
Return an array with the following values for each tire:
- `"Low"` if the tire pressure is below the minimum allowed.
- `"Good"` if it's between the minimum and maximum allowed.
- `"High"` if it's above the maximum allowed.
# --hints--
`tireStatus([32, 28, 35, 29], [2, 3])` should return `["Good", "Low", "Good", "Low"]`.
```js
assert.deepEqual(tireStatus([32, 28, 35, 29], [2, 3]), ["Good", "Low", "Good", "Low"]);
```
`tireStatus([32, 28, 35, 30], [2, 2.3])` should return `["Good", "Low", "High", "Good"]`.
```js
assert.deepEqual(tireStatus([32, 28, 35, 30], [2, 2.3]), ["Good", "Low", "High", "Good"]);
```
`tireStatus([29, 26, 31, 28], [2.1, 2.5])` should return `["Low", "Low", "Good", "Low"]`.
```js
assert.deepEqual(tireStatus([29, 26, 31, 28], [2.1, 2.5]), ["Low", "Low", "Good", "Low"]);
```
`tireStatus([31, 31, 30, 29], [1.5, 2])` should return `["High", "High", "High", "Good"]`.
```js
assert.deepEqual(tireStatus([31, 31, 30, 29], [1.5, 2]), ["High", "High", "High", "Good"]);
```
`tireStatus([30, 28, 30, 29], [1.9, 2.1])` should return `["Good", "Good", "Good", "Good"]`.
```js
assert.deepEqual(tireStatus([30, 28, 30, 29], [1.9, 2.1]), ["Good", "Good", "Good", "Good"]);
```
# --seed--
## --seed-contents--
```js
function tireStatus(pressuresPSI, rangeBar) {
return pressuresPSI;
}
```
# --solutions--
```js
function tireStatus(pressuresPSI, rangeBar) {
const psiToBar = 1 / 14.5038;
const [minBar, maxBar] = rangeBar;
return pressuresPSI.map(psi => {
const bar = psi * psiToBar;
if (bar < minBar) return "Low";
if (bar > maxBar) return "High";
return "Good";
});
}
```

View File

@@ -0,0 +1,77 @@
---
id: 69306364df283fcaff2e1ada
title: "Challenge 149: vOwElcAsE"
challengeType: 28
dashedName: challenge-149
---
# --description--
Given a string, return a new string where all vowels are converted to uppercase and all other alphabetical characters are converted to lowercase.
- Vowels are `"a"`, `"e"`, `"i"`, `"o"`, and `"u"` in any case.
- Non-alphabetical characters should remain unchanged.
# --hints--
`vowelCase("vowelcase")` should return `"vOwElcAsE"`.
```js
assert.equal(vowelCase("vowelcase"), "vOwElcAsE");
```
`vowelCase("coding is fun")` should return `"cOdIng Is fUn"`.
```js
assert.equal(vowelCase("coding is fun"), "cOdIng Is fUn");
```
`vowelCase("HELLO, world!")` should return `"hEllO, wOrld!"`.
```js
assert.equal(vowelCase("HELLO, world!"), "hEllO, wOrld!");
```
`vowelCase("git cherry-pick")` should return `"gIt chErry-pIck"`.
```js
assert.equal(vowelCase("git cherry-pick"), "gIt chErry-pIck");
```
`vowelCase("HEAD~1")` should return `"hEAd~1"`.
```js
assert.equal(vowelCase("HEAD~1"), "hEAd~1");
```
# --seed--
## --seed-contents--
```js
function vowelCase(str) {
return str;
}
```
# --solutions--
```js
function vowelCase(str) {
const vowels = "aeiouAEIOU";
let result = "";
for (let char of str) {
if (vowels.includes(char)) {
result += char.toUpperCase();
} else if (/[a-zA-Z]/.test(char)) {
result += char.toLowerCase();
} else {
result += char;
}
}
return result;
}
```

View File

@@ -0,0 +1,76 @@
---
id: 69373793f5a867f769cde135
title: "Challenge 150: Markdown Unordered List Parser"
challengeType: 28
dashedName: challenge-150
---
# --description--
Given the string of a valid unordered list in Markdown, return the equivalent HTML string.
An unordered list consists of one or more list items. A valid list item appears on its own line and:
- Starts with a dash (`"-"`), followed by
- At least one space, and then
- The list item text.
The list is given as a single string with new lines separated by the newline character (`"\n"`). Do not include the newline characters in the item text.
Wrap each list item in HTML `li` tags, and the whole list of items in `ul` tags.
For example, given `"- Item A\n- Item B"`, return `"<ul><li>Item A</li><li>Item B</li></ul>"`.
Note: The console may not display HTML tags in strings when logging messages. Check the browser console to see logs with tags included.
# --hints--
`parseUnorderedList("- Item A\n- Item B")` should return `"<ul><li>Item A</li><li>Item B</li></ul>"`.
```js
assert.equal(parseUnorderedList("- Item A\n- Item B"), "<ul><li>Item A</li><li>Item B</li></ul>");
```
`parseUnorderedList("- JavaScript\n- Python")` should return `"<ul><li>JavaScript</li><li>Python</li></ul>"`.
```js
assert.equal(parseUnorderedList("- JavaScript\n- Python"), "<ul><li>JavaScript</li><li>Python</li></ul>");
```
`parseUnorderedList("- 2 C Flour\n- 1/2 C Sugar\n- 1 Tsp Vanilla")` should return `"<ul><li>2 C Flour</li><li>1/2 C Sugar</li><li>1 Tsp Vanilla</li></ul>"`.
```js
assert.equal(parseUnorderedList("- 2 C Flour\n- 1/2 C Sugar\n- 1 Tsp Vanilla"), "<ul><li>2 C Flour</li><li>1/2 C Sugar</li><li>1 Tsp Vanilla</li></ul>");
```
`parseUnorderedList("- A-1\n- A-2\n- B-1")` should return `"<ul><li>A-1</li><li>A-2</li><li>B-1</li></ul>"`.
```js
assert.equal(parseUnorderedList("- A-1\n- A-2\n- B-1"), "<ul><li>A-1</li><li>A-2</li><li>B-1</li></ul>");
```
# --seed--
## --seed-contents--
```js
function parseUnorderedList(markdown) {
return markdown;
}
```
# --solutions--
```js
function parseUnorderedList(markdown) {
const lines = markdown.split("\n");
const listItems = [];
for (let line of lines) {
listItems.push(`<li>${line.slice(1).trim()}</li>`);
}
return `<ul>${listItems.join("")}</ul>`;
}
```

View File

@@ -0,0 +1,83 @@
---
id: 69373793f5a867f769cde136
title: "Challenge 151: Sorted Array?"
challengeType: 28
dashedName: challenge-151
---
# --description--
Given an array of numbers, determine if the numbers are sorted in ascending order, descending order, or neither.
If the given array is:
- In ascending order (lowest to highest), return `"Ascending"`.
- In descending order (highest to lowest), return `"Descending"`.
- Not sorted in ascending or descending order, return `"Not sorted"`.
# --hints--
`isSorted([1, 2, 3, 4, 5])` should return `"Ascending"`.
```js
assert.equal(isSorted([1, 2, 3, 4, 5]), "Ascending");
```
`isSorted([10, 8, 6, 4, 2])` should return `"Descending"`.
```js
assert.equal(isSorted([10, 8, 6, 4, 2]), "Descending");
```
`isSorted([1, 3, 2, 4, 5])` should return `"Not sorted"`.
```js
assert.equal(isSorted([1, 3, 2, 4, 5]), "Not sorted");
```
`isSorted([3.14, 2.71, 1.61, 0.57])` should return `"Descending"`.
```js
assert.equal(isSorted([3.14, 2.71, 1.61, 0.57]), "Descending");
```
`isSorted([12.3, 23.4, 34.5, 45.6, 56.7, 67.8, 78.9])` should return `"Ascending"`.
```js
assert.equal(isSorted([12.3, 23.4, 34.5, 45.6, 56.7, 67.8, 78.9]), "Ascending");
```
`isSorted([0.4, 0.5, 0.3])` should return `"Not sorted"`.
```js
assert.equal(isSorted([0.4, 0.5, 0.3]), "Not sorted");
```
# --seed--
## --seed-contents--
```js
function isSorted(arr) {
return arr;
}
```
# --solutions--
```js
function isSorted(arr) {
let ascending = true;
let descending = true;
for (let i = 1; i < arr.length; i++) {
if (arr[i] < arr[i - 1]) ascending = false;
if (arr[i] > arr[i - 1]) descending = false;
}
if (ascending) return "Ascending";
if (descending) return "Descending";
return "Not sorted";
}
```

View File

@@ -0,0 +1,83 @@
---
id: 69373793f5a867f769cde137
title: "Challenge 152: Circular Prime"
challengeType: 28
dashedName: challenge-152
---
# --description--
Given an integer, determine if it is a circular prime.
A circular prime is an integer where all rotations of its digits are themselves prime.
For example, `197` is a circular prime because all rotations of its digits: `197`, `971`, and `719`, are prime numbers.
# --hints--
`isCircularPrime(197)` should return `true`.
```js
assert.isTrue(isCircularPrime(197));
```
`isCircularPrime(23)` should return `false`.
```js
assert.isFalse(isCircularPrime(23));
```
`isCircularPrime(13)` should return `true`.
```js
assert.isTrue(isCircularPrime(13));
```
`isCircularPrime(89)` should return `false`.
```js
assert.isFalse(isCircularPrime(89));
```
`isCircularPrime(1193)` should return `true`.
```js
assert.isTrue(isCircularPrime(1193));
```
# --seed--
## --seed-contents--
```js
function isCircularPrime(n) {
return n;
}
```
# --solutions--
```js
function isPrime(n) {
if (n < 2) return false;
for (let i = 2, sqrt = Math.floor(Math.sqrt(n)); i <= sqrt; i++) {
if (n % i === 0) return false;
}
return true;
}
function rotations(num) {
const str = num.toString();
const result = [];
for (let i = 0; i < str.length; i++) {
result.push(str.slice(i) + str.slice(0, i));
}
return result.map(Number);
}
function isCircularPrime(num) {
const rots = rotations(num);
return rots.every(isPrime);
}
```

View File

@@ -0,0 +1,95 @@
---
id: 69373793f5a867f769cde138
title: "Challenge 153: Tic-Tac-Toe"
challengeType: 28
dashedName: challenge-153
---
# --description--
Given a 3×3 matrix (an array of arrays) representing a completed Tic-Tac-Toe game, determine the winner.
- Each element in the given matrix is either an `"X"` or `"O"`.
A player wins if they have three of their characters in a row - horizontally, vertically, or diagonally.
Return:
- `"X wins"` if player X has three in a row.
- `"O wins"` if player O has three in a row.
- `"Draw"` if no player has three in a row.
# --hints--
`ticTacToe([["X", "X", "X"], ["O", "O", "X"], ["O", "X", "O"]])` should return `"X wins"`.
```js
assert.equal(ticTacToe([["X", "X", "X"], ["O", "O", "X"], ["O", "X", "O"]]), "X wins");
```
`ticTacToe([["X", "O", "X"], ["X", "O", "X"], ["O", "O", "X"]])` should return `"O wins"`.
```js
assert.equal(ticTacToe([["X", "O", "X"], ["X", "O", "X"], ["O", "O", "X"]]), "O wins");
```
`ticTacToe([["X", "O", "X"], ["O", "X", "O"], ["O", "X", "O"]])` should return `"Draw"`.
```js
assert.equal(ticTacToe([["X", "O", "X"], ["O", "X", "O"], ["O", "X", "O"]]), "Draw");
```
`ticTacToe([["X", "X", "O"], ["X", "O", "X"], ["O", "X", "X"]])` should return `"O wins"`.
```js
assert.equal(ticTacToe([["X", "X", "O"], ["X", "O", "X"], ["O", "X", "X"]]), "O wins");
```
`ticTacToe([["X", "O", "O"], ["O", "X", "O"], ["O", "X", "X"]])` should return `"X wins"`.
```js
assert.equal(ticTacToe([["X", "O", "O"], ["O", "X", "O"], ["O", "X", "X"]]), "X wins");
```
`ticTacToe([["O", "X", "X"], ["X", "O", "O"], ["X", "O", "X"]])` should return `"Draw"`.
```js
assert.equal(ticTacToe([["O", "X", "X"], ["X", "O", "O"], ["X", "O", "X"]]), "Draw");
```
# --seed--
## --seed-contents--
```js
function ticTacToe(board) {
return board;
}
```
# --solutions--
```js
function ticTacToe(board) {
const lines = [];
for (let row of board) {
lines.push(row);
}
for (let c = 0; c < 3; c++) {
lines.push([board[0][c], board[1][c], board[2][c]]);
}
lines.push([board[0][0], board[1][1], board[2][2]]);
lines.push([board[0][2], board[1][1], board[2][0]]);
for (let line of lines) {
if (line.every(cell => cell === "X")) return "X wins";
if (line.every(cell => cell === "O")) return "O wins";
}
return "Draw";
}
```

View File

@@ -0,0 +1,84 @@
---
id: 69373793f5a867f769cde139
title: "Challenge 154: Par for the Hole"
challengeType: 28
dashedName: challenge-154
---
# --description--
Given two integers, the par for a golf hole and the number of strokes a golfer took on that hole, return the golfer's score using golf terms.
Return:
- `"Hole in one!"` if it took one stroke.
- `"Eagle"` if it took two strokes less than par.
- `"Birdie"` if it took one stroke less than par.
- `"Par"` if it took the same number of strokes as par.
- `"Bogey"` if it took one stroke more than par.
- `"Double bogey"` if took two strokes more than par.
# --hints--
`golfScore(3, 3)` should return `"Par"`.
```js
assert.equal(golfScore(3, 3), "Par");
```
`golfScore(4, 3)` should return `"Birdie"`.
```js
assert.equal(golfScore(4, 3), "Birdie");
```
`golfScore(3, 1)` should return `"Hole in one!"`.
```js
assert.equal(golfScore(3, 1), "Hole in one!");
```
`golfScore(5, 7)` should return `"Double bogey"`.
```js
assert.equal(golfScore(5, 7), "Double bogey");
```
`golfScore(4, 5)` should return `"Bogey"`.
```js
assert.equal(golfScore(4, 5), "Bogey");
```
`golfScore(5, 3)` should return `"Eagle"`.
```js
assert.equal(golfScore(5, 3), "Eagle");
```
# --seed--
## --seed-contents--
```js
function golfScore(par, strokes) {
return par;
}
```
# --solutions--
```js
function golfScore(par, strokes) {
if (strokes === 1) return "Hole in one!";
const diff = strokes - par;
if (diff === -2) return "Eagle";
if (diff === -1) return "Birdie";
if (diff === 0) return "Par";
if (diff === 1) return "Bogey";
if (diff === 2) return "Double bogey";
}
```

View File

@@ -0,0 +1,86 @@
---
id: 69373793f5a867f769cde13a
title: "Challenge 155: Plant the Crop"
challengeType: 28
dashedName: challenge-155
---
# --description--
Given an integer representing the size of your farm field, and `"acres"` or `"hectares"` representing the unit for the size of your farm field, and a type of crop, determine how many plants of that type you can fit in your field.
- 1 acre equals 4046.86 square meters.
- 1 hectare equals 10,000 square meters.
Here's a list of crops that will be given as input and how much space a single plant takes:
|Crop|Space per plant|
|-|-|
|`"corn"`|1 square meter|
|`"wheat"`|0.1 square meters|
|`"soybeans"`|0.5 square meters|
|`"tomatoes"`|0.25 square meters|
|`"lettuce"`|0.2 square meters|
Return the number of plants that fit in the field, rounded down to the nearest whole plant.
# --hints--
`getNumberOfPlants(1, "acres", "corn")` should return `4046`.
```js
assert.equal(getNumberOfPlants(1, "acres", "corn"), 4046);
```
`getNumberOfPlants(2, "hectares", "lettuce")` should return `100000`.
```js
assert.equal(getNumberOfPlants(2, "hectares", "lettuce"), 100000);
```
`getNumberOfPlants(20, "acres", "soybeans")` should return `161874`.
```js
assert.equal(getNumberOfPlants(20, "acres", "soybeans"), 161874);
```
`getNumberOfPlants(3.75, "hectares", "tomatoes")` should return `150000`.
```js
assert.equal(getNumberOfPlants(3.75, "hectares", "tomatoes"), 150000);
```
`getNumberOfPlants(16.75, "acres", "tomatoes")` should return `271139`.
```js
assert.equal(getNumberOfPlants(16.75, "acres", "tomatoes"), 271139);
```
# --seed--
## --seed-contents--
```js
function getNumberOfPlants(fieldSize, unit, crop) {
return fieldSize;
}
```
# --solutions--
```js
function getNumberOfPlants(fieldSize, unit, crop) {
const cropSpace = {
corn: 1,
wheat: 0.1,
soybeans: 0.5,
tomatoes: 0.25,
lettuce: 0.2
};
let fieldInSqM = unit === "acres" ? fieldSize * 4046.86 : fieldSize * 10000;
return Math.floor(fieldInSqM / cropSpace[crop.toLowerCase()]);
}
```

View File

@@ -0,0 +1,61 @@
---
id: 6939b873185d8e00d453563b
title: "Challenge 156: Odd or Even?"
challengeType: 28
dashedName: challenge-156
---
# --description--
Given a positive integer, return `"Odd"` if it's an odd number, and `"Even"` is it's even.
# --hints--
`oddOrEven(1)` should return `"Odd"`.
```js
assert.equal(oddOrEven(1), "Odd");
```
`oddOrEven(2)` should return `"Even"`.
```js
assert.equal(oddOrEven(2), "Even");
```
`oddOrEven(13)` should return `"Odd"`.
```js
assert.equal(oddOrEven(13), "Odd");
```
`oddOrEven(196)` should return `"Even"`.
```js
assert.equal(oddOrEven(196), "Even");
```
`oddOrEven(123456789)` should return `"Odd"`.
```js
assert.equal(oddOrEven(123456789), "Odd");
```
# --seed--
## --seed-contents--
```js
function oddOrEven(n) {
return n;
}
```
# --solutions--
```js
function oddOrEven(n) {
return n % 2 === 0 ? "Even" : "Odd";
}
```

View File

@@ -0,0 +1,58 @@
---
id: 6939b873185d8e00d453563c
title: "Challenge 157: Markdown Link Parser"
challengeType: 28
dashedName: challenge-157
---
# --description--
Given the string of a link in Markdown, return the equivalent HTML string.
A Markdown image has the following format: `"[link_text](link_url)"`. Return the string of the HTML `a` tag with the `href` set to the `link_url` and the `link_text` as the tag content.
For example, given `"[freeCodeCamp](https://freecodecamp.org/)"` return `'<a href="https://freecodecamp.org/">freeCodeCamp</a>'`;
Note: The console may not display HTML tags in strings when logging messages — check the browser console to see logs with tags included.
# --hints--
`parseLink("[freeCodeCamp](https://freecodecamp.org/)")` should return `'<a href="https://freecodecamp.org/">freeCodeCamp</a>'`.
```js
assert.equal(parseLink("[freeCodeCamp](https://freecodecamp.org/)"), '<a href="https://freecodecamp.org/">freeCodeCamp</a>');
```
`parseLink("[Donate to our charity.](https://www.freecodecamp.org/donate/)")` should return `'<a href="https://www.freecodecamp.org/donate/">Donate to our charity.</a>'`.
```js
assert.equal(parseLink("[Donate to our charity.](https://www.freecodecamp.org/donate/)"), '<a href="https://www.freecodecamp.org/donate/">Donate to our charity.</a>');
```
`parseLink("[Contribute to our repository at https://github.com/freeCodeCamp/freeCodeCamp.](https://github.com/freeCodeCamp/freeCodeCamp/)")` should return `'<a href="https://github.com/freeCodeCamp/freeCodeCamp/">Contribute to our repository at https://github.com/freeCodeCamp/freeCodeCamp.</a>'`.
```js
assert.equal(parseLink("[Contribute to our repository at https://github.com/freeCodeCamp/freeCodeCamp.](https://github.com/freeCodeCamp/freeCodeCamp/)"), '<a href="https://github.com/freeCodeCamp/freeCodeCamp/">Contribute to our repository at https://github.com/freeCodeCamp/freeCodeCamp.</a>');
```
# --seed--
## --seed-contents--
```js
function parseLink(markdown) {
return markdown;
}
```
# --solutions--
```js
function parseLink(markdown) {
const match = markdown.match(/\[(.*?)\]\((.*?)\)/);
const [, text, url] = match;
return `<a href="${url}">${text}</a>`;
}
```

View File

@@ -0,0 +1,58 @@
---
id: 6939b873185d8e00d453563d
title: "Challenge 158: Array Swap"
challengeType: 28
dashedName: challenge-158
---
# --description--
Given an array with two values, return an array with the values swapped.
For example, given `["A", "B"]` return `["B", "A"]`.
# --hints--
`arraySwap(["A", "B"])` should return `["B", "A"]`.
```js
assert.deepEqual(arraySwap(["A", "B"]), ["B", "A"]);
```
`arraySwap([25, 20])` should return `[20, 25]`.
```js
assert.deepEqual(arraySwap([25, 20]), [20, 25]);
```
`arraySwap([true, false])` should return `[false, true]`.
```js
assert.deepEqual(arraySwap([true, false]), [false, true]);
```
`arraySwap(["1", 1])` should return `[1, "1"]`.
```js
assert.deepEqual(arraySwap(["1", 1]), [1, "1"]);
```
# --seed--
## --seed-contents--
```js
function arraySwap(arr) {
return arr;
}
```
# --solutions--
```js
function arraySwap(arr) {
return [arr[1], arr[0]];
}
```

View File

@@ -0,0 +1,71 @@
---
id: 6939b873185d8e00d453563e
title: "Challenge 159: Integer Hypotenuse"
challengeType: 28
dashedName: challenge-159
---
# --description--
Given two positive integers representing the lengths for the two legs (the two short sides) of a right triangle, determine whether the hypotenuse is an integer.
The length of the hypotenuse is calculated by adding the squares of the two leg lengths together and then taking the square root of that total (a<sup>2</sup> + b<sup>2</sup> = c<sup>2</sup>).
# --hints--
`isIntegerHypotenuse(3, 4)` should return `true`.
```js
assert.isTrue(isIntegerHypotenuse(3, 4));
```
`isIntegerHypotenuse(2, 3)` should return `false`.
```js
assert.isFalse(isIntegerHypotenuse(2, 3));
```
`isIntegerHypotenuse(5, 12)` should return `true`.
```js
assert.isTrue(isIntegerHypotenuse(5, 12));
```
`isIntegerHypotenuse(10, 10)` should return `false`.
```js
assert.isFalse(isIntegerHypotenuse(10, 10));
```
`isIntegerHypotenuse(780, 1040)` should return `true`.
```js
assert.isTrue(isIntegerHypotenuse(780, 1040));
```
`isIntegerHypotenuse(250, 333)` should return `false`.
```js
assert.isFalse(isIntegerHypotenuse(250, 333));
```
# --seed--
## --seed-contents--
```js
function isIntegerHypotenuse(a, b) {
return a;
}
```
# --solutions--
```js
function isIntegerHypotenuse(a, b) {
const sum = a * a + b * b;
const c = Math.floor(Math.sqrt(sum));
return c * c === sum;
}
```

View File

@@ -0,0 +1,98 @@
---
id: 6939b873185d8e00d453563f
title: "Challenge 160: Knight Moves"
challengeType: 28
dashedName: challenge-160
---
# --description--
Given the position of a knight on a chessboard, return the number of valid squares the knight can move to.
A standard chessboard is 8x8, with columns labeled `A` through `H` (left to right) and rows labeled `1` through `8` (bottom to top). It looks like this:
|**A8**|**B8**|**C8**|**D8**|**E8**|**F8**|**G8**|**H8**|
|-|-|-|-|-|-|-|-|
|**A7**|**B7**|**C7**|**D7**|**E7**|**F7**|**G7**|**H7**|
|**A6**|**B6**|**C6**|**D6**|**E6**|**F6**|**G6**|**H6**|
|**A5**|**B5**|**C5**|**D5**|**E5**|**F5**|**G5**|**H5**|
|**A4**|**B4**|**C4**|**D4**|**E4**|**F4**|**G4**|**H4**|
|**A3**|**B3**|**C3**|**D3**|**E3**|**F3**|**G3**|**H3**|
|**A2**|**B2**|**C2**|**D2**|**E2**|**F2**|**G2**|**H2**|
|**A1**|**B1**|**C1**|**D1**|**E1**|**F1**|**G1**|**H1**|
A knight moves in an "L" shape: two squares in one direction (horizontal or vertical), and one square in the perpendicular direction.
This means a knight can move to up to eight possible positions, but fewer when near the edges of the board. For example, if a knight was at `A1`, it could only move to `B3` or `C2`.
# --hints--
`knightMoves("A1")` should return `2`.
```js
assert.equal(knightMoves("A1"), 2);
```
`knightMoves("D4")` should return `8`.
```js
assert.equal(knightMoves("D4"), 8);
```
`knightMoves("G6")` should return `6`.
```js
assert.equal(knightMoves("G6"), 6);
```
`knightMoves("B8")` should return `3`.
```js
assert.equal(knightMoves("B8"), 3);
```
`knightMoves("H3")` should return `4`.
```js
assert.equal(knightMoves("H3"), 4);
```
# --seed--
## --seed-contents--
```js
function knightMoves(position) {
return position;
}
```
# --solutions--
```js
function knightMoves(position) {
const col = position[0].charCodeAt(0) - 65;
const row = parseInt(position[1]) - 1;
const moves = [
[2, 1], [2, -1],
[-2, 1], [-2, -1],
[1, 2], [1, -2],
[-1, 2], [-1, -2]
];
let valid = 0;
for (const [dx, dy] of moves) {
const newCol = col + dx;
const newRow = row + dy;
if (newCol >= 0 && newCol < 8 && newRow >= 0 && newRow < 8) {
valid++;
}
}
return valid;
}
```

View File

@@ -0,0 +1,95 @@
---
id: 69306364df283fcaff2e1ad5
title: "Challenge 144: Resolution Streak"
challengeType: 29
dashedName: challenge-144
---
# --description--
Given an array of arrays, where each sub-array represents a day of your resolution activities and contains three integers: the number of steps walked that day, the minutes of screen time that day, and the number of pages read that day; determine if you are keeping your resolutions.
- The first sub-array is day 1, and second day 2, and so on.
A day is considered successful if all three of the following goals are met:
- You walked at least 10,000 steps.
- You had no more than 120 minutes of screen time.
- You read at least five pages.
If all of the given days are successful, return `"Resolution on track: N day streak."` Where `N` is the number of successful days.
If one or more days is not a success, return `"Resolution failed on day X: N day streak."`. Where `X` is the day number of the first unsuccessful day, and `N` is the number of successful days before the first unsuccessful day.
# --hints--
`resolution_streak([[10500, 75, 15], [11000, 90, 10], [10650, 100, 9]])` should return `"Resolution on track: 3 day streak."`
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(resolution_streak([[10500, 75, 15], [11000, 90, 10], [10650, 100, 9]]), "Resolution on track: 3 day streak.")`)
}})
```
`resolution_streak([[10000, 120, 5], [10950, 121, 11]])` should return `"Resolution failed on day 2: 1 day streak."`
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(resolution_streak([[10000, 120, 5], [10950, 121, 11]]), "Resolution failed on day 2: 1 day streak.")`)
}})
```
`resolution_streak([[15000, 110, 8], [12300, 60, 13], [10100, 120, 4], [9000, 125, 4]])` should return `"Resolution failed on day 3: 2 day streak."`
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(resolution_streak([[15000, 110, 8], [12300, 60, 13], [10100, 120, 4], [9000, 125, 4]]), "Resolution failed on day 3: 2 day streak.")`)
}})
```
`resolution_streak([[11600, 76, 13], [12556, 64, 26], [10404, 32, 59], [9999, 44, 124], [7508, 23, 167], [10900, 80, 0]])` should return `"Resolution failed on day 4: 3 day streak."`
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(resolution_streak([[11600, 76, 13], [12556, 64, 26], [10404, 32, 59], [9999, 44, 124], [7508, 23, 167], [10900, 80, 0]]), "Resolution failed on day 4: 3 day streak.")`)
}})
```
`resolution_streak([[10500, 75, 15], [11000, 90, 10], [10650, 100, 9], [10200, 60, 10], [10678, 87, 9], [12431, 67, 13], [10444, 107, 19], [10111, 95, 5], [10000, 120, 7], [11980, 101, 8]])` should return `"Resolution on track: 10 day streak."`
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(resolution_streak([[10500, 75, 15], [11000, 90, 10], [10650, 100, 9], [10200, 60, 10], [10678, 87, 9], [12431, 67, 13], [10444, 107, 19], [10111, 95, 5], [10000, 120, 7], [11980, 101, 8]]), "Resolution on track: 10 day streak.")`)
}})
```
# --seed--
## --seed-contents--
```py
def resolution_streak(days):
return days
```
# --solutions--
```py
def resolution_streak(days):
streak = 0
for i, day in enumerate(days):
steps, screen, pages = day
if steps >= 10000 and screen <= 120 and pages >= 5:
streak += 1
else:
return f"Resolution failed on day {i+1}: {streak} day streak."
return f"Resolution on track: {streak} day streak."
```

View File

@@ -0,0 +1,84 @@
---
id: 69306364df283fcaff2e1ad6
title: "Challenge 145: Nth Fibonacci Number"
challengeType: 29
dashedName: challenge-145
---
# --description--
Given an integer `n`, return the `n`th number in the fibonacci sequence.
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. The first 10 numbers in the sequence are `0`, `1`, `1`, `2`, `3`, `5`, `8`, `13`, `21`, `34`.
# --hints--
`nth_fibonacci(4)` should return `2`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(nth_fibonacci(4), 2)`)
}})
```
`nth_fibonacci(10)` should return `34`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(nth_fibonacci(10), 34)`)
}})
```
`nth_fibonacci(15)` should return `377`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(nth_fibonacci(15), 377)`)
}})
```
`nth_fibonacci(40)` should return `63245986`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(nth_fibonacci(40), 63245986)`)
}})
```
`nth_fibonacci(75)` should return `1304969544928657`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(nth_fibonacci(75), 1304969544928657)`)
}})
```
# --seed--
## --seed-contents--
```py
def nth_fibonacci(n):
return n
```
# --solutions--
```py
def nth_fibonacci(n):
if n == 1:
return 0
if n == 2:
return 1
a, b = 0, 1
for _ in range(3, n + 1):
a, b = b, a + b
return b
```

View File

@@ -0,0 +1,113 @@
---
id: 69306364df283fcaff2e1ad7
title: "Challenge 146: Left-Handed Seat at the Table"
challengeType: 29
dashedName: challenge-146
---
# --description--
Given a 4x2 matrix (array of arrays) representing the seating arrangement for a meal, determine how many seats a left-handed person can sit at.
- A left-handed person cannot sit where a right-handed person would be in the seat to the immediate left of them.
In the given matrix:
- An `"R"` is a seat occupied by a right-handed person.
- An `"L"` is a seat occupied by a left-handed person.
- An `"U"` is an unoccupied seat.
- Only unoccupied seats are available to sit at.
- The seats in the top row are facing "down", and the seats in the bottom row are facing "up" (like a table), so left and right are relative to the seat's orientation.
- Corner seats only have one seat next to them.
For example, in the given matrix:
```json
[
["U", "R", "U", "L"],
["U", "R", "R", "R"]
]
```
The top-left seat is cannot be sat in because there's a right-handed person to the left. The other two open seats can be sat in because there isn't a right-handed person to the left.
# --hints--
`find_left_handed_seats([["U", "R", "U", "L"], ["U", "R", "R", "R"]])` should return `2`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(find_left_handed_seats([["U", "R", "U", "L"], ["U", "R", "R", "R"]]), 2)`)
}})
```
`find_left_handed_seats([["U", "U", "U", "U"], ["U", "U", "U", "U"]])` should return `8`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(find_left_handed_seats([["U", "U", "U", "U"], ["U", "U", "U", "U"]]), 8)`)
}})
```
`find_left_handed_seats([["U", "R", "U", "R"], ["L", "R", "R", "U"]])` should return `0`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(find_left_handed_seats([["U", "R", "U", "R"], ["L", "R", "R", "U"]]), 0)`)
}})
```
`find_left_handed_seats([["L", "U", "R", "R"], ["L", "U", "R", "R"]])` should return `1`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(find_left_handed_seats([["L", "U", "R", "R"], ["L", "U", "R", "R"]]), 1)`)
}})
```
`find_left_handed_seats([["U", "R", "U", "U"], ["U", "U", "L", "U"]])` should return `5`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(find_left_handed_seats([["U", "R", "U", "U"], ["U", "U", "L", "U"]]), 5)`)
}})
```
# --seed--
## --seed-contents--
```py
def find_left_handed_seats(table):
return table
```
# --solutions--
```py
def find_left_handed_seats(table):
available_seats = 0
top_row, bottom_row = table
for i in range(len(top_row)):
if top_row[i] == "U":
if i == len(top_row) - 1:
available_seats += 1
elif top_row[i + 1] != "R":
available_seats += 1
for i in range(len(bottom_row)):
if bottom_row[i] == "U":
if i == 0:
available_seats += 1
elif bottom_row[i - 1] != "R":
available_seats += 1
return available_seats
```

View File

@@ -0,0 +1,101 @@
---
id: 69306364df283fcaff2e1ad8
title: "Challenge 147: Leap Year Calculator"
challengeType: 29
dashedName: challenge-147
---
# --description--
Given an integer year, determine whether it is a leap year.
A year is a leap year if it satisfies the following rules:
- The year is evenly divisible by 4, and
- The year is not evenly divisible by 100, unless
- The year is evenly divisible by 400.
# --hints--
`is_leap_year(2024)` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_leap_year(2024), True)`)
}})
```
`is_leap_year(2023)` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_leap_year(2023), False)`)
}})
```
`is_leap_year(2100)` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_leap_year(2100), False)`)
}})
```
`is_leap_year(2000)` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_leap_year(2000), True)`)
}})
```
`is_leap_year(1999)` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_leap_year(1999), False)`)
}})
```
`is_leap_year(2040)` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_leap_year(2040), True)`)
}})
```
`is_leap_year(2026)` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_leap_year(2026), False)`)
}})
```
# --seed--
## --seed-contents--
```py
def is_leap_year(year):
return year
```
# --solutions--
```py
def is_leap_year(year):
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True
else:
return False
```

View File

@@ -0,0 +1,94 @@
---
id: 69306364df283fcaff2e1ad9
title: "Challenge 148: Tire Pressure"
challengeType: 29
dashedName: challenge-148
---
# --description--
Given an array with four numbers representing the tire pressures in psi of the four tires in your vehicle, and another array of two numbers representing the minimum and maximum pressure for your tires in bar, return an array of four strings describing each tire's status.
- 1 bar equal 14.5038 psi.
Return an array with the following values for each tire:
- `"Low"` if the tire pressure is below the minimum allowed.
- `"Good"` if it's between the minimum and maximum allowed.
- `"High"` if it's above the maximum allowed.
# --hints--
`tire_status([32, 28, 35, 29], [2, 3])` should return `["Good", "Low", "Good", "Low"]`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(tire_status([32, 28, 35, 29], [2, 3]), ["Good", "Low", "Good", "Low"])`)
}})
```
`tire_status([32, 28, 35, 30], [2, 2.3])` should return `["Good", "Low", "High", "Good"]`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(tire_status([32, 28, 35, 30], [2, 2.3]), ["Good", "Low", "High", "Good"])`)
}})
```
`tire_status([29, 26, 31, 28], [2.1, 2.5])` should return `["Low", "Low", "Good", "Low"]`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(tire_status([29, 26, 31, 28], [2.1, 2.5]), ["Low", "Low", "Good", "Low"])`)
}})
```
`tire_status([31, 31, 30, 29], [1.5, 2])` should return `["High", "High", "High", "Good"]`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(tire_status([31, 31, 30, 29], [1.5, 2]), ["High", "High", "High", "Good"])`)
}})
```
`tire_status([30, 28, 30, 29], [1.9, 2.1])` should return `["Good", "Good", "Good", "Good"]`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(tire_status([30, 28, 30, 29], [1.9, 2.1]), ["Good", "Good", "Good", "Good"])`)
}})
```
# --seed--
## --seed-contents--
```py
def tire_status(pressures_psi, range_bar):
return pressures_psi
```
# --solutions--
```py
def tire_status(pressures_psi, range_bar):
psi_to_bar = 1 / 14.5038
min_bar, max_bar = range_bar
result = []
for psi in pressures_psi:
bar = psi * psi_to_bar
if bar < min_bar:
result.append("Low")
elif bar > max_bar:
result.append("High")
else:
result.append("Good")
return result
```

View File

@@ -0,0 +1,88 @@
---
id: 69306364df283fcaff2e1ada
title: "Challenge 149: vOwElcAsE"
challengeType: 29
dashedName: challenge-149
---
# --description--
Given a string, return a new string where all vowels are converted to uppercase and all other alphabetical characters are converted to lowercase.
- Vowels are `"a"`, `"e"`, `"i"`, `"o"`, and `"u"` in any case.
- Non-alphabetical characters should remain unchanged.
# --hints--
`vowel_case("vowelcase")` should return `"vOwElcAsE"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(vowel_case("vowelcase"), "vOwElcAsE")`)
}})
```
`vowel_case("coding is fun")` should return `"cOdIng Is fUn"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(vowel_case("coding is fun"), "cOdIng Is fUn")`)
}})
```
`vowel_case("HELLO, world!")` should return `"hEllO, wOrld!"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(vowel_case("HELLO, world!"), "hEllO, wOrld!")`)
}})
```
`vowel_case("git cherry-pick")` should return `"gIt chErry-pIck"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(vowel_case("git cherry-pick"), "gIt chErry-pIck")`)
}})
```
`vowel_case("HEAD~1")` should return `"hEAd~1"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(vowel_case("HEAD~1"), "hEAd~1")`)
}})
```
# --seed--
## --seed-contents--
```py
def vowel_case(s):
return s
```
# --solutions--
```py
def vowel_case(s):
vowels = "aeiouAEIOU"
result = ""
for char in s:
if char in vowels:
result += char.upper()
elif char.isalpha():
result += char.lower()
else:
result += char
return result
```

View File

@@ -0,0 +1,85 @@
---
id: 69373793f5a867f769cde135
title: "Challenge 150: Markdown Unordered List Parser"
challengeType: 29
dashedName: challenge-150
---
# --description--
Given the string of a valid unordered list in Markdown, return the equivalent HTML string.
An unordered list consists of one or more list items. A valid list item appears on its own line and:
- Starts with a dash (`"-"`), followed by
- At least one space, and then
- The list item text.
The list is given as a single string with new lines separated by the newline character (`"\n"`). Do not include the newline characters in the item text.
Wrap each list item in HTML `li` tags, and the whole list of items in `ul` tags.
For example, given `"- Item A\n- Item B"`, return `"<ul><li>Item A</li><li>Item B</li></ul>"`.
Note: The console may not display HTML tags in strings when logging messages. Check the browser console to see logs with tags included.
# --hints--
`parse_unordered_list("- Item A\n- Item B")` should return `"<ul><li>Item A</li><li>Item B</li></ul>"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(parse_unordered_list("- Item A\\n- Item B"), "<ul><li>Item A</li><li>Item B</li></ul>")`)
}})
```
`parse_unordered_list("- JavaScript\n- Python")` should return `"<ul><li>JavaScript</li><li>Python</li></ul>"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(parse_unordered_list("- JavaScript\\n- Python"), "<ul><li>JavaScript</li><li>Python</li></ul>")`)
}})
```
`parse_unordered_list("- 2 C Flour\n- 1/2 C Sugar\n- 1 Tsp Vanilla")` should return `"<ul><li>2 C Flour</li><li>1/2 C Sugar</li><li>1 Tsp Vanilla</li></ul>"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(parse_unordered_list("- 2 C Flour\\n- 1/2 C Sugar\\n- 1 Tsp Vanilla"), "<ul><li>2 C Flour</li><li>1/2 C Sugar</li><li>1 Tsp Vanilla</li></ul>")`)
}})
```
`parse_unordered_list("- A-1\n- A-2\n- B-1")` should return `"<ul><li>A-1</li><li>A-2</li><li>B-1</li></ul>"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(parse_unordered_list("- A-1\\n- A-2\\n- B-1"), "<ul><li>A-1</li><li>A-2</li><li>B-1</li></ul>")`)
}})
```
# --seed--
## --seed-contents--
```py
def parse_unordered_list(markdown):
return markdown
```
# --solutions--
```py
def parse_unordered_list(markdown):
lines = markdown.split("\n")
list_items = []
for line in lines:
list_items.append(f"<li>{line[1:].strip()}</li>")
return f"<ul>{''.join(list_items)}</ul>"
```

View File

@@ -0,0 +1,102 @@
---
id: 69373793f5a867f769cde136
title: "Challenge 151: Sorted Array?"
challengeType: 29
dashedName: challenge-151
---
# --description--
Given an array of numbers, determine if the numbers are sorted in ascending order, descending order, or neither.
If the given array is:
- In ascending order (lowest to highest), return `"Ascending"`.
- In descending order (highest to lowest), return `"Descending"`.
- Not sorted in ascending or descending order, return `"Not sorted"`.
# --hints--
`is_sorted([1, 2, 3, 4, 5])` should return `"Ascending"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(is_sorted([1, 2, 3, 4, 5]), "Ascending")`)
}})
```
`is_sorted([10, 8, 6, 4, 2])` should return `"Descending"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(is_sorted([10, 8, 6, 4, 2]), "Descending")`)
}})
```
`is_sorted([1, 3, 2, 4, 5])` should return `"Not sorted"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(is_sorted([1, 3, 2, 4, 5]), "Not sorted")`)
}})
```
`is_sorted([3.14, 2.71, 1.61, 0.57])` should return `"Descending"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(is_sorted([3.14, 2.71, 1.61, 0.57]), "Descending")`)
}})
```
`is_sorted([12.3, 23.4, 34.5, 45.6, 56.7, 67.8, 78.9])` should return `"Ascending"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(is_sorted([12.3, 23.4, 34.5, 45.6, 56.7, 67.8, 78.9]), "Ascending")`)
}})
```
`is_sorted([0.4, 0.5, 0.3])` should return `"Not sorted"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(is_sorted([0.4, 0.5, 0.3]), "Not sorted")`)
}})
```
# --seed--
## --seed-contents--
```py
def is_sorted(arr):
return arr
```
# --solutions--
```py
def is_sorted(arr):
ascending = True
descending = True
for i in range(1, len(arr)):
if arr[i] < arr[i - 1]:
ascending = False
if arr[i] > arr[i - 1]:
descending = False
if ascending:
return "Ascending"
if descending:
return "Descending"
return "Not sorted"
```

View File

@@ -0,0 +1,91 @@
---
id: 69373793f5a867f769cde137
title: "Challenge 152: Circular Prime"
challengeType: 29
dashedName: challenge-152
---
# --description--
Given an integer, determine if it is a circular prime.
A circular prime is an integer where all rotations of its digits are themselves prime.
For example, `197` is a circular prime because all rotations of its digits: `197`, `971`, and `719`, are prime numbers.
# --hints--
`is_circular_prime(197)` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_circular_prime(197), True)`)
}})
```
`is_circular_prime(23)` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_circular_prime(23), False)`)
}})
```
`is_circular_prime(13)` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_circular_prime(13), True)`)
}})
```
`is_circular_prime(89)` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_circular_prime(89), False)`)
}})
```
`is_circular_prime(1193)` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_circular_prime(1193), True)`)
}})
```
# --seed--
## --seed-contents--
```py
def is_circular_prime(n):
return n
```
# --solutions--
```py
import math
def is_prime(n):
if n < 2:
return False
for i in range(2, int(math.isqrt(n)) + 1):
if n % i == 0:
return False
return True
def rotations(n):
s = str(n)
return [int(s[i:] + s[:i]) for i in range(len(s))]
def is_circular_prime(n):
return all(is_prime(rot) for rot in rotations(n))
```

View File

@@ -0,0 +1,110 @@
---
id: 69373793f5a867f769cde138
title: "Challenge 153: Tic-Tac-Toe"
challengeType: 29
dashedName: challenge-153
---
# --description--
Given a 3×3 matrix (an array of arrays) representing a completed Tic-Tac-Toe game, determine the winner.
- Each element in the given matrix is either an `"X"` or `"O"`.
A player wins if they have three of their characters in a row - horizontally, vertically, or diagonally.
Return:
- `"X wins"` if player X has three in a row.
- `"O wins"` if player O has three in a row.
- `"Draw"` if no player has three in a row.
# --hints--
`tic_tac_toe([["X", "X", "X"], ["O", "O", "X"], ["O", "X", "O"]])` should return `"X wins"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(tic_tac_toe([["X", "X", "X"], ["O", "O", "X"], ["O", "X", "O"]]), "X wins")`)
}})
```
`tic_tac_toe([["X", "O", "X"], ["X", "O", "X"], ["O", "O", "X"]])` should return `"O wins"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(tic_tac_toe([["X", "O", "X"], ["X", "O", "X"], ["O", "O", "X"]]), "O wins")`)
}})
```
`tic_tac_toe([["X", "O", "X"], ["O", "X", "O"], ["O", "X", "O"]])` should return `"Draw"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(tic_tac_toe([["X", "O", "X"], ["O", "X", "O"], ["O", "X", "O"]]), "Draw")`)
}})
```
`tic_tac_toe([["X", "X", "O"], ["X", "O", "X"], ["O", "X", "X"]])` should return `"O wins"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(tic_tac_toe([["X", "X", "O"], ["X", "O", "X"], ["O", "X", "X"]]), "O wins")`)
}})
```
`tic_tac_toe([["X", "O", "O"], ["O", "X", "O"], ["O", "X", "X"]])` should return `"X wins"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(tic_tac_toe([["X", "O", "O"], ["O", "X", "O"], ["O", "X", "X"]]), "X wins")`)
}})
```
`tic_tac_toe([["O", "X", "X"], ["X", "O", "O"], ["X", "O", "X"]])` should return `"Draw"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(tic_tac_toe([["O", "X", "X"], ["X", "O", "O"], ["X", "O", "X"]]), "Draw")`)
}})
```
# --seed--
## --seed-contents--
```py
def tic_tac_toe(board):
return board
```
# --solutions--
```py
def tic_tac_toe(board):
lines = []
for row in board:
lines.append(row)
for c in range(3):
lines.append([board[0][c], board[1][c], board[2][c]])
lines.append([board[0][0], board[1][1], board[2][2]])
lines.append([board[0][2], board[1][1], board[2][0]])
for line in lines:
if all(cell == "X" for cell in line):
return "X wins"
if all(cell == "O" for cell in line):
return "O wins"
return "Draw"
```

View File

@@ -0,0 +1,106 @@
---
id: 69373793f5a867f769cde139
title: "Challenge 154: Par for the Hole"
challengeType: 29
dashedName: challenge-154
---
# --description--
Given two integers, the par for a golf hole and the number of strokes a golfer took on that hole, return the golfer's score using golf terms.
Return:
- `"Hole in one!"` if it took one stroke.
- `"Eagle"` if it took two strokes less than par.
- `"Birdie"` if it took one stroke less than par.
- `"Par"` if it took the same number of strokes as par.
- `"Bogey"` if it took one stroke more than par.
- `"Double bogey"` if took two strokes more than par.
# --hints--
`golf_score(3, 3)` should return `"Par"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(golf_score(3, 3), "Par")`)
}})
```
`golf_score(4, 3)` should return `"Birdie"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(golf_score(4, 3), "Birdie")`)
}})
```
`golf_score(3, 1)` should return `"Hole in one!"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(golf_score(3, 1), "Hole in one!")`)
}})
```
`golf_score(5, 7)` should return `"Double bogey"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(golf_score(5, 7), "Double bogey")`)
}})
```
`golf_score(4, 5)` should return `"Bogey"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(golf_score(4, 5), "Bogey")`)
}})
```
`golf_score(5, 3)` should return `"Eagle"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(golf_score(5, 3), "Eagle")`)
}})
```
# --seed--
## --seed-contents--
```py
def golf_score(par, strokes):
return par
```
# --solutions--
```py
def golf_score(par, strokes):
if strokes == 1:
return "Hole in one!"
diff = strokes - par
if diff == -2:
return "Eagle"
if diff == -1:
return "Birdie"
if diff == 0:
return "Par"
if diff == 1:
return "Bogey"
if diff == 2:
return "Double bogey"
```

View File

@@ -0,0 +1,100 @@
---
id: 69373793f5a867f769cde13a
title: "Challenge 155: Plant the Crop"
challengeType: 29
dashedName: challenge-155
---
# --description--
Given an integer representing the size of your farm field, and `"acres"` or `"hectares"` representing the unit for the size of your farm field, and a type of crop, determine how many plants of that type you can fit in your field.
- 1 acre equals 4046.86 square meters.
- 1 hectare equals 10,000 square meters.
Here's a list of crops that will be given as input and how much space a single plant takes:
|Crop|Space per plant|
|-|-|
|`"corn"`|1 square meter|
|`"wheat"`|0.1 square meters|
|`"soybeans"`|0.5 square meters|
|`"tomatoes"`|0.25 square meters|
|`"lettuce"`|0.2 square meters|
Return the number of plants that fit in the field, rounded down to the nearest whole plant.
# --hints--
`get_number_of_plants(1, "acres", "corn")` should return `4046`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(get_number_of_plants(1, "acres", "corn"), 4046)`)
}})
```
`get_number_of_plants(2, "hectares", "lettuce")` should return `100000`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(get_number_of_plants(2, "hectares", "lettuce"), 100000)`)
}})
```
`get_number_of_plants(20, "acres", "soybeans")` should return `161874`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(get_number_of_plants(20, "acres", "soybeans"), 161874)`)
}})
```
`get_number_of_plants(3.75, "hectares", "tomatoes")` should return `150000`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(get_number_of_plants(3.75, "hectares", "tomatoes"), 150000)`)
}})
```
`get_number_of_plants(16.75, "acres", "tomatoes")` should return `271139`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(get_number_of_plants(16.75, "acres", "tomatoes"), 271139)`)
}})
```
# --seed--
## --seed-contents--
```py
def get_number_of_plants(field_size, unit, crop):
return field_size
```
# --solutions--
```py
import math
def get_number_of_plants(field_size, unit, crop):
crop_space = {
"corn": 1,
"wheat": 0.1,
"soybeans": 0.5,
"tomatoes": 0.25,
"lettuce": 0.2
}
field_in_sqm = field_size * 4046.86 if unit == "acres" else field_size * 10000
return math.floor(field_in_sqm / crop_space[crop.lower()])
```

View File

@@ -0,0 +1,74 @@
---
id: 6939b873185d8e00d453563b
title: "Challenge 156: Odd or Even?"
challengeType: 29
dashedName: challenge-156
---
# --description--
Given a positive integer, return `"Odd"` if it's an odd number, and `"Even"` is it's even.
# --hints--
`odd_or_even(1)` should return `"Odd"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(odd_or_even(1), "Odd")`)
}})
```
`odd_or_even(2)` should return `"Even"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(odd_or_even(2), "Even")`)
}})
```
`odd_or_even(13)` should return `"Odd"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(odd_or_even(13), "Odd")`)
}})
```
`odd_or_even(196)` should return `"Even"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(odd_or_even(196), "Even")`)
}})
```
`odd_or_even(123456789)` should return `"Odd"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(odd_or_even(123456789), "Odd")`)
}})
```
# --seed--
## --seed-contents--
```py
def odd_or_even(n):
return n
```
# --solutions--
```py
def odd_or_even(n):
return "Even" if n % 2 == 0 else "Odd"
```

View File

@@ -0,0 +1,65 @@
---
id: 6939b873185d8e00d453563c
title: "Challenge 157: Markdown Link Parser"
challengeType: 29
dashedName: challenge-157
---
# --description--
Given the string of a link in Markdown, return the equivalent HTML string.
A Markdown image has the following format: `"[link_text](link_url)"`. Return the string of the HTML `a` tag with the `href` set to the `link_url` and the `link_text` as the tag content.
For example, given `"[freeCodeCamp](https://freecodecamp.org/)"` return `'<a href="https://freecodecamp.org/">freeCodeCamp</a>'`;
Note: The console may not display HTML tags in strings when logging messages — check the browser console to see logs with tags included.
# --hints--
`parse_link("[freeCodeCamp](https://freecodecamp.org/)")` should return `'<a href="https://freecodecamp.org/">freeCodeCamp</a>'`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(parse_link("[freeCodeCamp](https://freecodecamp.org/)"), '<a href="https://freecodecamp.org/">freeCodeCamp</a>')`)
}})
```
`parse_link("[Donate to our charity.](https://www.freecodecamp.org/donate/)")` should return `'<a href="https://www.freecodecamp.org/donate/">Donate to our charity.</a>'`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(parse_link("[Donate to our charity.](https://www.freecodecamp.org/donate/)"), '<a href="https://www.freecodecamp.org/donate/">Donate to our charity.</a>')`)
}})
```
`parse_link("[Contribute to our repository at https://github.com/freeCodeCamp/freeCodeCamp.](https://github.com/freeCodeCamp/freeCodeCamp/)")` should return `'<a href="https://github.com/freeCodeCamp/freeCodeCamp/">Contribute to our repository at https://github.com/freeCodeCamp/freeCodeCamp.</a>'`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(parse_link("[Contribute to our repository at https://github.com/freeCodeCamp/freeCodeCamp.](https://github.com/freeCodeCamp/freeCodeCamp/)"), '<a href="https://github.com/freeCodeCamp/freeCodeCamp/">Contribute to our repository at https://github.com/freeCodeCamp/freeCodeCamp.</a>')`)
}})
```
# --seed--
## --seed-contents--
```py
def parse_link(markdown):
return markdown
```
# --solutions--
```py
import re
def parse_link(markdown):
match = re.match(r'\[(.*?)\]\((.*?)\)', markdown)
text, url = match.groups()
return f'<a href="{url}">{text}</a>'
```

View File

@@ -0,0 +1,68 @@
---
id: 6939b873185d8e00d453563d
title: "Challenge 158: Array Swap"
challengeType: 29
dashedName: challenge-158
---
# --description--
Given an array with two values, return an array with the values swapped.
For example, given `["A", "B"]` return `["B", "A"]`.
# --hints--
`array_swap(["A", "B"])` should return `["B", "A"]`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(array_swap(["A", "B"]), ["B", "A"])`)
}})
```
`array_swap([25, 20])` should return `[20, 25]`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(array_swap([25, 20]), [20, 25])`)
}})
```
`array_swap([True, False])` should return `[False, True]`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(array_swap([True, False]), [False, True])`)
}})
```
`array_swap(["1", 1])` should return `[1, "1"]`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(array_swap(["1", 1]), [1, "1"])`)
}})
```
# --seed--
## --seed-contents--
```py
def array_swap(arr):
return arr
```
# --solutions--
```py
def array_swap(arr):
return [arr[1], arr[0]]
```

View File

@@ -0,0 +1,88 @@
---
id: 6939b873185d8e00d453563e
title: "Challenge 159: Integer Hypotenuse"
challengeType: 29
dashedName: challenge-159
---
# --description--
Given two positive integers representing the lengths for the two legs (the two short sides) of a right triangle, determine whether the hypotenuse is an integer.
The length of the hypotenuse is calculated by adding the squares of the two leg lengths together and then taking the square root of that total (a<sup>2</sup> + b<sup>2</sup> = c<sup>2</sup>).
# --hints--
`is_integer_hypotenuse(3, 4)` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_integer_hypotenuse(3, 4), True)`)
}})
```
`is_integer_hypotenuse(2, 3)` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_integer_hypotenuse(2, 3), False)`)
}})
```
`is_integer_hypotenuse(5, 12)` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_integer_hypotenuse(5, 12), True)`)
}})
```
`is_integer_hypotenuse(10, 10)` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_integer_hypotenuse(10, 10), False)`)
}})
```
`is_integer_hypotenuse(780, 1040)` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_integer_hypotenuse(780, 1040), True)`)
}})
```
`is_integer_hypotenuse(250, 333)` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_integer_hypotenuse(250, 333), False)`)
}})
```
# --seed--
## --seed-contents--
```py
def is_integer_hypotenuse(a, b):
return a
```
# --solutions--
```py
import math
def is_integer_hypotenuse(a, b):
total = a*a + b*b
c = math.isqrt(total)
return c*c == total
```

View File

@@ -0,0 +1,109 @@
---
id: 6939b873185d8e00d453563f
title: "Challenge 160: Knight Moves"
challengeType: 29
dashedName: challenge-160
---
# --description--
Given the position of a knight on a chessboard, return the number of valid squares the knight can move to.
A standard chessboard is 8x8, with columns labeled `A` through `H` (left to right) and rows labeled `1` through `8` (bottom to top). It looks like this:
|**A8**|**B8**|**C8**|**D8**|**E8**|**F8**|**G8**|**H8**|
|-|-|-|-|-|-|-|-|
|**A7**|**B7**|**C7**|**D7**|**E7**|**F7**|**G7**|**H7**|
|**A6**|**B6**|**C6**|**D6**|**E6**|**F6**|**G6**|**H6**|
|**A5**|**B5**|**C5**|**D5**|**E5**|**F5**|**G5**|**H5**|
|**A4**|**B4**|**C4**|**D4**|**E4**|**F4**|**G4**|**H4**|
|**A3**|**B3**|**C3**|**D3**|**E3**|**F3**|**G3**|**H3**|
|**A2**|**B2**|**C2**|**D2**|**E2**|**F2**|**G2**|**H2**|
|**A1**|**B1**|**C1**|**D1**|**E1**|**F1**|**G1**|**H1**|
A knight moves in an "L" shape: two squares in one direction (horizontal or vertical), and one square in the perpendicular direction.
This means a knight can move to up to eight possible positions, but fewer when near the edges of the board. For example, if a knight was at `A1`, it could only move to `B3` or `C2`.
# --hints--
`knight_moves("A1")` should return `2`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(knight_moves("A1"), 2)`)
}})
```
`knight_moves("D4")` should return `8`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(knight_moves("D4"), 8)`)
}})
```
`knight_moves("G6")` should return `6`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(knight_moves("G6"), 6)`)
}})
```
`knight_moves("B8")` should return `3`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(knight_moves("B8"), 3)`)
}})
```
`knight_moves("H3")` should return `4`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(knight_moves("H3"), 4)`)
}})
```
# --seed--
## --seed-contents--
```py
def knight_moves(position):
return position
```
# --solutions--
```py
def knight_moves(position):
col = ord(position[0]) - ord('A')
row = int(position[1]) - 1
moves = [
(2, 1), (2, -1),
(-2, 1), (-2, -1),
(1, 2), (1, -2),
(-1, 2), (-1, -2)
]
valid = 0
for dx, dy in moves:
new_col = col + dx
new_row = row + dy
if 0 <= new_col < 8 and 0 <= new_row < 8:
valid += 1
return valid
```

View File

@@ -578,6 +578,74 @@
{
"id": "69272dcf1c24b44fd79137c6",
"title": "Challenge 143: Markdown Italic Parser"
},
{
"id": "69306364df283fcaff2e1ad5",
"title": "Challenge 144: Resolution Streak"
},
{
"id": "69306364df283fcaff2e1ad6",
"title": "Challenge 145: Nth Fibonacci Number"
},
{
"id": "69306364df283fcaff2e1ad7",
"title": "Challenge 146: Left-Handed Seat at the Table"
},
{
"id": "69306364df283fcaff2e1ad8",
"title": "Challenge 147: Leap Year Calculator"
},
{
"id": "69306364df283fcaff2e1ad9",
"title": "Challenge 148: Tire Pressure"
},
{
"id": "69306364df283fcaff2e1ada",
"title": "Challenge 149: vOwElcAsE"
},
{
"id": "69373793f5a867f769cde135",
"title": "Challenge 150: Markdown Unordered List Parser"
},
{
"id": "69373793f5a867f769cde136",
"title": "Challenge 151: Sorted Array?"
},
{
"id": "69373793f5a867f769cde137",
"title": "Challenge 152: Circular Prime"
},
{
"id": "69373793f5a867f769cde138",
"title": "Challenge 153: Tic-Tac-Toe"
},
{
"id": "69373793f5a867f769cde139",
"title": "Challenge 154: Par for the Hole"
},
{
"id": "69373793f5a867f769cde13a",
"title": "Challenge 155: Plant the Crop"
},
{
"id": "6939b873185d8e00d453563b",
"title": "Challenge 156: Odd or Even?"
},
{
"id": "6939b873185d8e00d453563c",
"title": "Challenge 157: Markdown Link Parser"
},
{
"id": "6939b873185d8e00d453563d",
"title": "Challenge 158: Array Swap"
},
{
"id": "6939b873185d8e00d453563e",
"title": "Challenge 159: Integer Hypotenuse"
},
{
"id": "6939b873185d8e00d453563f",
"title": "Challenge 160: Knight Moves"
}
]
}

View File

@@ -577,6 +577,74 @@
{
"id": "69272dcf1c24b44fd79137c6",
"title": "Challenge 143: Markdown Italic Parser"
},
{
"id": "69306364df283fcaff2e1ad5",
"title": "Challenge 144: Resolution Streak"
},
{
"id": "69306364df283fcaff2e1ad6",
"title": "Challenge 145: Nth Fibonacci Number"
},
{
"id": "69306364df283fcaff2e1ad7",
"title": "Challenge 146: Left-Handed Seat at the Table"
},
{
"id": "69306364df283fcaff2e1ad8",
"title": "Challenge 147: Leap Year Calculator"
},
{
"id": "69306364df283fcaff2e1ad9",
"title": "Challenge 148: Tire Pressure"
},
{
"id": "69306364df283fcaff2e1ada",
"title": "Challenge 149: vOwElcAsE"
},
{
"id": "69373793f5a867f769cde135",
"title": "Challenge 150: Markdown Unordered List Parser"
},
{
"id": "69373793f5a867f769cde136",
"title": "Challenge 151: Sorted Array?"
},
{
"id": "69373793f5a867f769cde137",
"title": "Challenge 152: Circular Prime"
},
{
"id": "69373793f5a867f769cde138",
"title": "Challenge 153: Tic-Tac-Toe"
},
{
"id": "69373793f5a867f769cde139",
"title": "Challenge 154: Par for the Hole"
},
{
"id": "69373793f5a867f769cde13a",
"title": "Challenge 155: Plant the Crop"
},
{
"id": "6939b873185d8e00d453563b",
"title": "Challenge 156: Odd or Even?"
},
{
"id": "6939b873185d8e00d453563c",
"title": "Challenge 157: Markdown Link Parser"
},
{
"id": "6939b873185d8e00d453563d",
"title": "Challenge 158: Array Swap"
},
{
"id": "6939b873185d8e00d453563e",
"title": "Challenge 159: Integer Hypotenuse"
},
{
"id": "6939b873185d8e00d453563f",
"title": "Challenge 160: Knight Moves"
}
]
}

View File

@@ -13,7 +13,7 @@ const { MONGOHQ_URL } = process.env;
// Number challenges in the dev-playground blocks
// Update this if the number of challenges changes
const EXPECTED_CHALLENGE_COUNT = 143;
const EXPECTED_CHALLENGE_COUNT = 160;
// Date to set for the first challenge, second challenge will be one day later, etc...
// **DO NOT CHANGE THIS AFTER RELEASE (if seeding production - okay for local dev)**