mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-05-28 18:26:54 +00:00
feat(curriculum): daily challenges 264-278 (#67117)
Co-authored-by: majestic-owl448 <26656284+majestic-owl448@users.noreply.github.com>
This commit is contained in:
+76
@@ -0,0 +1,76 @@
|
||||
---
|
||||
id: 69cfca90e8a0a6d4d6871c4e
|
||||
title: "Challenge 264: Anagram Groups"
|
||||
challengeType: 28
|
||||
dashedName: challenge-264
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given an array of words, return a 2d array of the words grouped into anagrams.
|
||||
|
||||
- Words are anagrams if they contain the same letters in any order.
|
||||
- Each word belongs to exactly one group.
|
||||
- Return order doesn't matter.
|
||||
|
||||
For example, given `["listen", "silent", "hello", "enlist", "world"]`, return `[["listen", "silent", "enlist"], ["hello"], ["world"]]`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`groupAnagrams(["listen", "silent", "hello", "enlist", "world"])` should return `[["listen", "silent", "enlist"], ["hello"], ["world"]]`.
|
||||
|
||||
```js
|
||||
const groups = groupAnagrams(["listen", "silent", "hello", "enlist", "world"]);
|
||||
const sorted = groups.map(g => g.sort()).sort((a, b) => a[0].localeCompare(b[0]));
|
||||
assert.deepEqual(sorted, [["enlist", "listen", "silent"], ["hello"], ["world"]]);
|
||||
```
|
||||
|
||||
`groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"])` should return `[["ate", "eat", "tea"], ["bat"], ["nat", "tan"]]`.
|
||||
|
||||
```js
|
||||
const groups = groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]);
|
||||
const sorted = groups.map(g => g.sort()).sort((a, b) => a[0].localeCompare(b[0]));
|
||||
assert.deepEqual(sorted, [["ate", "eat", "tea"], ["bat"], ["nat", "tan"]]);
|
||||
```
|
||||
|
||||
`groupAnagrams(["care", "race", "acre", "pots", "stop", "tops", "opts", "post", "spot", "evil", "vile", "live", "veil"])` should return `[["acre", "care", "race"], ["evil", "live", "veil", "vile"], ["opts", "post", "pots", "spot", "stop", "tops"]]`.
|
||||
|
||||
```js
|
||||
const groups = groupAnagrams(["care", "race", "acre", "pots", "stop", "tops", "opts", "post", "spot", "evil", "vile", "live", "veil"]);
|
||||
const sorted = groups.map(g => g.sort()).sort((a, b) => a[0].localeCompare(b[0]));
|
||||
assert.deepEqual(sorted, [["acre", "care", "race"], ["evil", "live", "veil", "vile"], ["opts", "post", "pots", "spot", "stop", "tops"]]);
|
||||
|
||||
```
|
||||
|
||||
`groupAnagrams(["algorithms", "logarithms", "education", "cautioned", "auctioned", "triangle", "integral", "alerting", "relating"])` should return `[["alerting", "integral", "relating", "triangle"], ["algorithms", "logarithms"], ["auctioned", "cautioned", "education"]]`.
|
||||
|
||||
```js
|
||||
const groups = groupAnagrams(["algorithms", "logarithms", "education", "cautioned", "auctioned", "triangle", "integral", "alerting", "relating"]);
|
||||
const sorted = groups.map(g => g.sort()).sort((a, b) => a[0].localeCompare(b[0]));
|
||||
assert.deepEqual(sorted, [["alerting", "integral", "relating", "triangle"], ["algorithms", "logarithms"], ["auctioned", "cautioned", "education"]]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function groupAnagrams(words) {
|
||||
|
||||
return words;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function groupAnagrams(words) {
|
||||
const map = {};
|
||||
for (const word of words) {
|
||||
const key = word.split('').sort().join('');
|
||||
if (!map[key]) map[key] = [];
|
||||
map[key].push(word);
|
||||
}
|
||||
return Object.values(map);
|
||||
}
|
||||
```
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
---
|
||||
id: 69cfca90e8a0a6d4d6871c4f
|
||||
title: "Challenge 265: Deepest Brackets"
|
||||
challengeType: 28
|
||||
dashedName: challenge-265
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string containing balanced brackets, return the content of the deepest nested brackets.
|
||||
|
||||
- Brackets can be any of the three types: `()`, `[]`, and `{}`.
|
||||
- The input will always have a single deepest group.
|
||||
|
||||
For example, given `"(hello (world))"`, return `"world"`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`getDeepestBrackets("(hello (world))")` should return `"world"`.
|
||||
|
||||
```js
|
||||
assert.equal(getDeepestBrackets("(hello (world))"), "world");
|
||||
```
|
||||
|
||||
`getDeepestBrackets("[outer [inner] outer]")` should return `"inner"`.
|
||||
|
||||
```js
|
||||
assert.equal(getDeepestBrackets("[outer [inner] outer]"), "inner");
|
||||
```
|
||||
|
||||
`getDeepestBrackets("{a{b}c{d{e}f}g}")` should return `"e"`.
|
||||
|
||||
```js
|
||||
assert.equal(getDeepestBrackets("{a{b}c{d{e}f}g}"), "e");
|
||||
```
|
||||
|
||||
`getDeepestBrackets("[the {quick (brown [fox] jumped) over (the) lazy} dog]")` should return `"fox"`.
|
||||
|
||||
```js
|
||||
assert.equal(getDeepestBrackets("[the {quick (brown [fox] jumped) over (the) lazy} dog]"), "fox");
|
||||
```
|
||||
|
||||
`getDeepestBrackets("f[(r)e{e}C{o[(d){e(C)}a]m}]p")` should return `"C"`.
|
||||
|
||||
```js
|
||||
assert.equal(getDeepestBrackets("f[(r)e{e}C{o[(d){e(C)}a]m}]p"), "C");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function getDeepestBrackets(str) {
|
||||
|
||||
return str;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function getDeepestBrackets(str) {
|
||||
let maxDepth = 0, depth = 0, content = '';
|
||||
let start = 0;
|
||||
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
if ('([{'.includes(str[i])) {
|
||||
depth++;
|
||||
if (depth > maxDepth) {
|
||||
maxDepth = depth;
|
||||
start = i + 1;
|
||||
}
|
||||
} else if (')]}'.includes(str[i])) {
|
||||
if (depth === maxDepth) {
|
||||
content = str.slice(start, i);
|
||||
}
|
||||
depth--;
|
||||
}
|
||||
}
|
||||
return content;
|
||||
}
|
||||
```
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
---
|
||||
id: 69cfca90e8a0a6d4d6871c50
|
||||
title: "Challenge 266: Good Day"
|
||||
challengeType: 28
|
||||
dashedName: challenge-266
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a time string in `"HH:MM"` format (24-hour clock), return:
|
||||
|
||||
- `"Good morning"` for times `05:00` to `11:59`
|
||||
- `"Good afternoon"` for times `12:00` to `17:59`
|
||||
- `"Good evening"` for times `18:00` to `21:59`
|
||||
- `"Good night"` for times `22:00` to `04:59`
|
||||
|
||||
# --hints--
|
||||
|
||||
`getGreeting("06:30")` should return `"Good morning"`.
|
||||
|
||||
```js
|
||||
assert.equal(getGreeting("06:30"), "Good morning");
|
||||
```
|
||||
|
||||
`getGreeting("12:00")` should return `"Good afternoon"`.
|
||||
|
||||
```js
|
||||
assert.equal(getGreeting("12:00"), "Good afternoon");
|
||||
```
|
||||
|
||||
`getGreeting("21:59")` should return `"Good evening"`.
|
||||
|
||||
```js
|
||||
assert.equal(getGreeting("21:59"), "Good evening");
|
||||
```
|
||||
|
||||
`getGreeting("00:01")` should return `"Good night"`.
|
||||
|
||||
```js
|
||||
assert.equal(getGreeting("00:01"), "Good night");
|
||||
```
|
||||
|
||||
`getGreeting("11:30")` should return `"Good morning"`.
|
||||
|
||||
```js
|
||||
assert.equal(getGreeting("11:30"), "Good morning");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function getGreeting(time) {
|
||||
|
||||
return time;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function getGreeting(time) {
|
||||
const [hours, minutes] = time.split(':').map(Number);
|
||||
const total = hours * 60 + minutes;
|
||||
|
||||
if (total >= 300 && total < 720) return 'Good morning';
|
||||
if (total >= 720 && total < 1080) return 'Good afternoon';
|
||||
if (total >= 1080 && total < 1320) return 'Good evening';
|
||||
return 'Good night';
|
||||
}
|
||||
```
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
---
|
||||
id: 69cfca90e8a0a6d4d6871c51
|
||||
title: "Challenge 267: Parsec Converter"
|
||||
challengeType: 28
|
||||
dashedName: challenge-267
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In a distant galaxy, parsecs are used to measure both time and distance. Given an integer number of parsecs, return its equivalent in time or distance.
|
||||
|
||||
- If the given integer is odd, it represents time. If it's even, it represents distance.
|
||||
|
||||
Use these conversion rates:
|
||||
|
||||
| Parsecs | Time/Distance |
|
||||
| - | - |
|
||||
| 1 | 2 hours |
|
||||
| 2 | 6 light years |
|
||||
|
||||
Return the converted value as an integer.
|
||||
|
||||
# --hints--
|
||||
|
||||
`convertParsecs(1)` should return `2`.
|
||||
|
||||
```js
|
||||
assert.equal(convertParsecs(1), 2);
|
||||
```
|
||||
|
||||
`convertParsecs(2)` should return `6`.
|
||||
|
||||
```js
|
||||
assert.equal(convertParsecs(2), 6);
|
||||
```
|
||||
|
||||
`convertParsecs(31)` should return `62`.
|
||||
|
||||
```js
|
||||
assert.equal(convertParsecs(31), 62);
|
||||
```
|
||||
|
||||
`convertParsecs(88)` should return `264`.
|
||||
|
||||
```js
|
||||
assert.equal(convertParsecs(88), 264);
|
||||
```
|
||||
|
||||
`convertParsecs(17)` should return `34`.
|
||||
|
||||
```js
|
||||
assert.equal(convertParsecs(17), 34);
|
||||
```
|
||||
|
||||
`convertParsecs(14)` should return `42`.
|
||||
|
||||
```js
|
||||
assert.equal(convertParsecs(14), 42);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function convertParsecs(parsecs) {
|
||||
|
||||
return parsecs;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function convertParsecs(parsecs) {
|
||||
if (parsecs % 2 !== 0) {
|
||||
return parsecs * 2;
|
||||
} else {
|
||||
return parsecs * 3;
|
||||
}
|
||||
}
|
||||
```
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
---
|
||||
id: 69cfca90e8a0a6d4d6871c52
|
||||
title: "Challenge 268: Narcissistic Number"
|
||||
challengeType: 28
|
||||
dashedName: challenge-268
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a positive integer, determine whether it is a narcissistic number.
|
||||
|
||||
- A number is narcissistic if the sum of each of its digits raised to the power of the total number of digits equals the number itself.
|
||||
|
||||
For example, 153 has 3 digits, and 1<sup>3</sup> + 5<sup>3</sup> + 3<sup>3</sup> = 153, so it is narcissistic.
|
||||
|
||||
# --hints--
|
||||
|
||||
`isNarcissistic(153)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isNarcissistic(153));
|
||||
```
|
||||
|
||||
`isNarcissistic(154)` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isNarcissistic(154));
|
||||
```
|
||||
|
||||
`isNarcissistic(371)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isNarcissistic(371));
|
||||
```
|
||||
|
||||
`isNarcissistic(512)` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isNarcissistic(512));
|
||||
```
|
||||
|
||||
`isNarcissistic(9)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isNarcissistic(9));
|
||||
```
|
||||
|
||||
`isNarcissistic(11)` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isNarcissistic(11));
|
||||
```
|
||||
|
||||
`isNarcissistic(9474)` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isNarcissistic(9474));
|
||||
```
|
||||
|
||||
`isNarcissistic(6549)` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isNarcissistic(6549));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function isNarcissistic(n) {
|
||||
|
||||
return n;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function isNarcissistic(n) {
|
||||
const digits = String(n).split('');
|
||||
const power = digits.length;
|
||||
const sum = digits.reduce((acc, d) => acc + Math.pow(Number(d), power), 0);
|
||||
return sum === n;
|
||||
}
|
||||
```
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
---
|
||||
id: 69cfca90e8a0a6d4d6871c53
|
||||
title: "Challenge 269: Allergen Friendly Meals"
|
||||
challengeType: 28
|
||||
dashedName: challenge-269
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given an array of meals and an array of allergens to avoid, return the names of all the meals that contain none of the given allergens.
|
||||
|
||||
- Each meal is in the format `[meal, allergens]`, where `meal` is the name of the meal, and `allergens` is an array of the allergens the meal contains. For example, `["pasta", ["wheat", "milk"]]`.
|
||||
- Allergens to avoid will be an array of strings.
|
||||
|
||||
Return safe meal names in the same order given. If no meal is safe, return an empty array.
|
||||
|
||||
# --hints--
|
||||
|
||||
`getAllergenFriendlyMeals([["pasta", ["wheat", "milk"]], ["salad", ["nuts"]]], ["milk"])` should return `["salad"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(getAllergenFriendlyMeals([["pasta", ["wheat", "milk"]], ["salad", ["nuts"]]], ["milk"]), ["salad"]);
|
||||
```
|
||||
|
||||
`getAllergenFriendlyMeals([["steak", ["soy"]], ["fried rice", []], ["fish tacos", ["fish", "wheat"]], ["chicken parmesan", ["wheat", "milk"]]], ["soy", "fish"])` should return `["fried rice", "chicken parmesan"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(getAllergenFriendlyMeals([["steak", ["soy"]], ["fried rice", []], ["fish tacos", ["fish", "wheat"]], ["chicken parmesan", ["wheat", "milk"]]], ["soy", "fish"]), ["fried rice", "chicken parmesan"]);
|
||||
```
|
||||
|
||||
`getAllergenFriendlyMeals([["oatmeal", ["nuts"]], ["pancakes", ["wheat", "milk"]], ["granola", []], ["yogurt", ["milk"]], ["eggs", ["eggs", "milk"]], ["toast", ["wheat"]]], ["eggs", "milk"])` should return `["oatmeal", "granola", "toast"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(getAllergenFriendlyMeals([["oatmeal", ["nuts"]], ["pancakes", ["wheat", "milk"]], ["granola", []], ["yogurt", ["milk"]], ["eggs", ["eggs", "milk"]], ["toast", ["wheat"]]], ["eggs", "milk"]), ["oatmeal", "granola", "toast"]);
|
||||
```
|
||||
|
||||
`getAllergenFriendlyMeals([["oatmeal", ["nuts"]], ["pancakes", ["wheat", "milk"]], ["granola", []], ["yogurt", ["milk"]], ["eggs", ["eggs", "milk"]], ["toast", ["wheat"]]], ["wheat", "nuts"])` should return `["granola", "yogurt", "eggs"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(getAllergenFriendlyMeals([["oatmeal", ["nuts"]], ["pancakes", ["wheat", "milk"]], ["granola", []], ["yogurt", ["milk"]], ["eggs", ["eggs", "milk"]], ["toast", ["wheat"]]], ["wheat", "nuts"]), ["granola", "yogurt", "eggs"]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function getAllergenFriendlyMeals(meals, allergens) {
|
||||
|
||||
return meals;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function getAllergenFriendlyMeals(meals, allergens) {
|
||||
return meals
|
||||
.filter(([name, mealAllergens]) =>
|
||||
!allergens.some(a => mealAllergens.includes(a)))
|
||||
.map(([name]) => name);
|
||||
}
|
||||
```
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
---
|
||||
id: 69cfca90e8a0a6d4d6871c54
|
||||
title: "Challenge 270: Longest Common Substring"
|
||||
challengeType: 28
|
||||
dashedName: challenge-270
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string, return the longest substring that appears more than once.
|
||||
|
||||
- The substrings can overlap.
|
||||
|
||||
# --hints--
|
||||
|
||||
`getLongestSubstring("abracadabra")` should return `"abra"`.
|
||||
|
||||
```js
|
||||
assert.equal(getLongestSubstring("abracadabra"), "abra");
|
||||
```
|
||||
|
||||
`getLongestSubstring("hello world hello")` should return `"hello"`.
|
||||
|
||||
```js
|
||||
assert.equal(getLongestSubstring("hello world hello"), "hello");
|
||||
```
|
||||
|
||||
`getLongestSubstring("mississippi")` should return `"issi"`.
|
||||
|
||||
```js
|
||||
assert.equal(getLongestSubstring("mississippi"), "issi");
|
||||
```
|
||||
|
||||
`getLongestSubstring("ha ha ha ha ha ha ha")` should return `"ha ha ha ha ha ha"`.
|
||||
|
||||
```js
|
||||
assert.equal(getLongestSubstring("ha ha ha ha ha ha ha"), "ha ha ha ha ha ha");
|
||||
```
|
||||
|
||||
`getLongestSubstring("the quick brown fox jumped over the lazy dog that the quick brown fox jumped over")` should return `"the quick brown fox jumped over"`.
|
||||
|
||||
```js
|
||||
assert.equal(getLongestSubstring("the quick brown fox jumped over the lazy dog that the quick brown fox jumped over"), "the quick brown fox jumped over");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function getLongestSubstring(str) {
|
||||
|
||||
return str;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function getLongestSubstring(str) {
|
||||
let longest = '';
|
||||
|
||||
for (let len = str.length - 1; len >= 1; len--) {
|
||||
for (let i = 0; i <= str.length - len; i++) {
|
||||
const sub = str.slice(i, i + len);
|
||||
if (str.indexOf(sub) !== str.lastIndexOf(sub)) {
|
||||
return sub;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return longest;
|
||||
}
|
||||
```
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
---
|
||||
id: 69d03e549613fbdbe21d11e0
|
||||
title: "Challenge 271: Medication Reminder"
|
||||
challengeType: 28
|
||||
dashedName: challenge-271
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given an array of medications and a string representing the current time, return the next medication you need to take and how long until you need to take it.
|
||||
|
||||
- Each medication is in the format `[name, lastTaken]`, where `name` is the name of the medication and `lastTaken` is the time it was last taken.
|
||||
- All given times will be in `"HH:MM"` (24-hour) format.
|
||||
|
||||
Use the following medication schedule:
|
||||
|
||||
| Name | Schedule |
|
||||
| - | - |
|
||||
| Deployxitrin | 08:00, 16:00 |
|
||||
| Debuggamanizole | 07:00, 13:00, 21:00 |
|
||||
| Mergeflictamine | every 4 hours |
|
||||
|
||||
Return a string in the format `"{name} in Hh Mm"`. For example, `"Debuggamanizole in 2h 0m"` or `"Deployxitrin in 1h 5m"`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`medicationReminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "07:00"], ["Mergeflictamine", "10:00"]], "11:00")` should return `"Debuggamanizole in 2h 0m"`.
|
||||
|
||||
```js
|
||||
assert.equal(medicationReminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "07:00"], ["Mergeflictamine", "10:00"]], "11:00"), "Debuggamanizole in 2h 0m");
|
||||
```
|
||||
|
||||
`medicationReminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "13:00"], ["Mergeflictamine", "14:00"]], "14:55")` should return `"Deployxitrin in 1h 5m"`.
|
||||
|
||||
```js
|
||||
assert.equal(medicationReminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "13:00"], ["Mergeflictamine", "14:00"]], "14:55"), "Deployxitrin in 1h 5m");
|
||||
```
|
||||
|
||||
`medicationReminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "13:00"], ["Mergeflictamine", "14:00"]], "17:15")` should return `"Mergeflictamine in 0h 45m"`.
|
||||
|
||||
```js
|
||||
assert.equal(medicationReminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "13:00"], ["Mergeflictamine", "14:00"]], "17:15"), "Mergeflictamine in 0h 45m");
|
||||
```
|
||||
|
||||
`medicationReminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "07:00"], ["Mergeflictamine", "09:00"]], "12:59")` should return `"Debuggamanizole in 0h 1m"`.
|
||||
|
||||
```js
|
||||
assert.equal(medicationReminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "07:00"], ["Mergeflictamine", "09:00"]], "12:59"), "Debuggamanizole in 0h 1m");
|
||||
```
|
||||
|
||||
`medicationReminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "21:00"], ["Mergeflictamine", "03:00"]], "06:55")` should return `"Debuggamanizole in 0h 5m"`.
|
||||
|
||||
```js
|
||||
assert.equal(medicationReminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "21:00"], ["Mergeflictamine", "03:00"]], "06:55"), "Debuggamanizole in 0h 5m");
|
||||
```
|
||||
|
||||
`medicationReminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "07:00"], ["Mergeflictamine", "07:30"]], "08:00")` should return `"Mergeflictamine in 3h 30m"`.
|
||||
|
||||
```js
|
||||
assert.equal(medicationReminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "07:00"], ["Mergeflictamine", "07:30"]], "08:00"), "Mergeflictamine in 3h 30m");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function medicationReminder(medications, currentTime) {
|
||||
|
||||
return medications;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function medicationReminder(medications, currentTime) {
|
||||
const schedule = {
|
||||
Deployxitrin: { type: 'fixed', times: ['08:00', '16:00'] },
|
||||
Debuggamanizole: { type: 'fixed', times: ['07:00', '13:00', '21:00'] },
|
||||
Mergeflictamine: { type: 'interval', hours: 4 }
|
||||
};
|
||||
|
||||
const toMinutes = t => {
|
||||
const [h, m] = t.split(':').map(Number);
|
||||
return h * 60 + m;
|
||||
};
|
||||
|
||||
const current = toMinutes(currentTime);
|
||||
let earliest = Infinity;
|
||||
let nextMed = '';
|
||||
|
||||
for (const [name, lastTaken] of medications) {
|
||||
const med = schedule[name];
|
||||
let nextDue;
|
||||
|
||||
if (med.type === 'fixed') {
|
||||
const futureTimes = med.times
|
||||
.map(toMinutes)
|
||||
.filter(t => t > current);
|
||||
if (futureTimes.length === 0) continue;
|
||||
nextDue = Math.min(...futureTimes);
|
||||
} else {
|
||||
nextDue = toMinutes(lastTaken) + med.hours * 60;
|
||||
}
|
||||
|
||||
const diff = nextDue - current;
|
||||
if (diff > 0 && diff < earliest) {
|
||||
earliest = diff;
|
||||
nextMed = name;
|
||||
}
|
||||
}
|
||||
|
||||
const h = Math.floor(earliest / 60);
|
||||
const m = earliest % 60;
|
||||
return `${nextMed} in ${h}h ${m}m`;
|
||||
}
|
||||
```
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
---
|
||||
id: 69e2383af7832c8032603b8e
|
||||
title: "Challenge 272: Transposed Matrix"
|
||||
challengeType: 28
|
||||
dashedName: challenge-272
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a matrix (an array of arrays), return the transposed version of it.
|
||||
|
||||
To transpose the matrix, swap the rows and columns. E.g: a value at index `[0, 1]` should move to index `[1, 0]`.
|
||||
|
||||
For example, given:
|
||||
|
||||
```json
|
||||
[
|
||||
[1, 2, 3],
|
||||
[4, 5, 6]
|
||||
]
|
||||
```
|
||||
|
||||
Return:
|
||||
|
||||
```json
|
||||
[
|
||||
[1, 4],
|
||||
[2, 5],
|
||||
[3, 6]
|
||||
]
|
||||
```
|
||||
|
||||
# --hints--
|
||||
|
||||
`transpose([[1, 2, 3], [4, 5, 6]])` should return `[[1, 4], [2, 5], [3, 6]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(transpose([[1, 2, 3], [4, 5, 6]]), [[1, 4], [2, 5], [3, 6]]);
|
||||
```
|
||||
|
||||
`transpose([[1, 2], [3, 4], [5, 6]])` should return `[[1, 3, 5], [2, 4, 6]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(transpose([[1, 2], [3, 4], [5, 6]]), [[1, 3, 5], [2, 4, 6]]);
|
||||
```
|
||||
|
||||
`transpose([[1, 2], [3, 4], [5, 6], [7, 8]])` should return `[[1, 3, 5, 7], [2, 4, 6, 8]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(transpose([[1, 2], [3, 4], [5, 6], [7, 8]]), [[1, 3, 5, 7], [2, 4, 6, 8]]);
|
||||
```
|
||||
|
||||
`transpose([["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"], ["j", "k", "l"]])` should return `[["a", "d", "g", "j"], ["b", "e", "h", "k"], ["c", "f", "i", "l"]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(transpose([["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"], ["j", "k", "l"]]), [["a", "d", "g", "j"], ["b", "e", "h", "k"], ["c", "f", "i", "l"]]);
|
||||
```
|
||||
|
||||
`transpose([[true, false, true, false], [false, true, false, true], [true, true, false, false], [false, false, true, true], [true, false, false, true]])` should return `[[true, false, true, false, true], [false, true, true, false, false], [true, false, false, true, false], [false, true, false, true, true]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(transpose([[true, false, true, false], [false, true, false, true], [true, true, false, false], [false, false, true, true], [true, false, false, true]]), [[true, false, true, false, true], [false, true, true, false, false], [true, false, false, true, false], [false, true, false, true, true]]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function transpose(matrix) {
|
||||
|
||||
return matrix;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function transpose(matrix) {
|
||||
|
||||
return matrix[0].map((_, i) => matrix.map(row => row[i]));
|
||||
}
|
||||
```
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
---
|
||||
id: 69e2383af7832c8032603b8f
|
||||
title: "Challenge 273: ISBN-13 Validator"
|
||||
challengeType: 28
|
||||
dashedName: challenge-273
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string, determine if it is a valid ISBN-13 number.
|
||||
|
||||
A valid ISBN-13:
|
||||
|
||||
- Contains only digits and hyphens
|
||||
- Has exactly 13 digits after removing hyphens
|
||||
- Passes the following check:
|
||||
1. Multiply each digit by 1 or 3, alternating (multiply the first digit by 1, the second by 3, the third by 1, and so on).
|
||||
2. The sum of the results must be divisible by 10.
|
||||
|
||||
# --hints--
|
||||
|
||||
`isValidIsbn13("9780306406157")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isValidIsbn13("9780306406157"));
|
||||
```
|
||||
|
||||
`isValidIsbn13("97803064061570")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isValidIsbn13("97803064061570"));
|
||||
```
|
||||
|
||||
`isValidIsbn13("978-0-13-595705-9")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isValidIsbn13("978-0-13-595705-9"));
|
||||
```
|
||||
|
||||
`isValidIsbn13("978-030-64061A-4")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isValidIsbn13("978-030-64061A-4"));
|
||||
```
|
||||
|
||||
`isValidIsbn13("9-7-8-0-1-3-4-7-5-7-5-9-9")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isValidIsbn13("9-7-8-0-1-3-4-7-5-7-5-9-9"));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function isValidIsbn13(str) {
|
||||
|
||||
return str;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function isValidIsbn13(str) {
|
||||
const digits = str.replace(/-/g, '');
|
||||
if (!/^\d{13}$/.test(digits)) return false;
|
||||
const sum = digits.split('').reduce((acc, d, i) => acc + d * (i % 2 === 0 ? 1 : 3), 0);
|
||||
return sum % 10 === 0;
|
||||
}
|
||||
```
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
---
|
||||
id: 69e2383af7832c8032603b90
|
||||
title: "Challenge 274: Oldest Person"
|
||||
challengeType: 28
|
||||
dashedName: challenge-274
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given an array of objects, each with a `"name"` and `"age"` property, return an array containing the name of the oldest person.
|
||||
|
||||
If multiple people share the oldest age, return all of their names in the order they appear in the input.
|
||||
|
||||
# --hints--
|
||||
|
||||
`getOldest([{ name: "Brenda", age: 40 }])` should return `["Brenda"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(getOldest([{ name: "Brenda", age: 40 }]), ["Brenda"]);
|
||||
```
|
||||
|
||||
`getOldest([{ name: "Alice", age: 30 }, { name: "Bob", age: 25 }])` should return `["Alice"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(getOldest([{ name: "Alice", age: 30 }, { name: "Bob", age: 25 }]), ["Alice"]);
|
||||
```
|
||||
|
||||
`getOldest([{ name: "Allison", age: 25 }, { name: "Bill", age: 30 }, { name: "Carol", age: 30 }])` should return `["Bill", "Carol"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(getOldest([{ name: "Allison", age: 25 }, { name: "Bill", age: 30 }, { name: "Carol", age: 30 }]), ["Bill", "Carol"]);
|
||||
```
|
||||
|
||||
`getOldest([{ name: "George", age: 50 }, { name: "Shirley", age: 42 }, { name: "Beth", age: 48 }, { name: "Holly", age: 50 }, { name: "Kevin", age: 44 }, { name: "Frank", age: 47 }, { name: "Zach", age: 50 }, { name: "Jennifer", age: 43 }])` should return `["George", "Holly", "Zach"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(getOldest([{ name: "George", age: 50 }, { name: "Shirley", age: 42 }, { name: "Beth", age: 48 }, { name: "Holly", age: 50 }, { name: "Kevin", age: 44 }, { name: "Frank", age: 47 }, { name: "Zach", age: 50 }, { name: "Jennifer", age: 43 }]), ["George", "Holly", "Zach"]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function getOldest(people) {
|
||||
|
||||
return people;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function getOldest(people) {
|
||||
const maxAge = Math.max(...people.map(p => p.age));
|
||||
return people.filter(p => p.age === maxAge).map(p => p.name);
|
||||
}
|
||||
```
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
---
|
||||
id: 69e2383af7832c8032603b91
|
||||
title: "Challenge 275: Character Frequency"
|
||||
challengeType: 28
|
||||
dashedName: challenge-275
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string, return an object (JavaScript) or dictionary (Python) mapping each character to the number of times it appears.
|
||||
|
||||
# --hints--
|
||||
|
||||
`getFrequency("test")` should return `{t: 2, e: 1, s: 1}`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(getFrequency("test"), {t: 2, e: 1, s: 1});
|
||||
```
|
||||
|
||||
`getFrequency("mississippi")` should return `{m: 1, i: 4, s: 4, p: 2}`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(getFrequency("mississippi"), {m: 1, i: 4, s: 4, p: 2});
|
||||
```
|
||||
|
||||
`getFrequency("hello world")` should return `{h: 1, e: 1, l: 3, o: 2, " ": 1, w: 1, r: 1, d: 1}`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(getFrequency("hello world"), {h: 1, e: 1, l: 3, o: 2, " ": 1, w: 1, r: 1, d: 1});
|
||||
```
|
||||
|
||||
`getFrequency("She sells seashells by the seashore.")` should return `{S: 1, h: 4, e: 7, " ": 5, s: 7, l: 4, a: 2, b: 1, y: 1, t: 1, o: 1, r: 1, ".": 1}`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(getFrequency("She sells seashells by the seashore."), {S: 1, h: 4, e: 7, " ": 5, s: 7, l: 4, a: 2, b: 1, y: 1, t: 1, o: 1, r: 1, ".": 1});
|
||||
```
|
||||
|
||||
`getFrequency("The quick brown fox jumps over the lazy dog.")` should return `{T: 1, h: 2, e: 3, " ": 8, q: 1, u: 2, i: 1, c: 1, k: 1, b: 1, r: 2, o: 4, w: 1, n: 1, f: 1, x: 1, j: 1, m: 1, p: 1, s: 1, v: 1, t: 1, l: 1, a: 1, z: 1, y: 1, d: 1, g: 1, ".": 1}`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(getFrequency("The quick brown fox jumps over the lazy dog."), {T: 1, h: 2, e: 3, " ": 8, q: 1, u: 2, i: 1, c: 1, k: 1, b: 1, r: 2, o: 4, w: 1, n: 1, f: 1, x: 1, j: 1, m: 1, p: 1, s: 1, v: 1, t: 1, l: 1, a: 1, z: 1, y: 1, d: 1, g: 1, ".": 1});
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function getFrequency(str) {
|
||||
|
||||
return str;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function getFrequency(str) {
|
||||
return str.split('').reduce((acc, char) => {
|
||||
acc[char] = (acc[char] || 0) + 1;
|
||||
return acc;
|
||||
}, {});
|
||||
}
|
||||
```
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
---
|
||||
id: 69e2383af7832c8032603b92
|
||||
title: "Challenge 276: Offending Element"
|
||||
challengeType: 28
|
||||
dashedName: challenge-276
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given an array of integers that is sorted in ascending order except for one out-of-place element, return the index of that element.
|
||||
|
||||
- If more than one element could be considered out of place, return the index of the first one.
|
||||
|
||||
# --hints--
|
||||
|
||||
`findOffender([1, 6, 2, 3, 4, 5])` should return `1`.
|
||||
|
||||
```js
|
||||
assert.equal(findOffender([1, 6, 2, 3, 4, 5]), 1);
|
||||
```
|
||||
|
||||
`findOffender([1, 2, 3, 5, 4, 5])` should return `3`.
|
||||
|
||||
```js
|
||||
assert.equal(findOffender([1, 2, 3, 5, 4, 5]), 3);
|
||||
```
|
||||
|
||||
`findOffender([2, 1])` should return `0`.
|
||||
|
||||
```js
|
||||
assert.equal(findOffender([2, 1]), 0);
|
||||
```
|
||||
|
||||
`findOffender([2, 4, 1, 6, 8])` should return `2`.
|
||||
|
||||
```js
|
||||
assert.equal(findOffender([2, 4, 1, 6, 8]), 2);
|
||||
```
|
||||
|
||||
`findOffender([5, 18, 24, 33, 40, 55, 15, 68, 84, 91])` should return `6`.
|
||||
|
||||
```js
|
||||
assert.equal(findOffender([5, 18, 24, 33, 40, 55, 15, 68, 84, 91]), 6);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function findOffender(arr) {
|
||||
|
||||
return arr;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function findOffender(arr) {
|
||||
for (let i = 0; i < arr.length; i++) {
|
||||
const without = [...arr.slice(0, i), ...arr.slice(i + 1)];
|
||||
if (without.every((n, j) => j === 0 || without[j - 1] <= n)) return i;
|
||||
}
|
||||
}
|
||||
```
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
---
|
||||
id: 69e2383af7832c8032603b93
|
||||
title: "Challenge 277: Mirror Image"
|
||||
challengeType: 28
|
||||
dashedName: challenge-277
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given two strings, determine if the second string is a mirror image of the first.
|
||||
|
||||
A mirror image is formed by reversing the string and replacing each character with its mirror equivalent.
|
||||
|
||||
- Symmetric characters look like themselves in a mirror:
|
||||
|
||||
`W`, `T`, `Y`, `U`, `I`, `O`, `H`, `A`, `X`, `V`, `M`, `w`, `o`, `x`, `v`, `0`, `8`, `=`, `+`, `:`, `|`, `-`, `_`, `*`, `^`, `!`, `.`, and the space (` `).
|
||||
|
||||
- Mirrored pairs swap with each other in a mirror:
|
||||
|
||||
| Character | Swaps with |
|
||||
| - | - |
|
||||
| `[` | `]` |
|
||||
| `{` | `}` |
|
||||
| `<` | `>` |
|
||||
| `b` | `d` |
|
||||
| `p` | `q` |
|
||||
| `(` | `)` |
|
||||
|
||||
If either string includes a character not in the lists above, it doesn't have mirror image that can be created from the characters.
|
||||
|
||||
For example, the mirrored image of `"[HOW]"` is `"[WOH]"`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`isMirrorImage("[HOW]", "[WOH]")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isMirrorImage("[HOW]", "[WOH]"));
|
||||
```
|
||||
|
||||
`isMirrorImage("MOM", "MOM")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isMirrorImage("MOM", "MOM"));
|
||||
```
|
||||
|
||||
`isMirrorImage("vow", "wov")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isMirrorImage("vow", "wov"));
|
||||
```
|
||||
|
||||
`isMirrorImage("TIM", "TIM")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isMirrorImage("TIM", "TIM"));
|
||||
```
|
||||
|
||||
`isMirrorImage("{WOW}", "}WOW{")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isMirrorImage("{WOW}", "}WOW{"));
|
||||
```
|
||||
|
||||
`isMirrorImage("XXVII", "IIV%X")` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(isMirrorImage("XXVII", "IIV%X"));
|
||||
```
|
||||
|
||||
`isMirrorImage("><(((*>", "<*)))><")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isMirrorImage("><(((*>", "<*)))><"));
|
||||
```
|
||||
|
||||
`isMirrorImage("WTYUIOHAXVMwoxv08=+:|-_*^!.[]{}<>bdpq()", "()pqbd<>{}[].!^*_-|:+=80vxowMVXAHOIUYTW")` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(isMirrorImage("WTYUIOHAXVMwoxv08=+:|-_*^!.[]{}<>bdpq()", "()pqbd<>{}[].!^*_-|:+=80vxowMVXAHOIUYTW"));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function isMirrorImage(str1, str2) {
|
||||
|
||||
return str1;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function isMirrorImage(str1, str2) {
|
||||
const symmetric = new Set('WTYUIOHA XVMwoxv08=+:|-_*^!.');
|
||||
const pairs = { '[': ']', ']': '[', '{': '}', '}': '{', '<': '>', '>': '<', 'b': 'd', 'd': 'b', 'p': 'q', 'q': 'p', '(': ')', ')': '(' };
|
||||
|
||||
const mirrored = str1.split('').reverse().map(c => {
|
||||
if (symmetric.has(c)) return c;
|
||||
if (pairs[c]) return pairs[c];
|
||||
return null;
|
||||
});
|
||||
|
||||
if (mirrored.includes(null)) return false;
|
||||
return mirrored.join('') === str2;
|
||||
}
|
||||
```
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
---
|
||||
id: 69e2383af7832c8032603b94
|
||||
title: "Challenge 278: Coffee Order Parser"
|
||||
challengeType: 28
|
||||
dashedName: challenge-278
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string for a coffee order, identify any menu items and return a formatted order.
|
||||
|
||||
Use the following menu items and prices:
|
||||
|
||||
| Item | Price |
|
||||
| - | - |
|
||||
| `"cold brew"` | $4.50 |
|
||||
| `"oat latte"` | $5.00 |
|
||||
| `"cappuccino"` | $4.75 |
|
||||
| `"espresso"` | $3.00 |
|
||||
| `"vanilla syrup"` | $0.75 |
|
||||
| `"caramel drizzle"` | $0.60 |
|
||||
| `"extra shot"` | $0.50 |
|
||||
| `"oat milk"` | $0.75 |
|
||||
| `"cream"` | $0.75 |
|
||||
|
||||
Return a string with the matched items joined by `" + "`, followed by a colon and space (`": "`), and the total price.
|
||||
|
||||
For example, given `"I'd like an oat latte with vanilla syrup and an extra shot please."`, return `"oat latte + vanilla syrup + extra shot: $6.25"`
|
||||
|
||||
Items should appear in the order they appear in the menu and the total price should always have two decimal places.
|
||||
|
||||
# --hints--
|
||||
|
||||
`formatCoffeeOrder("I'd like an oat latte with vanilla syrup and an extra shot please.")` should return `"oat latte + vanilla syrup + extra shot: $6.25"`.
|
||||
|
||||
```js
|
||||
assert.equal(formatCoffeeOrder("I'd like an oat latte with vanilla syrup and an extra shot please."), "oat latte + vanilla syrup + extra shot: $6.25");
|
||||
```
|
||||
|
||||
`formatCoffeeOrder("Give me a cappuccino with caramel drizzle, vanilla syrup, and some oat milk.")` should return `"cappuccino + vanilla syrup + caramel drizzle + oat milk: $6.85"`.
|
||||
|
||||
```js
|
||||
assert.equal(formatCoffeeOrder("Give me a cappuccino with caramel drizzle, vanilla syrup, and some oat milk."), "cappuccino + vanilla syrup + caramel drizzle + oat milk: $6.85");
|
||||
```
|
||||
|
||||
`formatCoffeeOrder("Can I get a cold brew with some cream and an extra shot.")` should return `"cold brew + extra shot + cream: $5.75"`.
|
||||
|
||||
```js
|
||||
assert.equal(formatCoffeeOrder("Can I get a cold brew with some cream and an extra shot."), "cold brew + extra shot + cream: $5.75");
|
||||
```
|
||||
|
||||
`formatCoffeeOrder("Just an espresso please.")` should return `"espresso: $3.00"`.
|
||||
|
||||
```js
|
||||
assert.equal(formatCoffeeOrder("Just an espresso please."), "espresso: $3.00");
|
||||
```
|
||||
|
||||
`formatCoffeeOrder("I'll take an oat latte with cream and an extra shot, and some vanilla syrup and caramel drizzle.")` should return `"oat latte + vanilla syrup + caramel drizzle + extra shot + cream: $7.60"`.
|
||||
|
||||
```js
|
||||
assert.equal(formatCoffeeOrder("I'll take an oat latte with cream and an extra shot, and some vanilla syrup and caramel drizzle."), "oat latte + vanilla syrup + caramel drizzle + extra shot + cream: $7.60");
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function formatCoffeeOrder(order) {
|
||||
|
||||
return order;
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function formatCoffeeOrder(order) {
|
||||
const menu = [
|
||||
{ name: "cold brew", price: 4.50 },
|
||||
{ name: "oat latte", price: 5.00 },
|
||||
{ name: "cappuccino", price: 4.75 },
|
||||
{ name: "espresso", price: 3.00 },
|
||||
{ name: "vanilla syrup", price: 0.75 },
|
||||
{ name: "caramel drizzle", price: 0.60 },
|
||||
{ name: "extra shot", price: 0.50 },
|
||||
{ name: "oat milk", price: 0.75 },
|
||||
{ name: "cream", price: 0.75 },
|
||||
];
|
||||
|
||||
const found = menu.filter(item => order.toLowerCase().includes(item.name));
|
||||
const total = found.reduce((sum, item) => sum + item.price, 0);
|
||||
return `${found.map(item => item.name).join(" + ")}: $${total.toFixed(2)}`;
|
||||
}
|
||||
```
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
---
|
||||
id: 69cfca90e8a0a6d4d6871c4e
|
||||
title: "Challenge 264: Anagram Groups"
|
||||
challengeType: 29
|
||||
dashedName: challenge-264
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given an array of words, return a 2d array of the words grouped into anagrams.
|
||||
|
||||
- Words are anagrams if they contain the same letters in any order.
|
||||
- Each word belongs to exactly one group.
|
||||
- Return order doesn't matter.
|
||||
|
||||
For example, given `["listen", "silent", "hello", "enlist", "world"]`, return `[["listen", "silent", "enlist"], ["hello"], ["world"]]`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`group_anagrams(["listen", "silent", "hello", "enlist", "world"])` should return `[["listen", "silent", "enlist"], ["hello"], ["world"]]`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
groups = group_anagrams(["listen", "silent", "hello", "enlist", "world"])
|
||||
sorted_groups = sorted([sorted(g) for g in groups], key=lambda g: g[0])
|
||||
TestCase().assertEqual(sorted_groups, [["enlist", "listen", "silent"], ["hello"], ["world"]])`)
|
||||
}})
|
||||
```
|
||||
|
||||
`group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"])` should return `[["ate", "eat", "tea"], ["bat"], ["nat", "tan"]]`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
groups = group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"])
|
||||
sorted_groups = sorted([sorted(g) for g in groups], key=lambda g: g[0])
|
||||
TestCase().assertEqual(sorted_groups, [["ate", "eat", "tea"], ["bat"], ["nat", "tan"]])`)
|
||||
}})
|
||||
```
|
||||
|
||||
`group_anagrams(["care", "race", "acre", "pots", "stop", "tops", "opts", "post", "spot", "evil", "vile", "live", "veil"])` should return `[["acre", "care", "race"], ["evil", "live", "veil", "vile"], ["opts", "post", "pots", "spot", "stop", "tops"]]`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
groups = group_anagrams(["care", "race", "acre", "pots", "stop", "tops", "opts", "post", "spot", "evil", "vile", "live", "veil"])
|
||||
sorted_groups = sorted([sorted(g) for g in groups], key=lambda g: g[0])
|
||||
TestCase().assertEqual(sorted_groups, [["acre", "care", "race"], ["evil", "live", "veil", "vile"], ["opts", "post", "pots", "spot", "stop", "tops"]])`)
|
||||
}})
|
||||
```
|
||||
|
||||
`group_anagrams(["algorithms", "logarithms", "education", "cautioned", "auctioned", "triangle", "integral", "alerting", "relating"])` should return `[["alerting", "integral", "relating", "triangle"], ["algorithms", "logarithms"], ["auctioned", "cautioned", "education"]]`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
groups = group_anagrams(["algorithms", "logarithms", "education", "cautioned", "auctioned", "triangle", "integral", "alerting", "relating"])
|
||||
sorted_groups = sorted([sorted(g) for g in groups], key=lambda g: g[0])
|
||||
TestCase().assertEqual(sorted_groups, [["alerting", "integral", "relating", "triangle"], ["algorithms", "logarithms"], ["auctioned", "cautioned", "education"]])`)
|
||||
}})
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```py
|
||||
def group_anagrams(words):
|
||||
|
||||
return words
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```py
|
||||
def group_anagrams(words):
|
||||
groups = {}
|
||||
for word in words:
|
||||
key = ''.join(sorted(word))
|
||||
if key not in groups:
|
||||
groups[key] = []
|
||||
groups[key].append(word)
|
||||
return list(groups.values())
|
||||
```
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
---
|
||||
id: 69cfca90e8a0a6d4d6871c4f
|
||||
title: "Challenge 265: Deepest Brackets"
|
||||
challengeType: 29
|
||||
dashedName: challenge-265
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string containing balanced brackets, return the content of the deepest nested brackets.
|
||||
|
||||
- Brackets can be any of the three types: `()`, `[]`, and `{}`.
|
||||
- The input will always have a single deepest group.
|
||||
|
||||
For example, given `"(hello (world))"`, return `"world"`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`get_deepest_brackets("(hello (world))")` should return `"world"`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(get_deepest_brackets("(hello (world))"), "world")`)
|
||||
}})
|
||||
```
|
||||
|
||||
`get_deepest_brackets("[outer [inner] outer]")` should return `"inner"`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(get_deepest_brackets("[outer [inner] outer]"), "inner")`)
|
||||
}})
|
||||
```
|
||||
|
||||
`get_deepest_brackets("{a{b}c{d{e}f}g}")` should return `"e"`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(get_deepest_brackets("{a{b}c{d{e}f}g}"), "e")`)
|
||||
}})
|
||||
```
|
||||
|
||||
`get_deepest_brackets("[the {quick (brown [fox] jumped) over (the) lazy} dog]")` should return `"fox"`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(get_deepest_brackets("[the {quick (brown [fox] jumped) over (the) lazy} dog]"), "fox")`)
|
||||
}})
|
||||
```
|
||||
|
||||
`get_deepest_brackets("f[(r)e{e}C{o[(d){e(C)}a]m}]p")` should return `"C"`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(get_deepest_brackets("f[(r)e{e}C{o[(d){e(C)}a]m}]p"), "C")`)
|
||||
}})
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```py
|
||||
def get_deepest_brackets(s):
|
||||
|
||||
return s
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```py
|
||||
def get_deepest_brackets(s):
|
||||
max_depth = 0
|
||||
depth = 0
|
||||
content = ''
|
||||
start = 0
|
||||
|
||||
for i, ch in enumerate(s):
|
||||
if ch in '([{':
|
||||
depth += 1
|
||||
if depth > max_depth:
|
||||
max_depth = depth
|
||||
start = i + 1
|
||||
elif ch in ')]}':
|
||||
if depth == max_depth:
|
||||
content = s[start:i]
|
||||
depth -= 1
|
||||
|
||||
return content
|
||||
```
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
---
|
||||
id: 69cfca90e8a0a6d4d6871c50
|
||||
title: "Challenge 266: Good Day"
|
||||
challengeType: 29
|
||||
dashedName: challenge-266
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a time string in `"HH:MM"` format (24-hour clock), return:
|
||||
|
||||
- `"Good morning"` for times `05:00` to `11:59`
|
||||
- `"Good afternoon"` for times `12:00` to `17:59`
|
||||
- `"Good evening"` for times `18:00` to `21:59`
|
||||
- `"Good night"` for times `22:00` to `04:59`
|
||||
|
||||
# --hints--
|
||||
|
||||
`get_greeting("06:30")` should return `"Good morning"`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(get_greeting("06:30"), "Good morning")`)
|
||||
}})
|
||||
```
|
||||
|
||||
`get_greeting("12:00")` should return `"Good afternoon"`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(get_greeting("12:00"), "Good afternoon")`)
|
||||
}})
|
||||
```
|
||||
|
||||
`get_greeting("21:59")` should return `"Good evening"`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(get_greeting("21:59"), "Good evening")`)
|
||||
}})
|
||||
```
|
||||
|
||||
`get_greeting("00:01")` should return `"Good night"`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(get_greeting("00:01"), "Good night")`)
|
||||
}})
|
||||
```
|
||||
|
||||
`get_greeting("11:30")` should return `"Good morning"`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(get_greeting("11:30"), "Good morning")`)
|
||||
}})
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```py
|
||||
def get_greeting(s):
|
||||
|
||||
return s
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```py
|
||||
def get_greeting(s):
|
||||
hours, minutes = map(int, s.split(':'))
|
||||
total = hours * 60 + minutes
|
||||
|
||||
if 300 <= total < 720:
|
||||
return 'Good morning'
|
||||
if 720 <= total < 1080:
|
||||
return 'Good afternoon'
|
||||
if 1080 <= total < 1320:
|
||||
return 'Good evening'
|
||||
return 'Good night'
|
||||
```
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
---
|
||||
id: 69cfca90e8a0a6d4d6871c51
|
||||
title: "Challenge 267: Parsec Converter"
|
||||
challengeType: 29
|
||||
dashedName: challenge-267
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In a distant galaxy, parsecs are used to measure both time and distance. Given an integer number of parsecs, return its equivalent in time or distance.
|
||||
|
||||
- If the given integer is odd, it represents time. If it's even, it represents distance.
|
||||
|
||||
Use these conversion rates:
|
||||
|
||||
| Parsecs | Time/Distance |
|
||||
| - | - |
|
||||
| 1 | 2 hours |
|
||||
| 2 | 6 light years |
|
||||
|
||||
Return the converted value as an integer.
|
||||
|
||||
# --hints--
|
||||
|
||||
`convert_parsecs(1)` should return `2`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(convert_parsecs(1), 2)`)
|
||||
}})
|
||||
```
|
||||
|
||||
`convert_parsecs(2)` should return `6`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(convert_parsecs(2), 6)`)
|
||||
}})
|
||||
```
|
||||
|
||||
`convert_parsecs(31)` should return `62`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(convert_parsecs(31), 62)`)
|
||||
}})
|
||||
```
|
||||
|
||||
`convert_parsecs(88)` should return `264`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(convert_parsecs(88), 264)`)
|
||||
}})
|
||||
```
|
||||
|
||||
`convert_parsecs(17)` should return `34`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(convert_parsecs(17), 34)`)
|
||||
}})
|
||||
```
|
||||
|
||||
`convert_parsecs(14)` should return `42`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(convert_parsecs(14), 42)`)
|
||||
}})
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```py
|
||||
def convert_parsecs(parsecs):
|
||||
|
||||
return parsecs
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```py
|
||||
def convert_parsecs(parsecs):
|
||||
if parsecs % 2 != 0:
|
||||
return parsecs * 2
|
||||
else:
|
||||
return parsecs * 3
|
||||
```
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
---
|
||||
id: 69cfca90e8a0a6d4d6871c52
|
||||
title: "Challenge 268: Narcissistic Number"
|
||||
challengeType: 29
|
||||
dashedName: challenge-268
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a positive integer, determine whether it is a narcissistic number.
|
||||
|
||||
- A number is narcissistic if the sum of each of its digits raised to the power of the total number of digits equals the number itself.
|
||||
|
||||
For example, 153 has 3 digits, and 1<sup>3</sup> + 5<sup>3</sup> + 3<sup>3</sup> = 153, so it is narcissistic.
|
||||
|
||||
# --hints--
|
||||
|
||||
`is_narcissistic(153)` should return `True`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertIs(is_narcissistic(153), True)`)
|
||||
}})
|
||||
```
|
||||
|
||||
`is_narcissistic(154)` should return `False`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertIs(is_narcissistic(154), False)`)
|
||||
}})
|
||||
```
|
||||
|
||||
`is_narcissistic(371)` should return `True`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertIs(is_narcissistic(371), True)`)
|
||||
}})
|
||||
```
|
||||
|
||||
`is_narcissistic(512)` should return `False`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertIs(is_narcissistic(512), False)`)
|
||||
}})
|
||||
```
|
||||
|
||||
`is_narcissistic(9)` should return `True`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertIs(is_narcissistic(9), True)`)
|
||||
}})
|
||||
```
|
||||
|
||||
`is_narcissistic(11)` should return `False`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertIs(is_narcissistic(11), False)`)
|
||||
}})
|
||||
```
|
||||
|
||||
`is_narcissistic(9474)` should return `True`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertIs(is_narcissistic(9474), True)`)
|
||||
}})
|
||||
```
|
||||
|
||||
`is_narcissistic(6549)` should return `False`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertIs(is_narcissistic(6549), False)`)
|
||||
}})
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```py
|
||||
def is_narcissistic(n):
|
||||
|
||||
return n
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```py
|
||||
def is_narcissistic(n):
|
||||
digits = str(n)
|
||||
power = len(digits)
|
||||
return sum(int(d) ** power for d in digits) == n
|
||||
```
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
---
|
||||
id: 69cfca90e8a0a6d4d6871c53
|
||||
title: "Challenge 269: Allergen Friendly Meals"
|
||||
challengeType: 29
|
||||
dashedName: challenge-269
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given an array of meals and an array of allergens to avoid, return the names of all the meals that contain none of the given allergens.
|
||||
|
||||
- Each meal is in the format `[meal, allergens]`, where `meal` is the name of the meal, and `allergens` is an array of the allergens the meal contains. For example, `["pasta", ["wheat", "milk"]]`.
|
||||
- Allergens to avoid will be an array of strings.
|
||||
|
||||
Return safe meal names in the same order given. If no meal is safe, return an empty array.
|
||||
|
||||
# --hints--
|
||||
|
||||
`get_allergen_friendly_meals([["pasta", ["wheat", "milk"]], ["salad", ["nuts"]]], ["milk"])` should return `["salad"]`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(get_allergen_friendly_meals([["pasta", ["wheat", "milk"]], ["salad", ["nuts"]]], ["milk"]), ["salad"])`)
|
||||
}})
|
||||
```
|
||||
|
||||
`get_allergen_friendly_meals([["steak", ["soy"]], ["fried rice", []], ["fish tacos", ["fish", "wheat"]], ["chicken parmesan", ["wheat", "milk"]]], ["soy", "fish"])` should return `["fried rice", "chicken parmesan"]`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(get_allergen_friendly_meals([["steak", ["soy"]], ["fried rice", []], ["fish tacos", ["fish", "wheat"]], ["chicken parmesan", ["wheat", "milk"]]], ["soy", "fish"]), ["fried rice", "chicken parmesan"])`)
|
||||
}})
|
||||
```
|
||||
|
||||
`get_allergen_friendly_meals([["oatmeal", ["nuts"]], ["pancakes", ["wheat", "milk"]], ["granola", []], ["yogurt", ["milk"]], ["eggs", ["eggs", "milk"]], ["toast", ["wheat"]]], ["eggs", "milk"])` should return `["oatmeal", "granola", "toast"]`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(get_allergen_friendly_meals([["oatmeal", ["nuts"]], ["pancakes", ["wheat", "milk"]], ["granola", []], ["yogurt", ["milk"]], ["eggs", ["eggs", "milk"]], ["toast", ["wheat"]]], ["eggs", "milk"]), ["oatmeal", "granola", "toast"])`)
|
||||
}})
|
||||
```
|
||||
|
||||
`get_allergen_friendly_meals([["oatmeal", ["nuts"]], ["pancakes", ["wheat", "milk"]], ["granola", []], ["yogurt", ["milk"]], ["eggs", ["eggs", "milk"]], ["toast", ["wheat"]]], ["wheat", "nuts"])` should return `["granola", "yogurt", "eggs"]`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(get_allergen_friendly_meals([["oatmeal", ["nuts"]], ["pancakes", ["wheat", "milk"]], ["granola", []], ["yogurt", ["milk"]], ["eggs", ["eggs", "milk"]], ["toast", ["wheat"]]], ["wheat", "nuts"]), ["granola", "yogurt", "eggs"])`)
|
||||
}})
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```py
|
||||
def get_allergen_friendly_meals(meals, allergens):
|
||||
|
||||
return meals
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```py
|
||||
def get_allergen_friendly_meals(meals, allergens):
|
||||
return [name for name, meal_allergens in meals if not any(a in meal_allergens for a in allergens)]
|
||||
```
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
---
|
||||
id: 69cfca90e8a0a6d4d6871c54
|
||||
title: "Challenge 270: Longest Common Substring"
|
||||
challengeType: 29
|
||||
dashedName: challenge-270
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string, return the longest substring that appears more than once.
|
||||
|
||||
- The substrings can overlap.
|
||||
|
||||
# --hints--
|
||||
|
||||
`get_longest_substring("abracadabra")` should return `"abra"`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(get_longest_substring("abracadabra"), "abra")`)
|
||||
}})
|
||||
```
|
||||
|
||||
`get_longest_substring("hello world hello")` should return `"hello"`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(get_longest_substring("hello world hello"), "hello")`)
|
||||
}})
|
||||
```
|
||||
|
||||
`get_longest_substring("mississippi")` should return `"issi"`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(get_longest_substring("mississippi"), "issi")`)
|
||||
}})
|
||||
```
|
||||
|
||||
`get_longest_substring("ha ha ha ha ha ha ha")` should return `"ha ha ha ha ha ha"`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(get_longest_substring("ha ha ha ha ha ha ha"), "ha ha ha ha ha ha")`)
|
||||
}})
|
||||
```
|
||||
|
||||
`get_longest_substring("the quick brown fox jumped over the lazy dog that the quick brown fox jumped over")` should return `"the quick brown fox jumped over"`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(get_longest_substring("the quick brown fox jumped over the lazy dog that the quick brown fox jumped over"), "the quick brown fox jumped over")`)
|
||||
}})
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```py
|
||||
def get_longest_substring(s):
|
||||
|
||||
return s
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```py
|
||||
def get_longest_substring(s):
|
||||
longest = ''
|
||||
|
||||
for length in range(len(s) - 1, 0, -1):
|
||||
for i in range(len(s) - length + 1):
|
||||
sub = s[i:i + length]
|
||||
if s.find(sub) != s.rfind(sub):
|
||||
return sub
|
||||
|
||||
return longest
|
||||
```
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
---
|
||||
id: 69d03e549613fbdbe21d11e0
|
||||
title: "Challenge 271: Medication Reminder"
|
||||
challengeType: 29
|
||||
dashedName: challenge-271
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given an array of medications and a string representing the current time, return the next medication you need to take and how long until you need to take it.
|
||||
|
||||
- Each medication is in the format `[name, lastTaken]`, where `name` is the name of the medication and `lastTaken` is the time it was last taken.
|
||||
- All given times will be in `"HH:MM"` (24-hour) format.
|
||||
|
||||
Use the following medication schedule:
|
||||
|
||||
| Name | Schedule |
|
||||
| - | - |
|
||||
| Deployxitrin | 08:00, 16:00 |
|
||||
| Debuggamanizole | 07:00, 13:00, 21:00 |
|
||||
| Mergeflictamine | every 4 hours |
|
||||
|
||||
Return a string in the format `"{name} in Hh Mm"`. For example, `"Debuggamanizole in 2h 0m"` or `"Deployxitrin in 1h 5m"`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`medication_reminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "07:00"], ["Mergeflictamine", "10:00"]], "11:00")` should return `"Debuggamanizole in 2h 0m"`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(medication_reminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "07:00"], ["Mergeflictamine", "10:00"]], "11:00"), "Debuggamanizole in 2h 0m")`)
|
||||
}})
|
||||
```
|
||||
|
||||
`medication_reminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "13:00"], ["Mergeflictamine", "14:00"]], "14:55")` should return `"Deployxitrin in 1h 5m"`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(medication_reminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "13:00"], ["Mergeflictamine", "14:00"]], "14:55"), "Deployxitrin in 1h 5m")`)
|
||||
}})
|
||||
```
|
||||
|
||||
`medication_reminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "13:00"], ["Mergeflictamine", "14:00"]], "17:15")` should return `"Mergeflictamine in 0h 45m"`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(medication_reminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "13:00"], ["Mergeflictamine", "14:00"]], "17:15"), "Mergeflictamine in 0h 45m")`)
|
||||
}})
|
||||
```
|
||||
|
||||
`medication_reminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "07:00"], ["Mergeflictamine", "09:00"]], "12:59")` should return `"Debuggamanizole in 0h 1m"`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(medication_reminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "07:00"], ["Mergeflictamine", "09:00"]], "12:59"), "Debuggamanizole in 0h 1m")`)
|
||||
}})
|
||||
```
|
||||
|
||||
`medication_reminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "21:00"], ["Mergeflictamine", "03:00"]], "06:55")` should return `"Debuggamanizole in 0h 5m"`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(medication_reminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "21:00"], ["Mergeflictamine", "03:00"]], "06:55"), "Debuggamanizole in 0h 5m")`)
|
||||
}})
|
||||
```
|
||||
|
||||
`medication_reminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "07:00"], ["Mergeflictamine", "07:30"]], "08:00")` should return `"Mergeflictamine in 3h 30m"`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(medication_reminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "07:00"], ["Mergeflictamine", "07:30"]], "08:00"), "Mergeflictamine in 3h 30m")`)
|
||||
}})
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```py
|
||||
def medication_reminder(medications, current_time):
|
||||
|
||||
return medications
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```py
|
||||
def medication_reminder(medications, current_time):
|
||||
schedule = {
|
||||
'Deployxitrin': {'type': 'fixed', 'times': ['08:00', '16:00']},
|
||||
'Debuggamanizole': {'type': 'fixed', 'times': ['07:00', '13:00', '21:00']},
|
||||
'Mergeflictamine': {'type': 'interval', 'hours': 4},
|
||||
}
|
||||
|
||||
def to_minutes(t):
|
||||
h, m = map(int, t.split(':'))
|
||||
return h * 60 + m
|
||||
|
||||
current = to_minutes(current_time)
|
||||
earliest = float('inf')
|
||||
next_med = ''
|
||||
|
||||
for name, last_taken in medications:
|
||||
med = schedule[name]
|
||||
if med['type'] == 'fixed':
|
||||
future_times = [to_minutes(t) for t in med['times'] if to_minutes(t) > current]
|
||||
if not future_times:
|
||||
continue
|
||||
next_due = min(future_times)
|
||||
else:
|
||||
next_due = to_minutes(last_taken) + med['hours'] * 60
|
||||
|
||||
diff = next_due - current
|
||||
if 0 < diff < earliest:
|
||||
earliest = diff
|
||||
next_med = name
|
||||
|
||||
h = earliest // 60
|
||||
m = earliest % 60
|
||||
return f"{next_med} in {h}h {m}m"
|
||||
```
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
---
|
||||
id: 69e2383af7832c8032603b8e
|
||||
title: "Challenge 272: Transposed Matrix"
|
||||
challengeType: 29
|
||||
dashedName: challenge-272
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a matrix (an array of arrays), return the transposed version of it.
|
||||
|
||||
To transpose the matrix, swap the rows and columns. E.g: a value at index `[0, 1]` should move to index `[1, 0]`.
|
||||
|
||||
For example, given:
|
||||
|
||||
```json
|
||||
[
|
||||
[1, 2, 3],
|
||||
[4, 5, 6]
|
||||
]
|
||||
```
|
||||
|
||||
Return:
|
||||
|
||||
```json
|
||||
[
|
||||
[1, 4],
|
||||
[2, 5],
|
||||
[3, 6]
|
||||
]
|
||||
```
|
||||
|
||||
# --hints--
|
||||
|
||||
`transpose([[1, 2, 3], [4, 5, 6]])` should return `[[1, 4], [2, 5], [3, 6]]`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(transpose([[1, 2, 3], [4, 5, 6]]), [[1, 4], [2, 5], [3, 6]])`)
|
||||
}})
|
||||
```
|
||||
|
||||
`transpose([[1, 2], [3, 4], [5, 6]])` should return `[[1, 3, 5], [2, 4, 6]]`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(transpose([[1, 2], [3, 4], [5, 6]]), [[1, 3, 5], [2, 4, 6]])`)
|
||||
}})
|
||||
```
|
||||
|
||||
`transpose([[1, 2], [3, 4], [5, 6], [7, 8]])` should return `[[1, 3, 5, 7], [2, 4, 6, 8]]`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(transpose([[1, 2], [3, 4], [5, 6], [7, 8]]), [[1, 3, 5, 7], [2, 4, 6, 8]])`)
|
||||
}})
|
||||
```
|
||||
|
||||
`transpose([["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"], ["j", "k", "l"]])` should return `[["a", "d", "g", "j"], ["b", "e", "h", "k"], ["c", "f", "i", "l"]]`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(transpose([["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"], ["j", "k", "l"]]), [["a", "d", "g", "j"], ["b", "e", "h", "k"], ["c", "f", "i", "l"]])`)
|
||||
}})
|
||||
```
|
||||
|
||||
`transpose([[True, False, True, False], [False, True, False, True], [True, True, False, False], [False, False, True, True], [True, False, False, True]])` should return `[[True, False, True, False, True], [False, True, True, False, False], [True, False, False, True, False], [False, True, False, True, True]]`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(transpose([[True, False, True, False], [False, True, False, True], [True, True, False, False], [False, False, True, True], [True, False, False, True]]), [[True, False, True, False, True], [False, True, True, False, False], [True, False, False, True, False], [False, True, False, True, True]])`)
|
||||
}})
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```py
|
||||
def transpose(matrix):
|
||||
|
||||
return matrix
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```py
|
||||
def transpose(matrix):
|
||||
return [[row[i] for row in matrix] for i in range(len(matrix[0]))]
|
||||
```
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
---
|
||||
id: 69e2383af7832c8032603b8f
|
||||
title: "Challenge 273: ISBN-13 Validator"
|
||||
challengeType: 29
|
||||
dashedName: challenge-273
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string, determine if it is a valid ISBN-13 number.
|
||||
|
||||
A valid ISBN-13:
|
||||
|
||||
- Contains only digits and hyphens
|
||||
- Has exactly 13 digits after removing hyphens
|
||||
- Passes the following check:
|
||||
1. Multiply each digit by 1 or 3, alternating (multiply the first digit by 1, the second by 3, the third by 1, and so on).
|
||||
2. The sum of the results must be divisible by 10.
|
||||
|
||||
# --hints--
|
||||
|
||||
`is_valid_isbn_13("9780306406157")` should return `True`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertIs(is_valid_isbn_13("9780306406157"), True)`)
|
||||
}})
|
||||
```
|
||||
|
||||
`is_valid_isbn_13("97803064061570")` should return `False`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertIs(is_valid_isbn_13("97803064061570"), False)`)
|
||||
}})
|
||||
```
|
||||
|
||||
`is_valid_isbn_13("978-0-13-595705-9")` should return `True`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertIs(is_valid_isbn_13("978-0-13-595705-9"), True)`)
|
||||
}})
|
||||
```
|
||||
|
||||
`is_valid_isbn_13("978-030-64061A-4")` should return `False`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertIs(is_valid_isbn_13("978-030-64061A-4"), False)`)
|
||||
}})
|
||||
```
|
||||
|
||||
`is_valid_isbn_13("9-7-8-0-1-3-4-7-5-7-5-9-9")` should return `True`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertIs(is_valid_isbn_13("9-7-8-0-1-3-4-7-5-7-5-9-9"), True)`)
|
||||
}})
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```py
|
||||
def is_valid_isbn_13(s):
|
||||
|
||||
return s
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```py
|
||||
def is_valid_isbn_13(s):
|
||||
digits = s.replace("-", "")
|
||||
if not digits.isdigit() or len(digits) != 13:
|
||||
return False
|
||||
total = sum(int(d) * (1 if i % 2 == 0 else 3) for i, d in enumerate(digits))
|
||||
return total % 10 == 0
|
||||
```
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
---
|
||||
id: 69e2383af7832c8032603b90
|
||||
title: "Challenge 274: Oldest Person"
|
||||
challengeType: 29
|
||||
dashedName: challenge-274
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given an array of objects, each with a `"name"` and `"age"` property, return an array containing the name of the oldest person.
|
||||
|
||||
If multiple people share the oldest age, return all of their names in the order they appear in the input.
|
||||
|
||||
# --hints--
|
||||
|
||||
`get_oldest([{ "name": "Brenda", "age": 40 }])` should return `["Brenda"]`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(get_oldest([{"name": "Brenda", "age": 40}]), ["Brenda"])`)
|
||||
}})
|
||||
```
|
||||
|
||||
`get_oldest([{ "name": "Alice", "age": 30 }, { "name": "Bob", "age": 25 }])` should return `["Alice"]`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(get_oldest([{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]), ["Alice"])`)
|
||||
}})
|
||||
```
|
||||
|
||||
`get_oldest([{ "name": "Allison", "age": 25 }, { "name": "Bill", "age": 30 }, { "name": "Carol", "age": 30 }])` should return `["Bill", "Carol"]`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(get_oldest([{"name": "Allison", "age": 25}, {"name": "Bill", "age": 30}, {"name": "Carol", "age": 30}]), ["Bill", "Carol"])`)
|
||||
}})
|
||||
```
|
||||
|
||||
`get_oldest([{ "name": "George", "age": 50 }, { "name": "Shirley", "age": 42 }, { "name": "Beth", "age": 48 }, { "name": "Holly", "age": 50 }, { "name": "Kevin", "age": 44 }, { "name": "Frank", "age": 47 }, { "name": "Zach", "age": 50 }, { "name": "Jennifer", "age": 43 }])` should return `["George", "Holly", "Zach"]`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(get_oldest([{"name": "George", "age": 50}, {"name": "Shirley", "age": 42}, {"name": "Beth", "age": 48}, {"name": "Holly", "age": 50}, {"name": "Kevin", "age": 44}, {"name": "Frank", "age": 47}, {"name": "Zach", "age": 50}, {"name": "Jennifer", "age": 43}]), ["George", "Holly", "Zach"])`)
|
||||
}})
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```py
|
||||
def get_oldest(people):
|
||||
|
||||
return people
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```py
|
||||
def get_oldest(people):
|
||||
max_age = max(p["age"] for p in people)
|
||||
return [p["name"] for p in people if p["age"] == max_age]
|
||||
```
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
---
|
||||
id: 69e2383af7832c8032603b91
|
||||
title: "Challenge 275: Character Frequency"
|
||||
challengeType: 29
|
||||
dashedName: challenge-275
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string, return an object (JavaScript) or dictionary (Python) mapping each character to the number of times it appears.
|
||||
|
||||
# --hints--
|
||||
|
||||
`get_frequency("test")` should return `{"t": 2, "e": 1, "s": 1}`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(get_frequency("test"), {"t": 2, "e": 1, "s": 1})`)
|
||||
}})
|
||||
```
|
||||
|
||||
`get_frequency("mississippi")` should return `{"m": 1, "i": 4, "s": 4, "p": 2}`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(get_frequency("mississippi"), {"m": 1, "i": 4, "s": 4, "p": 2})`)
|
||||
}})
|
||||
```
|
||||
|
||||
`get_frequency("hello world")` should return `{"h": 1, "e": 1, "l": 3, "o": 2, " ": 1, "w": 1, "r": 1, "d": 1}`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(get_frequency("hello world"), {"h": 1, "e": 1, "l": 3, "o": 2, " ": 1, "w": 1, "r": 1, "d": 1})`)
|
||||
}})
|
||||
```
|
||||
|
||||
`get_frequency("She sells seashells by the seashore.")` should return `{"S": 1, "h": 4, "e": 7, " ": 5, "s": 7, "l": 4, "a": 2, "b": 1, "y": 1, "t": 1, "o": 1, "r": 1, ".": 1}`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(get_frequency("She sells seashells by the seashore."), {"S": 1, "h": 4, "e": 7, " ": 5, "s": 7, "l": 4, "a": 2, "b": 1, "y": 1, "t": 1, "o": 1, "r": 1, ".": 1})`)
|
||||
}})
|
||||
```
|
||||
|
||||
`get_frequency("The quick brown fox jumps over the lazy dog.")` should return `{"T": 1, "h": 2, "e": 3, " ": 8, "q": 1, "u": 2, "i": 1, "c": 1, "k": 1, "b": 1, "r": 2, "o": 4, "w": 1, "n": 1, "f": 1, "x": 1, "j": 1, "m": 1, "p": 1, "s": 1, "v": 1, "t": 1, "l": 1, "a": 1, "z": 1, "y": 1, "d": 1, "g": 1, ".": 1}`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(get_frequency("The quick brown fox jumps over the lazy dog."), {"T": 1, "h": 2, "e": 3, " ": 8, "q": 1, "u": 2, "i": 1, "c": 1, "k": 1, "b": 1, "r": 2, "o": 4, "w": 1, "n": 1, "f": 1, "x": 1, "j": 1, "m": 1, "p": 1, "s": 1, "v": 1, "t": 1, "l": 1, "a": 1, "z": 1, "y": 1, "d": 1, "g": 1, ".": 1})`)
|
||||
}})
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```py
|
||||
def get_frequency(s):
|
||||
|
||||
return s
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```py
|
||||
def get_frequency(s):
|
||||
freq = {}
|
||||
for char in s:
|
||||
freq[char] = freq.get(char, 0) + 1
|
||||
return freq
|
||||
```
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
---
|
||||
id: 69e2383af7832c8032603b92
|
||||
title: "Challenge 276: Offending Element"
|
||||
challengeType: 29
|
||||
dashedName: challenge-276
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given an array of integers that is sorted in ascending order except for one out-of-place element, return the index of that element.
|
||||
|
||||
- If more than one element could be considered out of place, return the index of the first one.
|
||||
|
||||
# --hints--
|
||||
|
||||
`find_offender([1, 6, 2, 3, 4, 5])` should return `1`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(find_offender([1, 6, 2, 3, 4, 5]), 1)`)
|
||||
}})
|
||||
```
|
||||
|
||||
`find_offender([1, 2, 3, 5, 4, 5])` should return `3`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(find_offender([1, 2, 3, 5, 4, 5]), 3)`)
|
||||
}})
|
||||
```
|
||||
|
||||
`find_offender([2, 1])` should return `0`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(find_offender([2, 1]), 0)`)
|
||||
}})
|
||||
```
|
||||
|
||||
`find_offender([2, 4, 1, 6, 8])` should return `2`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(find_offender([2, 4, 1, 6, 8]), 2)`)
|
||||
}})
|
||||
```
|
||||
|
||||
`find_offender([5, 18, 24, 33, 40, 55, 15, 68, 84, 91])` should return `6`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(find_offender([5, 18, 24, 33, 40, 55, 15, 68, 84, 91]), 6)`)
|
||||
}})
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```py
|
||||
def find_offender(arr):
|
||||
|
||||
return arr
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```py
|
||||
def find_offender(arr):
|
||||
for i in range(len(arr)):
|
||||
without = arr[:i] + arr[i+1:]
|
||||
if all(without[j-1] <= without[j] for j in range(1, len(without))):
|
||||
return i
|
||||
```
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
---
|
||||
id: 69e2383af7832c8032603b93
|
||||
title: "Challenge 277: Mirror Image"
|
||||
challengeType: 29
|
||||
dashedName: challenge-277
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given two strings, determine if the second string is a mirror image of the first.
|
||||
|
||||
A mirror image is formed by reversing the string and replacing each character with its mirror equivalent.
|
||||
|
||||
- Symmetric characters look like themselves in a mirror:
|
||||
|
||||
`W`, `T`, `Y`, `U`, `I`, `O`, `H`, `A`, `X`, `V`, `M`, `w`, `o`, `x`, `v`, `0`, `8`, `=`, `+`, `:`, `|`, `-`, `_`, `*`, `^`, `!`, `.`, and the space (` `).
|
||||
|
||||
- Mirrored pairs swap with each other in a mirror:
|
||||
|
||||
| Character | Swaps with |
|
||||
| - | - |
|
||||
| `[` | `]` |
|
||||
| `{` | `}` |
|
||||
| `<` | `>` |
|
||||
| `b` | `d` |
|
||||
| `p` | `q` |
|
||||
| `(` | `)` |
|
||||
|
||||
If either string includes a character not in the lists above, it doesn't have mirror image that can be created from the characters.
|
||||
|
||||
For example, the mirrored image of `"[HOW]"` is `"[WOH]"`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`is_mirror_image("[HOW]", "[WOH]")` should return `True`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertIs(is_mirror_image("[HOW]", "[WOH]"), True)`)
|
||||
}})
|
||||
```
|
||||
|
||||
`is_mirror_image("MOM", "MOM")` should return `True`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertIs(is_mirror_image("MOM", "MOM"), True)`)
|
||||
}})
|
||||
```
|
||||
|
||||
`is_mirror_image("vow", "wov")` should return `True`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertIs(is_mirror_image("vow", "wov"), True)`)
|
||||
}})
|
||||
```
|
||||
|
||||
`is_mirror_image("TIM", "TIM")` should return `False`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertIs(is_mirror_image("TIM", "TIM"), False)`)
|
||||
}})
|
||||
```
|
||||
|
||||
`is_mirror_image("{WOW}", "}WOW{")` should return `False`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertIs(is_mirror_image("{WOW}", "}WOW{"), False)`)
|
||||
}})
|
||||
```
|
||||
|
||||
`is_mirror_image("XXVII", "IIV%X")` should return `False`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertIs(is_mirror_image("XXVII", "IIV%X"), False)`)
|
||||
}})
|
||||
```
|
||||
|
||||
`is_mirror_image("><(((*>", "<*)))><")` should return `True`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertIs(is_mirror_image("><(((*>", "<*)))><"), True)`)
|
||||
}})
|
||||
```
|
||||
|
||||
`is_mirror_image("WTYUIOHAXVMwoxv08=+:|-_*^!.[]{}<>bdpq()", "()pqbd<>{}[].!^*_-|:+=80vxowMVXAHOIUYTW")` should return `True`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertIs(is_mirror_image("WTYUIOHAXVMwoxv08=+:|-_*^!.[]{}<>bdpq()", "()pqbd<>{}[].!^*_-|:+=80vxowMVXAHOIUYTW"), True)`)
|
||||
}})
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```py
|
||||
def is_mirror_image(s1, s2):
|
||||
|
||||
return s1
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```py
|
||||
def is_mirror_image(s1, s2):
|
||||
symmetric = set('WTYUIOHA XVMwoxv08=+:|-_*^!.')
|
||||
pairs = {'[': ']', ']': '[', '{': '}', '}': '{', '<': '>', '>': '<',
|
||||
'b': 'd', 'd': 'b', 'p': 'q', 'q': 'p', '(': ')', ')': '('}
|
||||
mirrored = []
|
||||
for c in reversed(s1):
|
||||
if c in symmetric:
|
||||
mirrored.append(c)
|
||||
elif c in pairs:
|
||||
mirrored.append(pairs[c])
|
||||
else:
|
||||
return False
|
||||
return ''.join(mirrored) == s2
|
||||
```
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
---
|
||||
id: 69e2383af7832c8032603b94
|
||||
title: "Challenge 278: Coffee Order Parser"
|
||||
challengeType: 29
|
||||
dashedName: challenge-278
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string for a coffee order, identify any menu items and return a formatted order.
|
||||
|
||||
Use the following menu items and prices:
|
||||
|
||||
| Item | Price |
|
||||
| - | - |
|
||||
| `"cold brew"` | $4.50 |
|
||||
| `"oat latte"` | $5.00 |
|
||||
| `"cappuccino"` | $4.75 |
|
||||
| `"espresso"` | $3.00 |
|
||||
| `"vanilla syrup"` | $0.75 |
|
||||
| `"caramel drizzle"` | $0.60 |
|
||||
| `"extra shot"` | $0.50 |
|
||||
| `"oat milk"` | $0.75 |
|
||||
| `"cream"` | $0.75 |
|
||||
|
||||
Return a string with the matched items joined by `" + "`, followed by a colon and space (`": "`), and the total price.
|
||||
|
||||
For example, given `"I'd like an oat latte with vanilla syrup and an extra shot please."`, return `"oat latte + vanilla syrup + extra shot: $6.25"`
|
||||
|
||||
Items should appear in the order they appear in the menu and the total price should always have two decimal places.
|
||||
|
||||
# --hints--
|
||||
|
||||
`format_coffee_order("I'd like an oat latte with vanilla syrup and an extra shot please.")` should return `"oat latte + vanilla syrup + extra shot: $6.25"`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(format_coffee_order("I'd like an oat latte with vanilla syrup and an extra shot please."), "oat latte + vanilla syrup + extra shot: $6.25")`)
|
||||
}})
|
||||
```
|
||||
|
||||
`format_coffee_order("Give me a cappuccino with caramel drizzle, vanilla syrup, and some oat milk.")` should return `"cappuccino + vanilla syrup + caramel drizzle + oat milk: $6.85"`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(format_coffee_order("Give me a cappuccino with caramel drizzle, vanilla syrup, and some oat milk."), "cappuccino + vanilla syrup + caramel drizzle + oat milk: $6.85")`)
|
||||
}})
|
||||
```
|
||||
|
||||
`format_coffee_order("Can I get a cold brew with some cream and an extra shot.")` should return `"cold brew + extra shot + cream: $5.75"`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(format_coffee_order("Can I get a cold brew with some cream and an extra shot."), "cold brew + extra shot + cream: $5.75")`)
|
||||
}})
|
||||
```
|
||||
|
||||
`format_coffee_order("Just an espresso please.")` should return `"espresso: $3.00"`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(format_coffee_order("Just an espresso please."), "espresso: $3.00")`)
|
||||
}})
|
||||
```
|
||||
|
||||
`format_coffee_order("I'll take an oat latte with cream and an extra shot, and some vanilla syrup and caramel drizzle.")` should return `"oat latte + vanilla syrup + caramel drizzle + extra shot + cream: $7.60"`.
|
||||
|
||||
```js
|
||||
({test: () => { runPython(`
|
||||
from unittest import TestCase
|
||||
TestCase().assertEqual(format_coffee_order("I'll take an oat latte with cream and an extra shot, and some vanilla syrup and caramel drizzle."), "oat latte + vanilla syrup + caramel drizzle + extra shot + cream: $7.60")`)
|
||||
}})
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```py
|
||||
def format_coffee_order(order):
|
||||
|
||||
return order
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```py
|
||||
def format_coffee_order(order):
|
||||
menu = [
|
||||
("cold brew", 450),
|
||||
("oat latte", 500),
|
||||
("cappuccino", 475),
|
||||
("espresso", 300),
|
||||
("vanilla syrup", 75),
|
||||
("caramel drizzle", 60),
|
||||
("extra shot", 50),
|
||||
("oat milk", 75),
|
||||
("cream", 75),
|
||||
]
|
||||
found = [(name, price) for name, price in menu if name in order.lower()]
|
||||
total = sum(price for _, price in found)
|
||||
items = " + ".join(name for name, _ in found)
|
||||
return f"{items}: ${total / 100:.2f}"
|
||||
```
|
||||
@@ -1057,6 +1057,66 @@
|
||||
{
|
||||
"id": "69c6ff713a52713463aa7929",
|
||||
"title": "Challenge 263: Binary Crossword"
|
||||
},
|
||||
{
|
||||
"id": "69cfca90e8a0a6d4d6871c4e",
|
||||
"title": "Challenge 264: Anagram Groups"
|
||||
},
|
||||
{
|
||||
"id": "69cfca90e8a0a6d4d6871c4f",
|
||||
"title": "Challenge 265: Deepest Brackets"
|
||||
},
|
||||
{
|
||||
"id": "69cfca90e8a0a6d4d6871c50",
|
||||
"title": "Challenge 266: Good Day"
|
||||
},
|
||||
{
|
||||
"id": "69cfca90e8a0a6d4d6871c51",
|
||||
"title": "Challenge 267: Parsec Converter"
|
||||
},
|
||||
{
|
||||
"id": "69cfca90e8a0a6d4d6871c52",
|
||||
"title": "Challenge 268: Narcissistic Number"
|
||||
},
|
||||
{
|
||||
"id": "69cfca90e8a0a6d4d6871c53",
|
||||
"title": "Challenge 269: Allergen Friendly Meals"
|
||||
},
|
||||
{
|
||||
"id": "69cfca90e8a0a6d4d6871c54",
|
||||
"title": "Challenge 270: Longest Common Substring"
|
||||
},
|
||||
{
|
||||
"id": "69d03e549613fbdbe21d11e0",
|
||||
"title": "Challenge 271: Medication Reminder"
|
||||
},
|
||||
{
|
||||
"id": "69e2383af7832c8032603b8e",
|
||||
"title": "Challenge 272: Transposed Matrix"
|
||||
},
|
||||
{
|
||||
"id": "69e2383af7832c8032603b8f",
|
||||
"title": "Challenge 273: ISBN-13 Validator"
|
||||
},
|
||||
{
|
||||
"id": "69e2383af7832c8032603b90",
|
||||
"title": "Challenge 274: Oldest Person"
|
||||
},
|
||||
{
|
||||
"id": "69e2383af7832c8032603b91",
|
||||
"title": "Challenge 275: Character Frequency"
|
||||
},
|
||||
{
|
||||
"id": "69e2383af7832c8032603b92",
|
||||
"title": "Challenge 276: Offending Element"
|
||||
},
|
||||
{
|
||||
"id": "69e2383af7832c8032603b93",
|
||||
"title": "Challenge 277: Mirror Image"
|
||||
},
|
||||
{
|
||||
"id": "69e2383af7832c8032603b94",
|
||||
"title": "Challenge 278: Coffee Order Parser"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1056,6 +1056,66 @@
|
||||
{
|
||||
"id": "69c6ff713a52713463aa7929",
|
||||
"title": "Challenge 263: Binary Crossword"
|
||||
},
|
||||
{
|
||||
"id": "69cfca90e8a0a6d4d6871c4e",
|
||||
"title": "Challenge 264: Anagram Groups"
|
||||
},
|
||||
{
|
||||
"id": "69cfca90e8a0a6d4d6871c4f",
|
||||
"title": "Challenge 265: Deepest Brackets"
|
||||
},
|
||||
{
|
||||
"id": "69cfca90e8a0a6d4d6871c50",
|
||||
"title": "Challenge 266: Good Day"
|
||||
},
|
||||
{
|
||||
"id": "69cfca90e8a0a6d4d6871c51",
|
||||
"title": "Challenge 267: Parsec Converter"
|
||||
},
|
||||
{
|
||||
"id": "69cfca90e8a0a6d4d6871c52",
|
||||
"title": "Challenge 268: Narcissistic Number"
|
||||
},
|
||||
{
|
||||
"id": "69cfca90e8a0a6d4d6871c53",
|
||||
"title": "Challenge 269: Allergen Friendly Meals"
|
||||
},
|
||||
{
|
||||
"id": "69cfca90e8a0a6d4d6871c54",
|
||||
"title": "Challenge 270: Longest Common Substring"
|
||||
},
|
||||
{
|
||||
"id": "69d03e549613fbdbe21d11e0",
|
||||
"title": "Challenge 271: Medication Reminder"
|
||||
},
|
||||
{
|
||||
"id": "69e2383af7832c8032603b8e",
|
||||
"title": "Challenge 272: Transposed Matrix"
|
||||
},
|
||||
{
|
||||
"id": "69e2383af7832c8032603b8f",
|
||||
"title": "Challenge 273: ISBN-13 Validator"
|
||||
},
|
||||
{
|
||||
"id": "69e2383af7832c8032603b90",
|
||||
"title": "Challenge 274: Oldest Person"
|
||||
},
|
||||
{
|
||||
"id": "69e2383af7832c8032603b91",
|
||||
"title": "Challenge 275: Character Frequency"
|
||||
},
|
||||
{
|
||||
"id": "69e2383af7832c8032603b92",
|
||||
"title": "Challenge 276: Offending Element"
|
||||
},
|
||||
{
|
||||
"id": "69e2383af7832c8032603b93",
|
||||
"title": "Challenge 277: Mirror Image"
|
||||
},
|
||||
{
|
||||
"id": "69e2383af7832c8032603b94",
|
||||
"title": "Challenge 278: Coffee Order Parser"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -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 = 263;
|
||||
const EXPECTED_CHALLENGE_COUNT = 278;
|
||||
|
||||
// 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)**
|
||||
|
||||
Reference in New Issue
Block a user