feat(curriculum): daily challenges 295-311 (#67606)

Co-authored-by: majestic-owl448 <26656284+majestic-owl448@users.noreply.github.com>
This commit is contained in:
Tom 2026-05-29 10:07:12 -05:00 committed by GitHub
parent f4c8d3f3c8
commit d0e24db0f8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
37 changed files with 3515 additions and 1 deletions

View File

@ -0,0 +1,69 @@
---
id: 6a0dcc730cb92a616f86f0bf
title: "Challenge 295: Schema Validator Part 1"
challengeType: 28
dashedName: challenge-295
---
# --description--
Given an object (JavaScript) or dictionary (Python), determine if it matches the following schema:
```json
{
username: string
}
```
- Extra keys are allowed
# --hints--
`isValidSchema({ username: "bob" })` should return `true`.
```js
assert.isTrue(isValidSchema({ username: "bob" }));
```
`isValidSchema({ username: "jen", posts: 30 })` should return `true`.
```js
assert.isTrue(isValidSchema({ username: "jen", posts: 30 }));
```
`isValidSchema({ username: "" })` should return `true`.
```js
assert.isTrue(isValidSchema({ username: "" }));
```
`isValidSchema({ username: 7 })` should return `false`.
```js
assert.isFalse(isValidSchema({ username: 7 }));
```
`isValidSchema({ posts: 25 })` should return `false`.
```js
assert.isFalse(isValidSchema({ posts: 25 }));
```
# --seed--
## --seed-contents--
```js
function isValidSchema(obj) {
return obj;
}
```
# --solutions--
```js
function isValidSchema(obj) {
return typeof obj.username === 'string';
}
```

View File

@ -0,0 +1,87 @@
---
id: 6a0dcc730cb92a616f86f0c0
title: "Challenge 296: Schema Validator Part 2"
challengeType: 28
dashedName: challenge-296
---
# --description--
Given an object (JavaScript) or dictionary (Python), determine if it matches the following schema:
```json
{
username: string,
posts: number,
verified: boolean
}
```
- Extra keys are allowed
# --hints--
`isValidSchema({ username: "alice", posts: 10, verified: false })` should return `true`.
```js
assert.isTrue(isValidSchema({ username: "alice", posts: 10, verified: false }));
```
`isValidSchema({ username: "carol", posts: 15, verified: true, followers: 25 })` should return `true`.
```js
assert.isTrue(isValidSchema({ username: "carol", posts: 15, verified: true, followers: 25 }));
```
`isValidSchema({ username: "frank", posts: "21", verified: true })` should return `false`.
```js
assert.isFalse(isValidSchema({ username: "frank", posts: "21", verified: true }));
```
`isValidSchema({ username: "sam", posts: 17, verified: "false" })` should return `false`.
```js
assert.isFalse(isValidSchema({ username: "sam", posts: 17, verified: "false" }));
```
`isValidSchema({ username: "bill", verified: true })` should return `false`.
```js
assert.isFalse(isValidSchema({ username: "bill", verified: true }));
```
`isValidSchema({ username: "fred", verified: true })` should return `false`.
```js
assert.isFalse(isValidSchema({ username: "fred", verified: true }));
```
`isValidSchema({ username: 5, posts: 10, verified: true })` should return `false`.
```js
assert.isFalse(isValidSchema({ username: 5, posts: 10, verified: true }));
```
# --seed--
## --seed-contents--
```js
function isValidSchema(obj) {
return obj;
}
```
# --solutions--
```js
function isValidSchema(obj) {
return (
typeof obj.username === 'string' &&
typeof obj.posts === 'number' &&
typeof obj.verified === 'boolean'
);
}
```

View File

@ -0,0 +1,117 @@
---
id: 6a0dcc730cb92a616f86f0c1
title: "Challenge 297: Schema Validator Part 3"
challengeType: 28
dashedName: challenge-297
---
# --description--
Given an object (JavaScript) or dictionary (Python), determine if it matches the following schema:
```json
Roles = "user" | "creator" | "moderator" | "staff" | "admin"
{
username: string,
posts: number,
verified: boolean,
role: Roles
}
```
- The pipe (`|`) symbol means "or". `role` must be one of the listed `Roles` values.
- Extra keys are allowed
# --hints--
`isValidSchema({ username: "henry", posts: 0, verified: true, role: "staff" })` should return `true`.
```js
assert.isTrue(isValidSchema({ username: "henry", posts: 0, verified: true, role: "staff" }));
```
`isValidSchema({ username: "sara", posts: 45, verified: false, role: "creator", followers: 70 })` should return `true`.
```js
assert.isTrue(isValidSchema({ username: "sara", posts: 45, verified: false, role: "creator", followers: 70 }));
```
`isValidSchema({ username: "penelope", posts: 20, verified: true, role: "admin" })` should return `true`.
```js
assert.isTrue(isValidSchema({ username: "penelope", posts: 20, verified: true, role: "admin" }));
```
`isValidSchema({ username: "kevin", posts: 0, verified: false, role: "user" })` should return `true`.
```js
assert.isTrue(isValidSchema({ username: "kevin", posts: 0, verified: false, role: "user" }));
```
`isValidSchema({ username: "george", posts: 15, verified: true, role: "moderator" })` should return `true`.
```js
assert.isTrue(isValidSchema({ username: "george", posts: 15, verified: true, role: "moderator" }));
```
`isValidSchema({ username: "david", posts: 0, verified: false, role: "guest" })` should return `false`.
```js
assert.isFalse(isValidSchema({ username: "david", posts: 0, verified: false, role: "guest" }));
```
`isValidSchema({ username: "wendy", posts: 10, verified: true })` should return `false`.
```js
assert.isFalse(isValidSchema({ username: "wendy", posts: 10, verified: true }));
```
`isValidSchema({ username: "fabian", posts: 1, verified: true, role: true })` should return `false`.
```js
assert.isFalse(isValidSchema({ username: "fabian", posts: 1, verified: true, role: true }));
```
`isValidSchema({ username: 8, posts: 1, verified: true, role: "user" })` should return `false`.
```js
assert.isFalse(isValidSchema({ username: 8, posts: 1, verified: true, role: "user" }));
```
`isValidSchema({ username: "penny", posts: "10", verified: true, role: "staff" })` should return `false`.
```js
assert.isFalse(isValidSchema({ username: "penny", posts: "10", verified: true, role: "staff" }));
```
`isValidSchema({ username: "john", posts: "1", verified: "true", role: "admin" })` should return `false`.
```js
assert.isFalse(isValidSchema({ username: "john", posts: "1", verified: "true", role: "admin" }));
```
# --seed--
## --seed-contents--
```js
function isValidSchema(obj) {
return obj;
}
```
# --solutions--
```js
function isValidSchema(obj) {
const roles = ["user", "creator", "moderator", "staff", "admin"];
return (
typeof obj.username === 'string' &&
typeof obj.posts === 'number' &&
typeof obj.verified === 'boolean' &&
roles.includes(obj.role)
);
}
```

View File

@ -0,0 +1,102 @@
---
id: 6a0dcc730cb92a616f86f0c2
title: "Challenge 298: Schema Validator Part 4"
challengeType: 28
dashedName: challenge-298
---
# --description--
Given an object (JavaScript) or dictionary (Python), determine if it matches the following schema:
```json
Roles = "user" | "creator" | "moderator" | "staff" | "admin"
{
username: string,
posts: number,
verified: boolean,
role: Roles,
supporter?: boolean
}
```
- The pipe (`|`) symbol means "or". `role` must be one of the listed `Roles` values.
- The question mark (`?`) after `supporter` means that the field is optional, but is the specified type if it exists.
- Extra keys are allowed
# --hints--
`isValidSchema({ username: "vivian", posts: 1, verified: false, role: "user", supporter: true })` should return `true`.
```js
assert.isTrue(isValidSchema({ username: "vivian", posts: 1, verified: false, role: "user", supporter: true }));
```
`isValidSchema({ username: "rudolph", posts: 15, verified: true, role: "creator" })` should return `true`.
```js
assert.isTrue(isValidSchema({ username: "rudolph", posts: 15, verified: true, role: "creator" }));
```
`isValidSchema({ username: "hernandez", posts: 35, verified: true, role: "moderator", supporter: false, followers: 55 })` should return `true`.
```js
assert.isTrue(isValidSchema({ username: "hernandez", posts: 35, verified: true, role: "moderator", supporter: false, followers: 55 }));
```
`isValidSchema({ username: "julia", posts: 50, verified: true, role: "admin", supporter: "true" })` should return `false`.
```js
assert.isFalse(isValidSchema({ username: "julia", posts: 50, verified: true, role: "admin", supporter: "true" }));
```
`isValidSchema({ username: "bernard", posts: 0, verified: true, role: "friend", supporter: true })` should return `false`.
```js
assert.isFalse(isValidSchema({ username: "bernard", posts: 0, verified: true, role: "friend", supporter: true }));
```
`isValidSchema({ username: "felix", posts: 40, verified: "yes", role: "staff", supporter: false })` should return `false`.
```js
assert.isFalse(isValidSchema({ username: "felix", posts: 40, verified: "yes", role: "staff", supporter: false }));
```
`isValidSchema({ username: "jimmy", posts: true, verified: false, role: "creator", supporter: true })` should return `false`.
```js
assert.isFalse(isValidSchema({ username: "jimmy", posts: true, verified: false, role: "creator", supporter: true }));
```
`isValidSchema({ username: true, posts: 30, verified: true, role: "moderator", supporter: false })` should return `false`.
```js
assert.isFalse(isValidSchema({ username: true, posts: 30, verified: true, role: "moderator", supporter: false }));
```
# --seed--
## --seed-contents--
```js
function isValidSchema(obj) {
return obj;
}
```
# --solutions--
```js
function isValidSchema(obj) {
const roles = ["user", "creator", "moderator", "staff", "admin"];
return (
typeof obj.username === 'string' &&
typeof obj.posts === 'number' &&
typeof obj.verified === 'boolean' &&
roles.includes(obj.role) &&
(obj.supporter === undefined || typeof obj.supporter === 'boolean')
);
}
```

View File

@ -0,0 +1,117 @@
---
id: 6a0dcc730cb92a616f86f0c3
title: "Challenge 299: Schema Validator Part 5"
challengeType: 28
dashedName: challenge-299
---
# --description--
Given an object (JavaScript) or dictionary (Python), determine if it matches the following schema:
```json
Roles = "user" | "creator" | "moderator" | "staff" | "admin"
{
username: string,
posts: number,
verified: boolean,
role: Roles,
supporter?: boolean,
badges: string[]
}
```
- The pipe (`|`) symbol means "or". `role` must be one of the listed `Roles` values.
- The question mark (`?`) after `supporter` means that the field is optional, but is the specified type if it exists.
- The brackets `[]` after `string` means that `badges` should be an array of strings (or empty).
- Extra keys are allowed
# --hints--
`isValidSchema({ username: "gill", posts: 12, verified: false, role: "creator", supporter: false, badges: [ "early-adopter", "popular" ] })` should return `true`.
```js
assert.isTrue(isValidSchema({ username: "gill", posts: 12, verified: false, role: "creator", supporter: false, badges: [ "early-adopter", "popular" ] }));
```
`isValidSchema({ username: "tonya", posts: 299, verified: true, role: "moderator", supporter: true, badges: [ "streak-master", "veteran" ], followers: 1233 })` should return `true`.
```js
assert.isTrue(isValidSchema({ username: "tonya", posts: 299, verified: true, role: "moderator", supporter: true, badges: [ "streak-master", "veteran" ], followers: 1233 }));
```
`isValidSchema({ username: "zara", posts: 0, verified: false, role: "user", supporter: false, badges: [] })` should return `true`.
```js
assert.isTrue(isValidSchema({ username: "zara", posts: 0, verified: false, role: "user", supporter: false, badges: [] }));
```
`isValidSchema({ username: "nicole", posts: 65, verified: true, role: "admin", supporter: false, badges: [ "first-post", 18 ] })` should return `false`.
```js
assert.isFalse(isValidSchema({ username: "nicole", posts: 65, verified: true, role: "admin", supporter: false, badges: [ "first-post", 18 ] }));
```
`isValidSchema({ username: "tim", posts: 25, verified: true, role: "staff", supporter: false })` should return `false`.
```js
assert.isFalse(isValidSchema({ username: "tim", posts: 25, verified: true, role: "staff", supporter: false }));
```
`isValidSchema({ username: "charlie", posts: 0, verified: false, role: "user", supporter: "no", badges: [ "first-post", "anniversary" ] })` should return `false`.
```js
assert.isFalse(isValidSchema({ username: "charlie", posts: 0, verified: false, role: "user", supporter: "no", badges: [ "first-post", "anniversary" ] }));
```
`isValidSchema({ username: "wanda", posts: 15, verified: true, role: "friend", supporter: true, badges: [ "popular" ] })` should return `false`.
```js
assert.isFalse(isValidSchema({ username: "wanda", posts: 15, verified: true, role: "friend", supporter: true, badges: [ "popular" ] }));
```
`isValidSchema({ username: "guy", posts: 5, verified: "false", role: "staff", supporter: true, badges: [ "helper" ] })` should return `false`.
```js
assert.isFalse(isValidSchema({ username: "guy", posts: 5, verified: "false", role: "staff", supporter: true, badges: [ "helper" ] }));
```
`isValidSchema({ username: "carrie", verified: true, role: "moderator", supporter: true, badges: [ "helper", "sharer" ] })` should return `false`.
```js
assert.isFalse(isValidSchema({ username: "carrie", verified: true, role: "moderator", supporter: true, badges: [ "helper", "sharer" ] }));
```
`isValidSchema({ username: true, posts: 75, verified: true, role: "creator", supporter: true, badges: [ "veteran" ] })` should return `false`.
```js
assert.isFalse(isValidSchema({ username: true, posts: 75, verified: true, role: "creator", supporter: true, badges: [ "veteran" ] }));
```
# --seed--
## --seed-contents--
```js
function isValidSchema(obj) {
return obj;
}
```
# --solutions--
```js
function isValidSchema(obj) {
const roles = ["user", "creator", "moderator", "staff", "admin"];
return (
typeof obj.username === 'string' &&
typeof obj.posts === 'number' &&
typeof obj.verified === 'boolean' &&
roles.includes(obj.role) &&
(obj.supporter === undefined || typeof obj.supporter === 'boolean') &&
Array.isArray(obj.badges) && obj.badges.every(b => typeof b === 'string')
);
}
```

View File

@ -0,0 +1,126 @@
---
id: 6a0dcc730cb92a616f86f0c4
title: "Challenge 300: Schema Validator Part 6"
challengeType: 28
dashedName: challenge-300
---
# --description--
Given an object (JavaScript) or dictionary (Python), determine if it matches the following schema:
```json
Roles = "user" | "creator" | "moderator" | "staff" | "admin"
UserProfile = {
username: string,
posts: number,
verified: boolean,
role: Roles,
supporter?: boolean,
badges: string[]
}
{
users: UserProfile[]
}
```
- The pipe (`|`) symbol means "or". role must be one of the listed `Roles` values.
- The question mark (`?`) after supporter means that the field is optional, but is the specified type if it exists.
- `UserProfile[]` denotes an array of `UserProfile` objects. An empty array is valid.
- Extra keys are allowed
# --hints--
`isValidSchema({ users: [{ username: "ron", posts: 14, verified: true, role: "creator", badges: [ "early-adopter" ]}, { username: "cher", posts: 25, verified: true, role: "moderator", supporter: true, followers: 20, badges: [ "helper" ]}]})` should return `true`.
```js
assert.isTrue(isValidSchema({users: [{ username: "ron", posts: 14, verified: true, role: "creator", badges: [ "early-adopter" ]}, { username: "cher", posts: 25, verified: true, role: "moderator", supporter: true, followers: 20, badges: [ "helper" ]}]}));
```
`isValidSchema({ users: [] })` should return `true`.
```js
assert.isTrue(isValidSchema({ users: [] }));
```
`isValidSchema({ users: { username: "anne", posts: 0, verified: false, role: "user", supporter: false, badges: []}})` should return `false`.
```js
assert.isFalse(isValidSchema({ users: { username: "anne", posts: 0, verified: false, role: "user", supporter: false, badges: []}}));
```
`isValidSchema({ users: [{ username: "tony", posts: 10, verified: true, role: "creator", supporter: true, badges: ["liked", 6]}]})` should return `false`.
```js
assert.isFalse(isValidSchema({ users: [{ username: "tony", posts: 10, verified: true, role: "creator", supporter: true, badges: ["liked", 6]}]}));
```
`isValidSchema({ users: [{ username: "ursula", posts: 3, verified: false, role: "user", supporter: "false", badges: ["comeback"]}]})` should return `false`.
```js
assert.isFalse(isValidSchema({ users: [{ username: "ursula", posts: 3, verified: false, role: "user", supporter: "false", badges: ["comeback"]}]}));
```
`isValidSchema({ users: [{ username: "benny", posts: 55, verified: true, role: "superstar", supporter: true, badges: ["veteran"]}]})` should return `false`.
```js
assert.isFalse(isValidSchema({ users: [{ username: "benny", posts: 55, verified: true, role: "superstar", supporter: true, badges: ["veteran"]}]}));
```
`isValidSchema({ users: [{ username: "chase", posts: 1, verified: "yes", role: "staff", supporter: false, badges: ["superstar"]}]})` should return `false`.
```js
assert.isFalse(isValidSchema({ users: [{ username: "chase", posts: 1, verified: "yes", role: "staff", supporter: false, badges: ["superstar"]}]}));
```
`isValidSchema({ users: [{ username: "carla", posts: "10", verified: false, role: "user", supporter: false, badges: ["newbie"]}]})` should return `false`.
```js
assert.isFalse(isValidSchema({ users: [{ username: "carla", posts: "10", verified: false, role: "user", supporter: false, badges: ["newbie"]}]}));
```
`isValidSchema({ users: [{ posts: 4, verified: false, role: "admin", supporter: false, badges: ["superuser", "veteran"]}]})` should return `false`.
```js
assert.isFalse(isValidSchema({ users: [{ posts: 4, verified: false, role: "admin", supporter: false, badges: ["superuser", "veteran"]}]}));
```
`isValidSchema({ users: [{ username: "harold", posts: 80, verified: true, role: "creator", supporter: true, badges: ["liked", "hero"]}, { username: "kim", posts: 11, verified: false, role: "admin", supporter: true, badges: ["first"]}, {}]})` should return `false`.
```js
assert.isFalse(isValidSchema({ users: [{ username: "harold", posts: 80, verified: true, role: "creator", supporter: true, badges: ["liked", "hero"]}, { username: "kim", posts: 11, verified: false, role: "admin", supporter: true, badges: ["first"]}, {}]}));
```
# --seed--
## --seed-contents--
```js
function isValidSchema(obj) {
return obj;
}
```
# --solutions--
```js
function isValidSchema(obj) {
const roles = ["user", "creator", "moderator", "staff", "admin"];
function isValidUser(user) {
return (
typeof user.username === 'string' &&
typeof user.posts === 'number' &&
typeof user.verified === 'boolean' &&
roles.includes(user.role) &&
(user.supporter === undefined || typeof user.supporter === 'boolean') &&
Array.isArray(user.badges) && user.badges.every(b => typeof b === 'string')
);
}
return Array.isArray(obj.users) && obj.users.every(isValidUser);
}
```

View File

@ -0,0 +1,64 @@
---
id: 6a0dcc730cb92a616f86f0c5
title: "Challenge 301: Last Load"
challengeType: 28
dashedName: challenge-301
---
# --description--
Given the number of scoops of laundry detergent you have remaining and an array of how many scoops you used in each of the previous days, return the number of full days of detergent you have remaining.
Calculate your average daily usage from the usage history and assume that amount of usage each day going forward.
# --hints--
`lastLoadDate(10, [2, 2, 2, 2, 2, 2, 2])` should return `5`.
```js
assert.equal(lastLoadDate(10, [2, 2, 2, 2, 2, 2, 2]), 5);
```
`lastLoadDate(16, [2, 3, 0, 3, 4, 2, 1])` should return `7`.
```js
assert.equal(lastLoadDate(16, [2, 3, 0, 3, 4, 2, 1]), 7);
```
`lastLoadDate(33, [5, 0, 4, 3, 3, 2])` should return `11`.
```js
assert.equal(lastLoadDate(33, [5, 0, 4, 3, 3, 2]), 11);
```
`lastLoadDate(50, [2, 0, 2, 9, 12, 0, 2])` should return `12`.
```js
assert.equal(lastLoadDate(50, [2, 0, 2, 9, 12, 0, 2]), 12);
```
`lastLoadDate(20, [13, 9, 12, 10, 8])` should return `1`.
```js
assert.equal(lastLoadDate(20, [13, 9, 12, 10, 8]), 1);
```
# --seed--
## --seed-contents--
```js
function lastLoadDate(scoops, usage) {
return scoops;
}
```
# --solutions--
```js
function lastLoadDate(scoops, usage) {
const avg = usage.reduce((sum, n) => sum + n, 0) / usage.length;
return Math.floor(scoops / avg);
}
```

View File

@ -0,0 +1,110 @@
---
id: 6a0dcd03ee4e68698080ef66
title: "Challenge 302: Jet Lagged"
challengeType: 28
dashedName: challenge-302
---
# --description--
Given a departure city, an arrival city, a flight duration in hours, and a direction of travel, return the number of jet lag hours the traveller is experiencing.
The given cities will be from the following list that includes their UTC offset:
| City | Offset |
| - | - |
| `"Los Angeles"` | -8 |
| `"New York"` | -5 |
| `"London"` | 0 |
| `"Istanbul"` | +3 |
| `"Dubai"` | +4 |
| `"Hong Kong"` | +8 |
| `"Tokyo"` | +9 |
To calculate jet lag hours:
1. Find the timezone difference in hours between the two cities.
2. Determine the direction multiplier. If travelling `"east"`, it's 1.5, otherwise, it's 1.0.
3. Get the jet lag hours with the formula: timezone difference + (flight duration * 0.1) * direction multiplier
Return the jet lag hours rounded to one decimal place.
# --hints--
`getJetLagHours("Istanbul", "Hong Kong", 10, "east")` should return `6.5`.
```js
assert.equal(getJetLagHours("Istanbul", "Hong Kong", 10, "east"), 6.5);
```
`getJetLagHours("London", "New York", 8, "west")` should return `5.8`.
```js
assert.equal(getJetLagHours("London", "New York", 8, "west"), 5.8);
```
`getJetLagHours("Hong Kong", "Tokyo", 4, "east")` should return `1.6`.
```js
assert.equal(getJetLagHours("Hong Kong", "Tokyo", 4, "east"), 1.6);
```
`getJetLagHours("Dubai", "London", 7, "west")` should return `4.7`.
```js
assert.equal(getJetLagHours("Dubai", "London", 7, "west"), 4.7);
```
`getJetLagHours("Los Angeles", "Hong Kong", 15, "west")` should return `17.5`.
```js
assert.equal(getJetLagHours("Los Angeles", "Hong Kong", 15, "west"), 17.5);
```
`getJetLagHours("Tokyo", "Dubai", 9, "west")` should return `5.9`.
```js
assert.equal(getJetLagHours("Tokyo", "Dubai", 9, "west"), 5.9);
```
`getJetLagHours("New York", "Istanbul", 10, "east")` should return `9.5`.
```js
assert.equal(getJetLagHours("New York", "Istanbul", 10, "east"), 9.5);
```
# --seed--
## --seed-contents--
```js
function getJetLagHours(departureCity, arrivalCity, flightDuration, direction) {
return departureCity;
}
```
# --solutions--
```js
function getJetLagHours(departureCity, arrivalCity, flightDuration, direction) {
const offsets = {
"Los Angeles": -8,
"New York": -5,
"London": 0,
"Istanbul": +3,
"Dubai": +4,
"Hong Kong": +8,
"Tokyo": +9
};
const depOffset = offsets[departureCity];
const arrOffset = offsets[arrivalCity];
const timezoneDiff = Math.abs(arrOffset - depOffset);
const multiplier = direction === "east" ? 1.5 : 1.0;
const score = timezoneDiff + (flightDuration * 0.1) * multiplier;
return Math.round(score * 10) / 10;
}
```

View File

@ -0,0 +1,86 @@
---
id: 6a0dcd03ee4e68698080ef67
title: "Challenge 303: Roommates"
challengeType: 28
dashedName: challenge-303
---
# --description--
Given an array of people and their roommate group, return the room assignments for a hotel stay using the following rules:
- Each person has a `name` and a `group` property:
```json
[
{ "name": "Alice", "group": "A" },
{ "name": "Bob", "group": "B" },
{ "name": "Carol", "group": "A" }
]
```
- People can only share a room with someone from the same group and are paired in the order they are given.
- Return an array of strings with names separated by `" and "` for a shared room, and just the name for a solo room. Names must appear in the order they were paired. For the example above, return `["Alice and Carol", "Bob"]`.
# --hints--
`getRoommates([{ "name": "Alice", "group": "A" }, { "name": "Bob", "group": "B" }, { "name": "Carol", "group": "A" }])` should return `["Alice and Carol", "Bob"]`.
```js
assert.deepEqual(getRoommates([{ "name": "Alice", "group": "A" }, { "name": "Bob", "group": "B" }, { "name": "Carol", "group": "A" }]).sort(), ["Alice and Carol", "Bob"].sort());
```
`getRoommates([{ "name": "John", "group": "C" }, { "name": "Julia", "group": "C" }, { "name": "Jim", "group": "C" }])` should return `["John and Julia", "Jim"]`.
```js
assert.deepEqual(getRoommates([{ "name": "John", "group": "C" }, { "name": "Julia", "group": "C" }, { "name": "Jim", "group": "C" }]).sort(), ["John and Julia", "Jim"].sort());
```
`getRoommates([{ "name": "Adam", "group": "D" }, { "name": "Abraham", "group": "E" }, { "name": "Austin", "group": "E" }, { "name": "Augustus", "group": "D" }, { "name": "Angelica", "group": "D" }, { "name": "Aaron", "group": "E" }])` should return `["Adam and Augustus", "Angelica", "Abraham and Austin", "Aaron"]`.
```js
assert.deepEqual(getRoommates([{ "name": "Adam", "group": "D" }, { "name": "Abraham", "group": "E" }, { "name": "Austin", "group": "E" }, { "name": "Augustus", "group": "D" }, { "name": "Angelica", "group": "D" }, { "name": "Aaron", "group": "E" }]).sort(), ["Adam and Augustus", "Angelica", "Abraham and Austin", "Aaron"].sort());
```
`getRoommates([{ "name": "Frank", "group": "A" }, { "name": "Emitt", "group": "B" }, { "name": "Daria", "group": "F" }, { "name": "Charles", "group": "D" }, { "name": "Bailey", "group": "A" }, { "name": "Albert", "group": "F" }])` should return `["Frank and Bailey", "Emitt", "Daria and Albert", "Charles"]`.
```js
assert.deepEqual(getRoommates([{ "name": "Frank", "group": "A" }, { "name": "Emitt", "group": "B" }, { "name": "Daria", "group": "F" }, { "name": "Charles", "group": "D" }, { "name": "Bailey", "group": "A" }, { "name": "Albert", "group": "F" }]).sort(), ["Frank and Bailey", "Emitt", "Daria and Albert", "Charles"].sort());
```
`getRoommates([{ "name": "Kevin", "group": "A" }, { "name": "Yuri", "group": "A" }, { "name": "Hugo", "group": "B" }, { "name": "Violet", "group": "A" }, { "name": "Brett", "group": "A" }, { "name": "Wayne", "group": "B" }])` should return `["Kevin and Yuri", "Violet and Brett", "Hugo and Wayne"]`.
```js
assert.deepEqual(getRoommates([{ "name": "Kevin", "group": "A" }, { "name": "Yuri", "group": "A" }, { "name": "Hugo", "group": "B" }, { "name": "Violet", "group": "A" }, { "name": "Brett", "group": "A" }, { "name": "Wayne", "group": "B" }]).sort(), ["Kevin and Yuri", "Violet and Brett", "Hugo and Wayne"].sort());
```
# --seed--
## --seed-contents--
```js
function getRoommates(people) {
return people;
}
```
# --solutions--
```js
function getRoommates(people) {
const groups = {};
for (const { name, group } of people) {
(groups[group] = groups[group] || []).push(name);
}
return Object.values(groups).flatMap(group => {
const rooms = [];
for (let i = 0; i < group.length; i += 2) {
rooms.push(group.slice(i, i + 2).join(" and "));
}
return rooms;
});
}
```

View File

@ -0,0 +1,91 @@
---
id: 6a0dcd03ee4e68698080ef68
title: "Challenge 304: Itinerary Arrangements"
challengeType: 28
dashedName: challenge-304
---
# --description--
Given an array of at least two optional stops for a day trip, return the number of valid itinerary arrangements.
The itinerary always includes `"breakfast"`, `"lunch"`, and `"dinner"`, these will not be passed in as arguments. The optional stops can be placed anywhere in the itinerary, subject to the following rules:
- `"breakfast"` is always first, with at least one stop before `"lunch"`.
- `"lunch"` must appear before `"dinner"`, with at least one stop in between.
- At most, one optional stop may appear after `"dinner"`.
Return the number of valid arrangements.
# --hints--
`getItineraryCount(["library", "park"])` should return `2`.
```js
assert.equal(getItineraryCount(["library", "park"]), 2);
```
`getItineraryCount(["library", "park", "arcade"])` should return `18`.
```js
assert.equal(getItineraryCount(["library", "park", "arcade"]), 18);
```
`getItineraryCount(["library", "park", "arcade", "store"])` should return `120`.
```js
assert.equal(getItineraryCount(["library", "park", "arcade", "store"]), 120);
```
`getItineraryCount(["library", "park", "arcade", "store", "cafe"])` should return `840`.
```js
assert.equal(getItineraryCount(["library", "park", "arcade", "store", "cafe"]), 840);
```
`getItineraryCount(["library", "park", "arcade", "store", "cafe", "market", "museum"])` should return `55440`.
```js
assert.equal(getItineraryCount(["library", "park", "arcade", "store", "cafe", "market", "museum"]), 55440);
```
# --seed--
## --seed-contents--
```js
function getItineraryCount(stops) {
return stops;
}
```
# --solutions--
```js
function getItineraryCount(stops) {
const items = ["lunch", "dinner", ...stops];
let count = 0;
function permute(arr) {
if (arr.length === 0) return [[]];
return arr.flatMap((item, i) =>
permute([...arr.slice(0, i), ...arr.slice(i + 1)]).map(p => [item, ...p])
);
}
for (const perm of permute(items)) {
const lunchIdx = perm.indexOf("lunch");
const dinnerIdx = perm.indexOf("dinner");
if (lunchIdx >= dinnerIdx) continue;
if (lunchIdx < 1) continue;
if (dinnerIdx - lunchIdx < 2) continue;
if (perm.length - dinnerIdx - 1 > 1) continue;
count++;
}
return count;
}
```

View File

@ -0,0 +1,71 @@
---
id: 6a0dcd03ee4e68698080ef69
title: "Challenge 305: Idea Rankings"
challengeType: 28
dashedName: challenge-305
---
# --description--
Given a 2D array where each inner array contains (in this order) an idea name, an optimistic estimate, a realistic estimate, and a pessimistic estimate (in days), return an array of the idea names sorted by expected time to completion, shortest first.
Calculate the expected time to completion for each idea using the following formula:
- `expected = ((optimistic + 4 * realistic + pessimistic) / 6) * length of idea name`
# --hints--
`analyzeIdeas([["Add logging", 2, 5, 15], ["SEO optimization", 4, 8, 20], ["Fix bug", 1, 3, 5]])` should return `["Fix bug", "Add logging", "SEO optimization"]`.
```js
assert.deepEqual(analyzeIdeas([["Add logging", 2, 5, 15], ["SEO optimization", 4, 8, 20], ["Fix bug", 1, 3, 5]]), ["Fix bug", "Add logging", "SEO optimization"]);
```
`analyzeIdeas([["Dark mode", 1, 3, 8], ["Real-time collaboration feature", 6, 12, 20], ["Add tooltip", 1, 2, 4]])` should return `["Add tooltip", "Dark mode", "Real-time collaboration feature"]`.
```js
assert.deepEqual(analyzeIdeas([["Dark mode", 1, 3, 8], ["Real-time collaboration feature", 6, 12, 20], ["Add tooltip", 1, 2, 4]]), ["Add tooltip", "Dark mode", "Real-time collaboration feature"]);
```
`analyzeIdeas([["Update user profile page", 3, 7, 14], ["Add pagination", 2, 5, 10], ["Add tags", 2, 3, 6], ["Fix login bug", 1, 4, 8]])` should return `["Add tags", "Fix login bug", "Add pagination", "Update user profile page"]`.
```js
assert.deepEqual(analyzeIdeas([["Update user profile page", 3, 7, 14], ["Add pagination", 2, 5, 10], ["Add tags", 2, 3, 6], ["Fix login bug", 1, 4, 8]]), ["Add tags", "Fix login bug", "Add pagination", "Update user profile page"]);
```
`analyzeIdeas([["Migrate database", 14, 25, 40], ["Add chat assistant", 8, 15, 24], ["Redesign onboarding flow", 3, 7, 13], ["Add language support", 6, 11, 18]])` should return `["Redesign onboarding flow", "Add language support", "Add chat assistant", "Migrate database"]`.
```js
assert.deepEqual(analyzeIdeas([["Migrate database", 14, 25, 40], ["Add chat assistant", 8, 15, 24], ["Redesign onboarding flow", 3, 7, 13], ["Add language support", 6, 11, 18]]), ["Redesign onboarding flow", "Add language support", "Add chat assistant", "Migrate database"]);
```
`analyzeIdeas([["Add email notifications", 3, 7, 10], ["Migrate deployment flow", 6, 10, 16], ["Add push notifications", 2, 6, 10], ["Optimize continuous integration", 5, 8, 15], ["Analyze user patterns", 5, 10, 18], ["Create onboarding curriculum", 6, 15, 25]])` should return `["Add push notifications", "Add email notifications", "Analyze user patterns", "Migrate deployment flow", "Optimize continuous integration", "Create onboarding curriculum"]`.
```js
assert.deepEqual(analyzeIdeas([["Add email notifications", 3, 7, 10], ["Migrate deployment flow", 6, 10, 16], ["Add push notifications", 2, 6, 10], ["Optimize continuous integration", 5, 8, 15], ["Analyze user patterns", 5, 10, 18], ["Create onboarding curriculum", 6, 15, 25]]), ["Add push notifications", "Add email notifications", "Analyze user patterns", "Migrate deployment flow", "Optimize continuous integration", "Create onboarding curriculum"]);
```
# --seed--
## --seed-contents--
```js
function analyzeIdeas(ideas) {
return ideas;
}
```
# --solutions--
```js
function analyzeIdeas(ideas) {
return ideas
.map(([name, optimistic, realistic, pessimistic]) => ({
name,
expected: ((optimistic + 4 * realistic + pessimistic) / 6) * name.length
}))
.sort((a, b) => a.expected - b.expected)
.map(idea => idea.name);
}
```

View File

@ -0,0 +1,61 @@
---
id: 6a0dcd03ee4e68698080ef6a
title: "Challenge 306: HTML Content Extractor"
challengeType: 28
dashedName: challenge-306
---
# --description--
Given a string of HTML, return the plain text content with all tags removed.
# --hints--
`extractContent('<p>hello world</p>')` should return `"hello world"`.
```js
assert.equal(extractContent('<p>hello world</p>'), "hello world");
```
`extractContent('<p>hello <span>world</span></p>')` should return `"hello world"`.
```js
assert.equal(extractContent('<p>hello <span>world</span></p>'), "hello world");
```
`extractContent('<a href="example.com">Click me</a>')` should return `"Click me"`.
```js
assert.equal(extractContent('<a href="example.com">Click me</a>'), "Click me");
```
`extractContent('<p><button onClick="learnToCode()">Learn</button> to <code>code<code> <br/>for <strong>free</strong> <br/>on <a href="https://freecodecamp.org/" target="_blank"><span class="highlight">freecodecamp</span>.org</a>')` should return `"Learn to code for free on freecodecamp.org"`.
```js
assert.equal(extractContent('<p><button onClick="learnToCode()">Learn</button> to <code>code<code> <br/>for <strong>free</strong> <br/>on <a href="https://freecodecamp.org/" target="_blank"><span class="highlight">freecodecamp</span>.org</a>'), "Learn to code for free on freecodecamp.org");
```
`extractContent('<div class="container"><h1 id="title">Welcome to <strong>My</strong> Website.</h1><p>This is a <a href="https://example.com" target="_blank">link</a> to something <em>really</em> <span class="highlight">important</span>.</p><ul><li>Item <strong>one</strong></li><li>Item <em>two</em></li><li>Item three</li></ul><img src="pic.jpg" alt="A picture"/><p class="footer">Contact us at <a href="mailto:hello@example.com">hello@example.com</a> for <span>more <strong>info</strong></span>.</p></div>')` should return `"Welcome to My Website.This is a link to something really important.Item oneItem twoItem threeContact us at hello@example.com for more info."`.
```js
assert.equal(extractContent('<div class="container"><h1 id="title">Welcome to <strong>My</strong> Website.</h1><p>This is a <a href="https://example.com" target="_blank">link</a> to something <em>really</em> <span class="highlight">important</span>.</p><ul><li>Item <strong>one</strong></li><li>Item <em>two</em></li><li>Item three</li></ul><img src="pic.jpg" alt="A picture"/><p class="footer">Contact us at <a href="mailto:hello@example.com">hello@example.com</a> for <span>more <strong>info</strong></span>.</p></div>'), "Welcome to My Website.This is a link to something really important.Item oneItem twoItem threeContact us at hello@example.com for more info.");
```
# --seed--
## --seed-contents--
```js
function extractContent(html) {
return html;
}
```
# --solutions--
```js
function extractContent(html) {
return html.replace(/<[^>]*>/g, '').trim();
}
```

View File

@ -0,0 +1,105 @@
---
id: 6a0dcd03ee4e68698080ef6b
title: "Challenge 307: Zoning Regulations"
challengeType: 28
dashedName: challenge-307
---
# --description--
Given a 2D grid (array of arrays) representing a city's building layout, return the coordinates of all buildings that are violating zoning rules.
Each cell in the grid contains one of the labels from the table below. A building is in violation if any of its (up to) 4 neighbors, horizontal or vertical, are a type it cannot be adjacent to.
| Label | Type | Cannot be adjacent to |
| - | - | - |
| `"i"` | industrial | `"R"`, `"I"` |
| `"A"` | Agricultural | `"C"` |
| `"R"` | Residential | `"i"`, `"C"` |
| `"I"` | Institutional | `"i"` |
| `"C"` | Commercial | `"R"`, `"A"` |
| `""` (empty string) | undeveloped | no restrictions |
Return the coordinates of all violating cells as an array of `[row, col]` pairs, in any order. If no violations exist, return an empty array.
# --hints--
`getZoneViolations([["R", "C"], ["", "C"]])` should return `[[0, 0], [0, 1]]`.
```js
assert.deepEqual(getZoneViolations([["R", "C"], ["", "C"]]).sort(), [[0, 0], [0, 1]]);
```
`getZoneViolations([["", "i"], ["", "R"], ["R", "I"]])` should return `[[0, 1], [1, 1]]`.
```js
assert.deepEqual(getZoneViolations([["", "i"], ["", "R"], ["R", "I"]]).sort(), [[0, 1], [1, 1]]);
```
`getZoneViolations([["A", "i", "C"], ["A", "", "C"], ["R", "R", "I"]])` should return `[]`.
```js
assert.deepEqual(getZoneViolations([["A", "i", "C"], ["A", "", "C"], ["R", "R", "I"]]).sort(), []);
```
`getZoneViolations([["R", "R", "C", "R", "R"], ["R", "I", "C", "", "A"], ["R", "R", "", "i", "A"]])` should return `[[0, 1], [0, 2], [0, 3]]`.
```js
assert.deepEqual(getZoneViolations([["R", "R", "C", "R", "R"], ["R", "I", "C", "", "A"], ["R", "R", "", "i", "A"]]).sort(), [[0, 1], [0, 2], [0, 3]]);
```
`getZoneViolations([["R", "A", "A", "", "i", "i"], ["R", "I", "", "C", "i", "i"], ["R", "", "C", "C", "A", "A"], ["R", "R", "C", "I", "R", "R"]])` should return `[[2, 3], [2, 4], [3, 1], [3, 2]]`.
```js
assert.deepEqual(getZoneViolations([["R", "A", "A", "", "i", "i"], ["R", "I", "", "C", "i", "i"], ["R", "", "C", "C", "A", "A"], ["R", "R", "C", "I", "R", "R"]]).sort(), [[2, 3], [2, 4], [3, 1], [3, 2]]);
```
# --seed--
## --seed-contents--
```js
function getZoneViolations(grid) {
return grid;
}
```
# --solutions--
```js
function getZoneViolations(grid) {
const rules = {
"i": ["R", "I"],
"A": ["C"],
"R": ["i", "C"],
"I": ["i"],
"C": ["R", "A"],
"": []
};
const directions = [[-1, 0], [0, -1], [0, 1], [1, 0]];
const violations = [];
for (let row = 0; row < grid.length; row++) {
for (let col = 0; col < grid[row].length; col++) {
const cell = grid[row][col];
const forbidden = rules[cell];
for (const [dr, dc] of directions) {
const nr = row + dr;
const nc = col + dc;
if (nr >= 0 && nr < grid.length && nc >= 0 && nc < grid[row].length) {
if (forbidden.includes(grid[nr][nc])) {
violations.push([row, col]);
break;
}
}
}
}
}
return violations;
}
```

View File

@ -0,0 +1,91 @@
---
id: 6a0dcd03ee4e68698080ef6c
title: "Challenge 308: Credit Card Validator"
challengeType: 28
dashedName: challenge-308
---
# --description--
Given a string of digits for a credit card number, determine if it's a valid card number using the following method:
- Starting from the second-to-last digit, double every other digit moving left.
- If doubling a digit results in a number greater than 9, subtract 9.
- Sum all the digits (doubled and undoubled).
- If the total is divisible by 10, the number is valid.
# --hints--
`isValidCard("4532015112830366")` should return `true`.
```js
assert.isTrue(isValidCard("4532015112830366"));
```
`isValidCard("5425233430109903")` should return `true`.
```js
assert.isTrue(isValidCard("5425233430109903"));
```
`isValidCard("371449635398431")` should return `true`.
```js
assert.isTrue(isValidCard("371449635398431"));
```
`isValidCard("6011111111111117")` should return `true`.
```js
assert.isTrue(isValidCard("6011111111111117"));
```
`isValidCard("4532015112830367")` should return `false`.
```js
assert.isFalse(isValidCard("4532015112830367"));
```
`isValidCard("1234567890123456")` should return `false`.
```js
assert.isFalse(isValidCard("1234567890123456"));
```
`isValidCard("4532015112830368")` should return `false`.
```js
assert.isFalse(isValidCard("4532015112830368"));
```
# --seed--
## --seed-contents--
```js
function isValidCard(number) {
return number;
}
```
# --solutions--
```js
function isValidCard(number) {
let sum = 0;
for (let i = number.length - 1; i >= 0; i--) {
let digit = parseInt(number[i]);
if ((number.length - 1 - i) % 2 === 1) {
digit *= 2;
if (digit > 9) digit -= 9;
}
sum += digit;
}
return sum % 10 === 0;
}
```

View File

@ -0,0 +1,55 @@
---
id: 6a0dcd03ee4e68698080ef6d
title: "Challenge 309: Number Sort"
challengeType: 28
dashedName: challenge-309
---
# --description--
Given a string of numbers separated by commas, return an array of the numbers sorted from smallest to largest.
# --hints--
`sortNumbers("3,1,2")` should return `[1, 2, 3]`.
```js
assert.deepEqual(sortNumbers("3,1,2"), [1, 2, 3]);
```
`sortNumbers("5,3,8,1,9,2")` should return `[1, 2, 3, 5, 8, 9]`.
```js
assert.deepEqual(sortNumbers("5,3,8,1,9,2"), [1, 2, 3, 5, 8, 9]);
```
`sortNumbers("12,61,49,80,19,50,77,38")` should return `[12, 19, 38, 49, 50, 61, 77, 80]`.
```js
assert.deepEqual(sortNumbers("12,61,49,80,19,50,77,38"), [12, 19, 38, 49, 50, 61, 77, 80]);
```
`sortNumbers("0,6,-19,44,-2,7,0")` should return `[-19, -2, 0, 0, 6, 7, 44]`.
```js
assert.deepEqual(sortNumbers("0,6,-19,44,-2,7,0"), [-19, -2, 0, 0, 6, 7, 44]);
```
# --seed--
## --seed-contents--
```js
function sortNumbers(str) {
return str;
}
```
# --solutions--
```js
function sortNumbers(str) {
return str.split(",").map(Number).sort((a, b) => a - b);
}
```

View File

@ -0,0 +1,107 @@
---
id: 6a151d32d772271dd2448c2c
title: "Challenge 310: British to American"
challengeType: 28
dashedName: challenge-310
---
# --description--
Given a sentence, convert any British English spellings to their American English equivalents using the following lookup table and return the updated sentence:
| British | American |
| - | - |
| `"colour"` | `"color"` |
| `"flavour"` | `"flavor"` |
| `"honour"` | `"honor"` |
| `"neighbour"` | `"neighbor"` |
| `"labour"` | `"labor"` |
| `"humour"` | `"humor"` |
| `"centre"` | `"center"` |
| `"fibre"` | `"fiber"` |
| `"defence"` | `"defense"` |
| `"offence"` | `"offense"` |
| `"organise"` | `"organize"` |
| `"recognise"` | `"recognize"` |
| `"analyse"` | `"analyze"` |
- Replacements should be case-insensitive. For example, `"Colour"` should become `"Color"`.
- The input may contain words that build on the exact spelling of a root in the table that also need to be changed. For example, `"colouring"` should become `"coloring"`, and `"disorganised"` should become `"disorganized"`.
# --hints--
`britishToAmerican("I love the colour blue.")` should return `"I love the color blue."`
```js
assert.equal(britishToAmerican("I love the colour blue."), "I love the color blue.");
```
`britishToAmerican("The fibre optic cable is new.")` should return `"The fiber optic cable is new."`
```js
assert.equal(britishToAmerican("The fibre optic cable is new."), "The fiber optic cable is new.");
```
`britishToAmerican("It's an honour to meet someone with such humour.")` should return `"It's an honor to meet someone with such humor."`
```js
assert.equal(britishToAmerican("It's an honour to meet someone with such humour."), "It's an honor to meet someone with such humor.");
```
`britishToAmerican("The unrecognised artist analysed his colour palette at the centre.")` should return `"The unrecognized artist analyzed his color palette at the center."`
```js
assert.equal(britishToAmerican("The unrecognised artist analysed his colour palette at the centre."), "The unrecognized artist analyzed his color palette at the center.");
```
`britishToAmerican("The offence analysed, with organisation, the defence centre and recognised that the neighbouring labouror was humourous, flavourful, and colourful.")` should return `The offense analyzed, with organisation, the defense center and recognized that the neighboring laboror was humorous, flavorful, and colorful.`
```js
assert.equal(britishToAmerican("The offence analysed, with organisation, the defence centre and recognised that the neighbouring labouror was humourous, flavourful, and colourful."), "The offense analyzed, with organisation, the defense center and recognized that the neighboring laboror was humorous, flavorful, and colorful.");
```
# --seed--
## --seed-contents--
```js
function britishToAmerican(sentence) {
return sentence;
}
```
# --solutions--
```js
function britishToAmerican(sentence) {
const lookup = {
colour: "color",
flavour: "flavor",
honour: "honor",
neighbour: "neighbor",
labour: "labor",
humour: "humor",
centre: "center",
fibre: "fiber",
defence: "defense",
offence: "offense",
organise: "organize",
recognise: "recognize",
analyse: "analyze"
};
let result = sentence;
for (const [british, american] of Object.entries(lookup)) {
const regex = new RegExp(british, "gi");
result = result.replace(regex, match => {
return match[0] === match[0].toUpperCase()
? american[0].toUpperCase() + american.slice(1)
: american;
});
}
return result;
}
```

View File

@ -0,0 +1,107 @@
---
id: 6a151d32d772271dd2448c2d
title: "Challenge 311: Spellcaster"
challengeType: 28
dashedName: challenge-311
---
# --description--
Given a string of spell codes you are casting, calculate the total score.
Each character in the string represents a spell:
| Code | Spell| Category | Base Score |
| - | - | - | - |
| `"f"` | Fire | Destruction | 3 |
| `"l"` | Lightning | Destruction | 3 |
| `"i"` | Ice | Control | 2 |
| `"w"` | Wind | Control | 2 |
| `"h"` | Heal | Restoration | 1 |
| `"s"` | Shield | Restoration | 1 |
A combo multiplier is applied based on how many spells in a row have been cast from different categories:
- The first spell always scores at base value.
- Each consecutive spell from a different category than the previous increases the multiplier by 1.
- Casting a spell from the same category as the previous resets the multiplier back to 1.
- The score for each spell is its base score multiplied by the current multiplier.
Return the total score from the sequence of spells.
# --hints--
`cast("fihwl")` should return `33`.
```js
assert.equal(cast("fihwl"), 33);
```
`cast("lwswfi")` should return `45`.
```js
assert.equal(cast("lwswfi"), 45);
```
`cast("wislhfl")` should return `37`.
```js
assert.equal(cast("wislhfl"), 37);
```
`cast("sihwlih")` should return `50`.
```js
assert.equal(cast("sihwlih"), 50);
```
`cast("wishlfihwslwifihl")` should return `101`.
```js
assert.equal(cast("wishlfihwslwifihl"), 101);
```
# --seed--
## --seed-contents--
```js
function cast(spells) {
return spells;
}
```
# --solutions--
```js
function cast(spells) {
const lookup = {
f: { category: "destruction", score: 3 },
l: { category: "destruction", score: 3 },
i: { category: "control", score: 2 },
w: { category: "control", score: 2 },
h: { category: "restoration", score: 1 },
s: { category: "restoration", score: 1 }
};
let total = 0;
let multiplier = 1;
let prevCategory = null;
for (const spell of spells) {
const { category, score } = lookup[spell];
if (prevCategory && category !== prevCategory) {
multiplier++;
} else {
multiplier = 1;
}
total += score * multiplier;
prevCategory = category;
}
return total;
}
```

View File

@ -0,0 +1,82 @@
---
id: 6a0dcc730cb92a616f86f0bf
title: "Challenge 295: Schema Validator Part 1"
challengeType: 29
dashedName: challenge-295
---
# --description--
Given an object (JavaScript) or dictionary (Python), determine if it matches the following schema:
```json
{
username: string
}
```
- Extra keys are allowed
# --hints--
`is_valid_schema({"username": "bob"})` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "bob"}), True)`)
}})
```
`is_valid_schema({"username": "jen", "posts": 30})` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "jen", "posts": 30}), True)`)
}})
```
`is_valid_schema({"username": ""})` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": ""}), True)`)
}})
```
`is_valid_schema({"username": 7})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": 7}), False)`)
}})
```
`is_valid_schema({"posts": 25})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"posts": 25}), False)`)
}})
```
# --seed--
## --seed-contents--
```py
def is_valid_schema(obj):
return obj
```
# --solutions--
```py
def is_valid_schema(obj):
return isinstance(obj.get("username"), str)
```

View File

@ -0,0 +1,106 @@
---
id: 6a0dcc730cb92a616f86f0c0
title: "Challenge 296: Schema Validator Part 2"
challengeType: 29
dashedName: challenge-296
---
# --description--
Given an object (JavaScript) or dictionary (Python), determine if it matches the following schema:
```json
{
username: string,
posts: number,
verified: boolean
}
```
- Extra keys are allowed
# --hints--
`is_valid_schema({"username": "alice", "posts": 10, "verified": False})` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "alice", "posts": 10, "verified": False}), True)`)
}})
```
`is_valid_schema({"username": "carol", "posts": 15, "verified": True, "followers": 25})` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "carol", "posts": 15, "verified": True, "followers": 25}), True)`)
}})
```
`is_valid_schema({"username": "frank", "posts": "21", "verified": True})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "frank", "posts": "21", "verified": True}), False)`)
}})
```
`is_valid_schema({"username": "sam", "posts": 17, "verified": "false"})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "sam", "posts": 17, "verified": "false"}), False)`)
}})
```
`is_valid_schema({"username": "bill", "verified": True})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "bill", "verified": True}), False)`)
}})
```
`is_valid_schema({"username": "fred", "verified": True})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "fred", "verified": True}), False)`)
}})
```
`is_valid_schema({"username": 5, "posts": 10, "verified": True})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": 5, "posts": 10, "verified": True}), False)`)
}})
```
# --seed--
## --seed-contents--
```py
def is_valid_schema(obj):
return obj
```
# --solutions--
```py
def is_valid_schema(obj):
return (
isinstance(obj.get("username"), str) and
isinstance(obj.get("posts"), int) and not isinstance(obj.get("posts"), bool) and
isinstance(obj.get("verified"), bool)
)
```

View File

@ -0,0 +1,148 @@
---
id: 6a0dcc730cb92a616f86f0c1
title: "Challenge 297: Schema Validator Part 3"
challengeType: 29
dashedName: challenge-297
---
# --description--
Given an object (JavaScript) or dictionary (Python), determine if it matches the following schema:
```json
Roles = "user" | "creator" | "moderator" | "staff" | "admin"
{
username: string,
posts: number,
verified: boolean,
role: Roles
}
```
- The pipe (`|`) symbol means "or". `role` must be one of the listed `Roles` values.
- Extra keys are allowed
# --hints--
`is_valid_schema({"username": "henry", "posts": 0, "verified": True, "role": "staff"})` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "henry", "posts": 0, "verified": True, "role": "staff"}), True)`)
}})
```
`is_valid_schema({"username": "sara", "posts": 45, "verified": False, "role": "creator", "followers": 70})` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "sara", "posts": 45, "verified": False, "role": "creator", "followers": 70}), True)`)
}})
```
`is_valid_schema({"username": "penelope", "posts": 20, "verified": True, "role": "admin"})` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "penelope", "posts": 20, "verified": True, "role": "admin"}), True)`)
}})
```
`is_valid_schema({"username": "kevin", "posts": 0, "verified": False, "role": "user"})` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "kevin", "posts": 0, "verified": False, "role": "user"}), True)`)
}})
```
`is_valid_schema({"username": "george", "posts": 15, "verified": True, "role": "moderator"})` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "george", "posts": 15, "verified": True, "role": "moderator"}), True)`)
}})
```
`is_valid_schema({"username": "david", "posts": 0, "verified": False, "role": "guest"})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "david", "posts": 0, "verified": False, "role": "guest"}), False)`)
}})
```
`is_valid_schema({"username": "wendy", "posts": 10, "verified": True})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "wendy", "posts": 10, "verified": True}), False)`)
}})
```
`is_valid_schema({"username": "fabian", "posts": 1, "verified": True, "role": True})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "fabian", "posts": 1, "verified": True, "role": True}), False)`)
}})
```
`is_valid_schema({"username": 8, "posts": 1, "verified": True, "role": "user"})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": 8, "posts": 1, "verified": True, "role": "user"}), False)`)
}})
```
`is_valid_schema({"username": "penny", "posts": "10", "verified": True, "role": "staff"})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "penny", "posts": "10", "verified": True, "role": "staff"}), False)`)
}})
```
`is_valid_schema({"username": "john", "posts": "1", "verified": "true", "role": "admin"})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "john", "posts": "1", "verified": "true", "role": "admin"}), False)`)
}})
```
# --seed--
## --seed-contents--
```py
def is_valid_schema(obj):
return obj
```
# --solutions--
```py
def is_valid_schema(obj):
roles = ["user", "creator", "moderator", "staff", "admin"]
return (
isinstance(obj.get("username"), str) and
isinstance(obj.get("posts"), int) and not isinstance(obj.get("posts"), bool) and
isinstance(obj.get("verified"), bool) and
obj.get("role") in roles
)
```

View File

@ -0,0 +1,124 @@
---
id: 6a0dcc730cb92a616f86f0c2
title: "Challenge 298: Schema Validator Part 4"
challengeType: 29
dashedName: challenge-298
---
# --description--
Given an object (JavaScript) or dictionary (Python), determine if it matches the following schema:
```json
Roles = "user" | "creator" | "moderator" | "staff" | "admin"
{
username: string,
posts: number,
verified: boolean,
role: Roles,
supporter?: boolean
}
```
- The pipe (`|`) symbol means "or". `role` must be one of the listed `Roles` values.
- The question mark (`?`) after `supporter` means that the field is optional, but is the specified type if it exists.
- Extra keys are allowed
# --hints--
`is_valid_schema({"username": "vivian", "posts": 1, "verified": False, "role": "user", "supporter": True})` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "vivian", "posts": 1, "verified": False, "role": "user", "supporter": True}), True)`)
}})
```
`is_valid_schema({"username": "rudolph", "posts": 15, "verified": True, "role": "creator"})` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "rudolph", "posts": 15, "verified": True, "role": "creator"}), True)`)
}})
```
`is_valid_schema({"username": "hernandez", "posts": 35, "verified": True, "role": "moderator", "supporter": False, "followers": 55})` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "hernandez", "posts": 35, "verified": True, "role": "moderator", "supporter": False, "followers": 55}), True)`)
}})
```
`is_valid_schema({"username": "julia", "posts": 50, "verified": True, "role": "admin", "supporter": "true"})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "julia", "posts": 50, "verified": True, "role": "admin", "supporter": "true"}), False)`)
}})
```
`is_valid_schema({"username": "bernard", "posts": 0, "verified": True, "role": "friend", "supporter": True})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "bernard", "posts": 0, "verified": True, "role": "friend", "supporter": True}), False)`)
}})
```
`is_valid_schema({"username": "felix", "posts": 40, "verified": "yes", "role": "staff", "supporter": False})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "felix", "posts": 40, "verified": "yes", "role": "staff", "supporter": False}), False)`)
}})
```
`is_valid_schema({"username": "jimmy", "posts": True, "verified": False, "role": "creator", "supporter": True})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "jimmy", "posts": True, "verified": False, "role": "creator", "supporter": True}), False)`)
}})
```
`is_valid_schema({"username": True, "posts": 30, "verified": True, "role": "moderator", "supporter": False})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": True, "posts": 30, "verified": True, "role": "moderator", "supporter": False}), False)`)
}})
```
# --seed--
## --seed-contents--
```py
def is_valid_schema(obj):
return obj
```
# --solutions--
```py
def is_valid_schema(obj):
roles = ["user", "creator", "moderator", "staff", "admin"]
return (
isinstance(obj.get("username"), str) and
isinstance(obj.get("posts"), int) and not isinstance(obj.get("posts"), bool) and
isinstance(obj.get("verified"), bool) and
obj.get("role") in roles and
("supporter" not in obj or isinstance(obj["supporter"], bool))
)
```

View File

@ -0,0 +1,145 @@
---
id: 6a0dcc730cb92a616f86f0c3
title: "Challenge 299: Schema Validator Part 5"
challengeType: 29
dashedName: challenge-299
---
# --description--
Given an object (JavaScript) or dictionary (Python), determine if it matches the following schema:
```json
Roles = "user" | "creator" | "moderator" | "staff" | "admin"
{
username: string,
posts: number,
verified: boolean,
role: Roles,
supporter?: boolean,
badges: string[]
}
```
- The pipe (`|`) symbol means "or". `role` must be one of the listed `Roles` values.
- The question mark (`?`) after `supporter` means that the field is optional, but is the specified type if it exists.
- The brackets `[]` after `string` means that `badges` should be an array of strings (or empty).
- Extra keys are allowed
# --hints--
`is_valid_schema({"username": "gill", "posts": 12, "verified": False, "role": "creator", "supporter": False, "badges": ["early-adopter", "popular"]})` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "gill", "posts": 12, "verified": False, "role": "creator", "supporter": False, "badges": ["early-adopter", "popular"]}), True)`)
}})
```
`is_valid_schema({"username": "tonya", "posts": 299, "verified": True, "role": "moderator", "supporter": True, "badges": ["streak-master", "veteran"], "followers": 1233})` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "tonya", "posts": 299, "verified": True, "role": "moderator", "supporter": True, "badges": ["streak-master", "veteran"], "followers": 1233}), True)`)
}})
```
`is_valid_schema({"username": "zara", "posts": 0, "verified": False, "role": "user", "supporter": False, "badges": []})` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "zara", "posts": 0, "verified": False, "role": "user", "supporter": False, "badges": []}), True)`)
}})
```
`is_valid_schema({"username": "nicole", "posts": 65, "verified": True, "role": "admin", "supporter": False, "badges": ["first-post", 18]})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "nicole", "posts": 65, "verified": True, "role": "admin", "supporter": False, "badges": ["first-post", 18]}), False)`)
}})
```
`is_valid_schema({"username": "tim", "posts": 25, "verified": True, "role": "staff", "supporter": False})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "tim", "posts": 25, "verified": True, "role": "staff", "supporter": False}), False)`)
}})
```
`is_valid_schema({"username": "charlie", "posts": 0, "verified": False, "role": "user", "supporter": "no", "badges": ["first-post", "anniversary"]})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "charlie", "posts": 0, "verified": False, "role": "user", "supporter": "no", "badges": ["first-post", "anniversary"]}), False)`)
}})
```
`is_valid_schema({"username": "wanda", "posts": 15, "verified": True, "role": "friend", "supporter": True, "badges": ["popular"]})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "wanda", "posts": 15, "verified": True, "role": "friend", "supporter": True, "badges": ["popular"]}), False)`)
}})
```
`is_valid_schema({"username": "guy", "posts": 5, "verified": "false", "role": "staff", "supporter": True, "badges": ["helper"]})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "guy", "posts": 5, "verified": "false", "role": "staff", "supporter": True, "badges": ["helper"]}), False)`)
}})
```
`is_valid_schema({"username": "carrie", "verified": True, "role": "moderator", "supporter": True, "badges": ["helper", "sharer"]})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": "carrie", "verified": True, "role": "moderator", "supporter": True, "badges": ["helper", "sharer"]}), False)`)
}})
```
`is_valid_schema({"username": True, "posts": 75, "verified": True, "role": "creator", "supporter": True, "badges": ["veteran"]})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"username": True, "posts": 75, "verified": True, "role": "creator", "supporter": True, "badges": ["veteran"]}), False)`)
}})
```
# --seed--
## --seed-contents--
```py
def is_valid_schema(obj):
return obj
```
# --solutions--
```py
def is_valid_schema(obj):
roles = ["user", "creator", "moderator", "staff", "admin"]
return (
isinstance(obj.get("username"), str) and
isinstance(obj.get("posts"), int) and not isinstance(obj.get("posts"), bool) and
isinstance(obj.get("verified"), bool) and
obj.get("role") in roles and
("supporter" not in obj or isinstance(obj["supporter"], bool)) and
isinstance(obj.get("badges"), list) and all(isinstance(b, str) for b in obj["badges"])
)
```

View File

@ -0,0 +1,153 @@
---
id: 6a0dcc730cb92a616f86f0c4
title: "Challenge 300: Schema Validator Part 6"
challengeType: 29
dashedName: challenge-300
---
# --description--
Given an object (JavaScript) or dictionary (Python), determine if it matches the following schema:
```json
Roles = "user" | "creator" | "moderator" | "staff" | "admin"
UserProfile = {
username: string,
posts: number,
verified: boolean,
role: Roles,
supporter?: boolean,
badges: string[]
}
{
users: UserProfile[]
}
```
- The pipe (`|`) symbol means "or". role must be one of the listed `Roles` values.
- The question mark (`?`) after supporter means that the field is optional, but is the specified type if it exists.
- `UserProfile[]` denotes an array of `UserProfile` objects. An empty array is valid.
- Extra keys are allowed
# --hints--
`is_valid_schema({"users": [{"username": "ron", "posts": 14, "verified": True, "role": "creator", "badges": ["early-adopter"]}, {"username": "cher", "posts": 25, "verified": True, "role": "moderator", "supporter": True, "followers": 20, "badges": ["helper"]}]})` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"users": [{"username": "ron", "posts": 14, "verified": True, "role": "creator", "badges": ["early-adopter"]}, {"username": "cher", "posts": 25, "verified": True, "role": "moderator", "supporter": True, "followers": 20, "badges": ["helper"]}]}), True)`)
}})
```
`is_valid_schema({"users": []})` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"users": []}), True)`)
}})
```
`is_valid_schema({"users": {"username": "anne", "posts": 0, "verified": False, "role": "user", "supporter": False, "badges": []}})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"users": {"username": "anne", "posts": 0, "verified": False, "role": "user", "supporter": False, "badges": []}}), False)`)
}})
```
`is_valid_schema({"users": [{"username": "tony", "posts": 10, "verified": True, "role": "creator", "supporter": True, "badges": ["liked", 6]}]})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"users": [{"username": "tony", "posts": 10, "verified": True, "role": "creator", "supporter": True, "badges": ["liked", 6]}]}), False)`)
}})
```
`is_valid_schema({"users": [{"username": "ursula", "posts": 3, "verified": False, "role": "user", "supporter": "false", "badges": ["comeback"]}]})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"users": [{"username": "ursula", "posts": 3, "verified": False, "role": "user", "supporter": "false", "badges": ["comeback"]}]}), False)`)
}})
```
`is_valid_schema({"users": [{"username": "benny", "posts": 55, "verified": True, "role": "superstar", "supporter": True, "badges": ["veteran"]}]})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"users": [{"username": "benny", "posts": 55, "verified": True, "role": "superstar", "supporter": True, "badges": ["veteran"]}]}), False)`)
}})
```
`is_valid_schema({"users": [{"username": "chase", "posts": 1, "verified": "yes", "role": "staff", "supporter": False, "badges": ["superstar"]}]})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"users": [{"username": "chase", "posts": 1, "verified": "yes", "role": "staff", "supporter": False, "badges": ["superstar"]}]}), False)`)
}})
```
`is_valid_schema({"users": [{"username": "carla", "posts": "10", "verified": False, "role": "user", "supporter": False, "badges": ["newbie"]}]})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"users": [{"username": "carla", "posts": "10", "verified": False, "role": "user", "supporter": False, "badges": ["newbie"]}]}), False)`)
}})
```
`is_valid_schema({"users": [{"posts": 4, "verified": False, "role": "admin", "supporter": False, "badges": ["superuser", "veteran"]}]})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"users": [{"posts": 4, "verified": False, "role": "admin", "supporter": False, "badges": ["superuser", "veteran"]}]}), False)`)
}})
```
`is_valid_schema({"users": [{"username": "harold", "posts": 80, "verified": True, "role": "creator", "supporter": True, "badges": ["liked", "hero"]}, {"username": "kim", "posts": 11, "verified": False, "role": "admin", "supporter": True, "badges": ["first"]}, {}]})` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_schema({"users": [{"username": "harold", "posts": 80, "verified": True, "role": "creator", "supporter": True, "badges": ["liked", "hero"]}, {"username": "kim", "posts": 11, "verified": False, "role": "admin", "supporter": True, "badges": ["first"]}, {}]}), False)`)
}})
```
# --seed--
## --seed-contents--
```py
def is_valid_schema(obj):
return obj
```
# --solutions--
```py
def is_valid_schema(obj):
roles = ["user", "creator", "moderator", "staff", "admin"]
def is_valid_user(user):
return (
isinstance(user.get("username"), str) and
isinstance(user.get("posts"), int) and not isinstance(user.get("posts"), bool) and
isinstance(user.get("verified"), bool) and
user.get("role") in roles and
("supporter" not in user or isinstance(user["supporter"], bool)) and
isinstance(user.get("badges"), list) and all(isinstance(b, str) for b in user["badges"])
)
return isinstance(obj.get("users"), list) and all(is_valid_user(u) for u in obj["users"])
```

View File

@ -0,0 +1,77 @@
---
id: 6a0dcc730cb92a616f86f0c5
title: "Challenge 301: Last Load"
challengeType: 29
dashedName: challenge-301
---
# --description--
Given the number of scoops of laundry detergent you have remaining and an array of how many scoops you used in each of the previous days, return the number of full days of detergent you have remaining.
Calculate your average daily usage from the usage history and assume that amount of usage each day going forward.
# --hints--
`last_load_date(10, [2, 2, 2, 2, 2, 2, 2])` should return `5`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(last_load_date(10, [2, 2, 2, 2, 2, 2, 2]), 5)`)
}})
```
`last_load_date(16, [2, 3, 0, 3, 4, 2, 1])` should return `7`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(last_load_date(16, [2, 3, 0, 3, 4, 2, 1]), 7)`)
}})
```
`last_load_date(33, [5, 0, 4, 3, 3, 2])` should return `11`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(last_load_date(33, [5, 0, 4, 3, 3, 2]), 11)`)
}})
```
`last_load_date(50, [2, 0, 2, 9, 12, 0, 2])` should return `12`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(last_load_date(50, [2, 0, 2, 9, 12, 0, 2]), 12)`)
}})
```
`last_load_date(20, [13, 9, 12, 10, 8])` should return `1`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(last_load_date(20, [13, 9, 12, 10, 8]), 1)`)
}})
```
# --seed--
## --seed-contents--
```py
def last_load_date(scoops, usage):
return scoops
```
# --solutions--
```py
def last_load_date(scoops, usage):
avg = sum(usage) / len(usage)
return int(scoops / avg)
```

View File

@ -0,0 +1,124 @@
---
id: 6a0dcd03ee4e68698080ef66
title: "Challenge 302: Jet Lagged"
challengeType: 29
dashedName: challenge-302
---
# --description--
Given a departure city, an arrival city, a flight duration in hours, and a direction of travel, return the number of jet lag hours the traveller is experiencing.
The given cities will be from the following list that includes their UTC offset:
| City | Offset |
| - | - |
| `"Los Angeles"` | -8 |
| `"New York"` | -5 |
| `"London"` | 0 |
| `"Istanbul"` | +3 |
| `"Dubai"` | +4 |
| `"Hong Kong"` | +8 |
| `"Tokyo"` | +9 |
To calculate jet lag hours:
1. Find the timezone difference in hours between the two cities.
2. Determine the direction multiplier. If travelling `"east"`, it's 1.5, otherwise, it's 1.0.
3. Get the jet lag hours with the formula: timezone difference + (flight duration * 0.1) * direction multiplier
Return the jet lag hours rounded to one decimal place.
# --hints--
`get_jet_lag_hours("Istanbul", "Hong Kong", 10, "east")` should return `6.5`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(get_jet_lag_hours("Istanbul", "Hong Kong", 10, "east"), 6.5)`)
}})
```
`get_jet_lag_hours("London", "New York", 8, "west")` should return `5.8`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(get_jet_lag_hours("London", "New York", 8, "west"), 5.8)`)
}})
```
`get_jet_lag_hours("Hong Kong", "Tokyo", 4, "east")` should return `1.6`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(get_jet_lag_hours("Hong Kong", "Tokyo", 4, "east"), 1.6)`)
}})
```
`get_jet_lag_hours("Dubai", "London", 7, "west")` should return `4.7`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(get_jet_lag_hours("Dubai", "London", 7, "west"), 4.7)`)
}})
```
`get_jet_lag_hours("Los Angeles", "Hong Kong", 15, "west")` should return `17.5`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(get_jet_lag_hours("Los Angeles", "Hong Kong", 15, "west"), 17.5)`)
}})
```
`get_jet_lag_hours("Tokyo", "Dubai", 9, "west")` should return `5.9`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(get_jet_lag_hours("Tokyo", "Dubai", 9, "west"), 5.9)`)
}})
```
`get_jet_lag_hours("New York", "Istanbul", 10, "east")` should return `9.5`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(get_jet_lag_hours("New York", "Istanbul", 10, "east"), 9.5)`)
}})
```
# --seed--
## --seed-contents--
```py
def get_jet_lag_hours(departure_city, arrival_city, flight_duration, direction):
return departure_city
```
# --solutions--
```py
def get_jet_lag_hours(departure_city, arrival_city, flight_duration, direction):
offsets = {
"Los Angeles": -8,
"New York": -5,
"London": 0,
"Istanbul": 3,
"Dubai": 4,
"Hong Kong": 8,
"Tokyo": 9
}
timezone_diff = abs(offsets[arrival_city] - offsets[departure_city])
multiplier = 1.5 if direction == "east" else 1.0
score = timezone_diff + (flight_duration * 0.1) * multiplier
return round(score, 1)
```

View File

@ -0,0 +1,94 @@
---
id: 6a0dcd03ee4e68698080ef67
title: "Challenge 303: Roommates"
challengeType: 29
dashedName: challenge-303
---
# --description--
Given an array of people and their roommate group, return the room assignments for a hotel stay using the following rules:
- Each person has a `name` and a `group` property:
```json
[
{ "name": "Alice", "group": "A" },
{ "name": "Bob", "group": "B" },
{ "name": "Carol", "group": "A" }
]
```
- People can only share a room with someone from the same group and are paired in the order they are given.
- Return an array of strings with names separated by `" and "` for a shared room, and just the name for a solo room. Names must appear in the order they were paired. For the example above, return `["Alice and Carol", "Bob"]`.
# --hints--
`get_roommates([{ "name": "Alice", "group": "A" }, { "name": "Bob", "group": "B" }, { "name": "Carol", "group": "A" }])` should return `["Alice and Carol", "Bob"]`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(sorted(get_roommates([{"name": "Alice", "group": "A"}, {"name": "Bob", "group": "B"}, {"name": "Carol", "group": "A"}])), sorted(["Alice and Carol", "Bob"]))`)
}})
```
`get_roommates([{ "name": "John", "group": "C" }, { "name": "Julia", "group": "C" }, { "name": "Jim", "group": "C" }])` should return `["John and Julia", "Jim"]`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(sorted(get_roommates([{"name": "John", "group": "C"}, {"name": "Julia", "group": "C"}, {"name": "Jim", "group": "C"}])), sorted(["John and Julia", "Jim"]))`)
}})
```
`get_roommates([{ "name": "Adam", "group": "D" }, { "name": "Abraham", "group": "E" }, { "name": "Austin", "group": "E" }, { "name": "Augustus", "group": "D" }, { "name": "Angelica", "group": "D" }, { "name": "Aaron", "group": "E" }])` should return `["Adam and Augustus", "Angelica", "Abraham and Austin", "Aaron"]`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(sorted(get_roommates([{"name": "Adam", "group": "D"}, {"name": "Abraham", "group": "E"}, {"name": "Austin", "group": "E"}, {"name": "Augustus", "group": "D"}, {"name": "Angelica", "group": "D"}, {"name": "Aaron", "group": "E"}])), sorted(["Adam and Augustus", "Angelica", "Abraham and Austin", "Aaron"]))`)
}})
```
`get_roommates([{ "name": "Frank", "group": "A" }, { "name": "Emitt", "group": "B" }, { "name": "Daria", "group": "F" }, { "name": "Charles", "group": "D" }, { "name": "Bailey", "group": "A" }, { "name": "Albert", "group": "F" }])` should return `["Frank and Bailey", "Emitt", "Daria and Albert", "Charles"]`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(sorted(get_roommates([{"name": "Frank", "group": "A"}, {"name": "Emitt", "group": "B"}, {"name": "Daria", "group": "F"}, {"name": "Charles", "group": "D"}, {"name": "Bailey", "group": "A"}, {"name": "Albert", "group": "F"}])), sorted(["Frank and Bailey", "Emitt", "Daria and Albert", "Charles"]))`)
}})
```
`get_roommates([{ "name": "Kevin", "group": "A" }, { "name": "Yuri", "group": "A" }, { "name": "Hugo", "group": "B" }, { "name": "Violet", "group": "A" }, { "name": "Brett", "group": "A" }, { "name": "Wayne", "group": "B" }])` should return `["Kevin and Yuri", "Violet and Brett", "Hugo and Wayne"]`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(sorted(get_roommates([{"name": "Kevin", "group": "A"}, {"name": "Yuri", "group": "A"}, {"name": "Hugo", "group": "B"}, {"name": "Violet", "group": "A"}, {"name": "Brett", "group": "A"}, {"name": "Wayne", "group": "B"}])), sorted(["Kevin and Yuri", "Violet and Brett", "Hugo and Wayne"]))`)
}})
```
# --seed--
## --seed-contents--
```py
def get_roommates(people):
return people
```
# --solutions--
```py
def get_roommates(people):
groups = {}
for person in people:
groups.setdefault(person["group"], []).append(person["name"])
result = []
for members in groups.values():
for i in range(0, len(members), 2):
result.append(" and ".join(members[i:i + 2]))
return result
```

View File

@ -0,0 +1,85 @@
---
id: 6a0dcd03ee4e68698080ef68
title: "Challenge 304: Itinerary Arrangements"
challengeType: 29
dashedName: challenge-304
---
# --description--
Given an array of at least two optional stops for a day trip, return the number of valid itinerary arrangements.
The itinerary always includes `"breakfast"`, `"lunch"`, and `"dinner"`, these will not be passed in as arguments. The optional stops can be placed anywhere in the itinerary, subject to the following rules:
- `"breakfast"` is always first, with at least one stop before `"lunch"`.
- `"lunch"` must appear before `"dinner"`, with at least one stop in between.
- At most, one optional stop may appear after `"dinner"`.
Return the number of valid arrangements.
# --hints--
`get_itinerary_count(["library", "park"])` should return `2`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(get_itinerary_count(["library", "park"]), 2)`)
}})
```
`get_itinerary_count(["library", "park", "arcade"])` should return `18`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(get_itinerary_count(["library", "park", "arcade"]), 18)`)
}})
```
`get_itinerary_count(["library", "park", "arcade", "store"])` should return `120`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(get_itinerary_count(["library", "park", "arcade", "store"]), 120)`)
}})
```
`get_itinerary_count(["library", "park", "arcade", "store", "cafe"])` should return `840`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(get_itinerary_count(["library", "park", "arcade", "store", "cafe"]), 840)`)
}})
```
`get_itinerary_count(["library", "park", "arcade", "store", "cafe", "market", "museum"])` should return `55440`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(get_itinerary_count(["library", "park", "arcade", "store", "cafe", "market", "museum"]), 55440)`)
}})
```
# --seed--
## --seed-contents--
```py
def get_itinerary_count(stops):
return stops
```
# --solutions--
```py
from math import factorial
def get_itinerary_count(stops):
n = len(stops)
return (2 * n - 3) * factorial(n)
```

View File

@ -0,0 +1,81 @@
---
id: 6a0dcd03ee4e68698080ef69
title: "Challenge 305: Idea Rankings"
challengeType: 29
dashedName: challenge-305
---
# --description--
Given a 2D array where each inner array contains (in this order) an idea name, an optimistic estimate, a realistic estimate, and a pessimistic estimate (in days), return an array of the idea names sorted by expected time to completion, shortest first.
Calculate the expected time to completion for each idea using the following formula:
- `expected = ((optimistic + 4 * realistic + pessimistic) / 6) * length of idea name`
# --hints--
`analyze_ideas([["Add logging", 2, 5, 15], ["SEO optimization", 4, 8, 20], ["Fix bug", 1, 3, 5]])` should return `["Fix bug", "Add logging", "SEO optimization"]`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(analyze_ideas([["Add logging", 2, 5, 15], ["SEO optimization", 4, 8, 20], ["Fix bug", 1, 3, 5]]), ["Fix bug", "Add logging", "SEO optimization"])`)
}})
```
`analyze_ideas([["Dark mode", 1, 3, 8], ["Real-time collaboration feature", 6, 12, 20], ["Add tooltip", 1, 2, 4]])` should return `["Add tooltip", "Dark mode", "Real-time collaboration feature"]`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(analyze_ideas([["Dark mode", 1, 3, 8], ["Real-time collaboration feature", 6, 12, 20], ["Add tooltip", 1, 2, 4]]), ["Add tooltip", "Dark mode", "Real-time collaboration feature"])`)
}})
```
`analyze_ideas([["Update user profile page", 3, 7, 14], ["Add pagination", 2, 5, 10], ["Add tags", 2, 3, 6], ["Fix login bug", 1, 4, 8]])` should return `["Add tags", "Fix login bug", "Add pagination", "Update user profile page"]`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(analyze_ideas([["Update user profile page", 3, 7, 14], ["Add pagination", 2, 5, 10], ["Add tags", 2, 3, 6], ["Fix login bug", 1, 4, 8]]), ["Add tags", "Fix login bug", "Add pagination", "Update user profile page"])`)
}})
```
`analyze_ideas([["Migrate database", 14, 25, 40], ["Add chat assistant", 8, 15, 24], ["Redesign onboarding flow", 3, 7, 13], ["Add language support", 6, 11, 18]])` should return `["Redesign onboarding flow", "Add language support", "Add chat assistant", "Migrate database"]`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(analyze_ideas([["Migrate database", 14, 25, 40], ["Add chat assistant", 8, 15, 24], ["Redesign onboarding flow", 3, 7, 13], ["Add language support", 6, 11, 18]]), ["Redesign onboarding flow", "Add language support", "Add chat assistant", "Migrate database"])`)
}})
```
`analyze_ideas([["Add email notifications", 3, 7, 10], ["Migrate deployment flow", 6, 10, 16], ["Add push notifications", 2, 6, 10], ["Optimize continuous integration", 5, 8, 15], ["Analyze user patterns", 5, 10, 18], ["Create onboarding curriculum", 6, 15, 25]])` should return `["Add push notifications", "Add email notifications", "Analyze user patterns", "Migrate deployment flow", "Optimize continuous integration", "Create onboarding curriculum"]`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(analyze_ideas([["Add email notifications", 3, 7, 10], ["Migrate deployment flow", 6, 10, 16], ["Add push notifications", 2, 6, 10], ["Optimize continuous integration", 5, 8, 15], ["Analyze user patterns", 5, 10, 18], ["Create onboarding curriculum", 6, 15, 25]]), ["Add push notifications", "Add email notifications", "Analyze user patterns", "Migrate deployment flow", "Optimize continuous integration", "Create onboarding curriculum"])`)
}})
```
# --seed--
## --seed-contents--
```py
def analyze_ideas(ideas):
return ideas
```
# --solutions--
```py
def analyze_ideas(ideas):
def expected(idea):
name, optimistic, realistic, pessimistic = idea
return ((optimistic + 4 * realistic + pessimistic) / 6) * len(name)
return [idea[0] for idea in sorted(ideas, key=expected)]
```

View File

@ -0,0 +1,76 @@
---
id: 6a0dcd03ee4e68698080ef6a
title: "Challenge 306: HTML Content Extractor"
challengeType: 29
dashedName: challenge-306
---
# --description--
Given a string of HTML, return the plain text content with all tags removed.
# --hints--
`extract_content('<p>hello world</p>')` should return `"hello world"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(extract_content('<p>hello world</p>'), "hello world")`)
}})
```
`extract_content('<p>hello <span>world</span></p>')` should return `"hello world"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(extract_content('<p>hello <span>world</span></p>'), "hello world")`)
}})
```
`extract_content('<a href="example.com">Click me</a>')` should return `"Click me"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(extract_content('<a href="example.com">Click me</a>'), "Click me")`)
}})
```
`extract_content('<p><button onClick="learnToCode()">Learn</button> to <code>code<code> <br/>for <strong>free</strong> <br/>on <a href="https://freecodecamp.org/" target="_blank"><span class="highlight">freecodecamp</span>.org</a>')` should return `"Learn to code for free on freecodecamp.org"`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(extract_content('<p><button onClick="learnToCode()">Learn</button> to <code>code<code> <br/>for <strong>free</strong> <br/>on <a href="https://freecodecamp.org/" target="_blank"><span class="highlight">freecodecamp</span>.org</a>'), "Learn to code for free on freecodecamp.org")`)
}})
```
`extract_content('<div class="container"><h1 id="title">Welcome to <strong>My</strong> Website.</h1><p>This is a <a href="https://example.com" target="_blank">link</a> to something <em>really</em> <span class="highlight">important</span>.</p><ul><li>Item <strong>one</strong></li><li>Item <em>two</em></li><li>Item three</li></ul><img src="pic.jpg" alt="A picture"/><p class="footer">Contact us at <a href="mailto:hello@example.com">hello@example.com</a> for <span>more <strong>info</strong></span>.</p></div>')` should return `"Welcome to My Website.This is a link to something really important.Item oneItem twoItem threeContact us at hello@example.com for more info."`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(extract_content('<div class="container"><h1 id="title">Welcome to <strong>My</strong> Website.</h1><p>This is a <a href="https://example.com" target="_blank">link</a> to something <em>really</em> <span class="highlight">important</span>.</p><ul><li>Item <strong>one</strong></li><li>Item <em>two</em></li><li>Item three</li></ul><img src="pic.jpg" alt="A picture"/><p class="footer">Contact us at <a href="mailto:hello@example.com">hello@example.com</a> for <span>more <strong>info</strong></span>.</p></div>'), "Welcome to My Website.This is a link to something really important.Item oneItem twoItem threeContact us at hello@example.com for more info.")`)
}})
```
# --seed--
## --seed-contents--
```py
def extract_content(html):
return html
```
# --solutions--
```py
import re
def extract_content(html):
return re.sub(r'<[^>]*>', '', html).strip()
```

View File

@ -0,0 +1,112 @@
---
id: 6a0dcd03ee4e68698080ef6b
title: "Challenge 307: Zoning Regulations"
challengeType: 29
dashedName: challenge-307
---
# --description--
Given a 2D grid (array of arrays) representing a city's building layout, return the coordinates of all buildings that are violating zoning rules.
Each cell in the grid contains one of the labels from the table below. A building is in violation if any of its (up to) 4 neighbors, horizontal or vertical, are a type it cannot be adjacent to.
| Label | Type | Cannot be adjacent to |
| - | - | - |
| `"i"` | industrial | `"R"`, `"I"` |
| `"A"` | Agricultural | `"C"` |
| `"R"` | Residential | `"i"`, `"C"` |
| `"I"` | Institutional | `"i"` |
| `"C"` | Commercial | `"R"`, `"A"` |
| `""` (empty string) | undeveloped | no restrictions |
Return the coordinates of all violating cells as an array of `[row, col]` pairs, in any order. If no violations exist, return an empty array.
# --hints--
`get_zone_violations([["R", "C"], ["", "C"]])` should return `[[0, 0], [0, 1]]`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(sorted(get_zone_violations([["R", "C"], ["", "C"]])), [[0, 0], [0, 1]])`)
}})
```
`get_zone_violations([["", "i"], ["", "R"], ["R", "I"]])` should return `[[0, 1], [1, 1]]`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(sorted(get_zone_violations([["", "i"], ["", "R"], ["R", "I"]])), [[0, 1], [1, 1]])`)
}})
```
`get_zone_violations([["A", "i", "C"], ["A", "", "C"], ["R", "R", "I"]])` should return `[]`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(sorted(get_zone_violations([["A", "i", "C"], ["A", "", "C"], ["R", "R", "I"]])), [])`)
}})
```
`get_zone_violations([["R", "R", "C", "R", "R"], ["R", "I", "C", "", "A"], ["R", "R", "", "i", "A"]])` should return `[[0, 1], [0, 2], [0, 3]]`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(sorted(get_zone_violations([["R", "R", "C", "R", "R"], ["R", "I", "C", "", "A"], ["R", "R", "", "i", "A"]])), [[0, 1], [0, 2], [0, 3]])`)
}})
```
`get_zone_violations([["R", "A", "A", "", "i", "i"], ["R", "I", "", "C", "i", "i"], ["R", "", "C", "C", "A", "A"], ["R", "R", "C", "I", "R", "R"]])` should return `[[2, 3], [2, 4], [3, 1], [3, 2]]`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(sorted(get_zone_violations([["R", "A", "A", "", "i", "i"], ["R", "I", "", "C", "i", "i"], ["R", "", "C", "C", "A", "A"], ["R", "R", "C", "I", "R", "R"]])), [[2, 3], [2, 4], [3, 1], [3, 2]])`)
}})
```
# --seed--
## --seed-contents--
```py
def get_zone_violations(grid):
return grid
```
# --solutions--
```py
def get_zone_violations(grid):
rules = {
"i": ["R", "I"],
"A": ["C"],
"R": ["i", "C"],
"I": ["i"],
"C": ["R", "A"],
"": []
}
directions = [[-1, 0], [0, -1], [0, 1], [1, 0]]
violations = []
for row in range(len(grid)):
for col in range(len(grid[row])):
cell = grid[row][col]
forbidden = rules[cell]
for dr, dc in directions:
nr = row + dr
nc = col + dc
if 0 <= nr < len(grid) and 0 <= nc < len(grid[row]):
if grid[nr][nc] in forbidden:
violations.append([row, col])
break
return violations
```

View File

@ -0,0 +1,105 @@
---
id: 6a0dcd03ee4e68698080ef6c
title: "Challenge 308: Credit Card Validator"
challengeType: 29
dashedName: challenge-308
---
# --description--
Given a string of digits for a credit card number, determine if it's a valid card number using the following method:
- Starting from the second-to-last digit, double every other digit moving left.
- If doubling a digit results in a number greater than 9, subtract 9.
- Sum all the digits (doubled and undoubled).
- If the total is divisible by 10, the number is valid.
# --hints--
`is_valid_card("4532015112830366")` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_card("4532015112830366"), True)`)
}})
```
`is_valid_card("5425233430109903")` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_card("5425233430109903"), True)`)
}})
```
`is_valid_card("371449635398431")` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_card("371449635398431"), True)`)
}})
```
`is_valid_card("6011111111111117")` should return `True`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_card("6011111111111117"), True)`)
}})
```
`is_valid_card("4532015112830367")` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_card("4532015112830367"), False)`)
}})
```
`is_valid_card("1234567890123456")` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_card("1234567890123456"), False)`)
}})
```
`is_valid_card("4532015112830368")` should return `False`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_card("4532015112830368"), False)`)
}})
```
# --seed--
## --seed-contents--
```py
def is_valid_card(number):
return number
```
# --solutions--
```py
def is_valid_card(number):
total = 0
for i, digit in enumerate(reversed(number)):
d = int(digit)
if i % 2 == 1:
d *= 2
if d > 9:
d -= 9
total += d
return total % 10 == 0
```

View File

@ -0,0 +1,65 @@
---
id: 6a0dcd03ee4e68698080ef6d
title: "Challenge 309: Number Sort"
challengeType: 29
dashedName: challenge-309
---
# --description--
Given a string of numbers separated by commas, return an array of the numbers sorted from smallest to largest.
# --hints--
`sort_numbers("3,1,2")` should return `[1, 2, 3]`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(sort_numbers("3,1,2"), [1, 2, 3])`)
}})
```
`sort_numbers("5,3,8,1,9,2")` should return `[1, 2, 3, 5, 8, 9]`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(sort_numbers("5,3,8,1,9,2"), [1, 2, 3, 5, 8, 9])`)
}})
```
`sort_numbers("12,61,49,80,19,50,77,38")` should return `[12, 19, 38, 49, 50, 61, 77, 80]`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(sort_numbers("12,61,49,80,19,50,77,38"), [12, 19, 38, 49, 50, 61, 77, 80])`)
}})
```
`sort_numbers("0,6,-19,44,-2,7,0")` should return `[-19, -2, 0, 0, 6, 7, 44]`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(sort_numbers("0,6,-19,44,-2,7,0"), [-19, -2, 0, 0, 6, 7, 44])`)
}})
```
# --seed--
## --seed-contents--
```py
def sort_numbers(s):
return s
```
# --solutions--
```py
def sort_numbers(s):
return sorted(int(x) for x in s.split(","))
```

View File

@ -0,0 +1,117 @@
---
id: 6a151d32d772271dd2448c2c
title: "Challenge 310: British to American"
challengeType: 29
dashedName: challenge-310
---
# --description--
Given a sentence, convert any British English spellings to their American English equivalents using the following lookup table and return the updated sentence:
| British | American |
| - | - |
| `"colour"` | `"color"` |
| `"flavour"` | `"flavor"` |
| `"honour"` | `"honor"` |
| `"neighbour"` | `"neighbor"` |
| `"labour"` | `"labor"` |
| `"humour"` | `"humor"` |
| `"centre"` | `"center"` |
| `"fibre"` | `"fiber"` |
| `"defence"` | `"defense"` |
| `"offence"` | `"offense"` |
| `"organise"` | `"organize"` |
| `"recognise"` | `"recognize"` |
| `"analyse"` | `"analyze"` |
- Replacements should be case-insensitive. For example, `"Colour"` should become `"Color"`.
- The input may contain words that build on the exact spelling of a root in the table that also need to be changed. For example, `"colouring"` should become `"coloring"`, and `"disorganised"` should become `"disorganized"`.
# --hints--
`british_to_american("I love the colour blue.")` should return `"I love the color blue."`
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(british_to_american("I love the colour blue."), "I love the color blue.")`)
}})
```
`british_to_american("The fibre optic cable is new.")` should return `"The fiber optic cable is new."`
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(british_to_american("The fibre optic cable is new."), "The fiber optic cable is new.")`)
}})
```
`british_to_american("It's an honour to meet someone with such humour.")` should return `"It's an honor to meet someone with such humor."`
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(british_to_american("It's an honour to meet someone with such humour."), "It's an honor to meet someone with such humor.")`)
}})
```
`british_to_american("The unrecognised artist analysed his colour palette at the centre.")` should return `"The unrecognized artist analyzed his color palette at the center."`
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(british_to_american("The unrecognised artist analysed his colour palette at the centre."), "The unrecognized artist analyzed his color palette at the center.")`)
}})
```
`british_to_american("The offence analysed, with organisation, the defence centre and recognised that the neighbouring labouror was humourous, flavourful, and colourful.")` should return `The offense analyzed, with organisation, the defense center and recognized that the neighboring laboror was humorous, flavorful, and colorful.`
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(british_to_american("The offence analysed, with organisation, the defence centre and recognised that the neighbouring labouror was humourous, flavourful, and colourful."), "The offense analyzed, with organisation, the defense center and recognized that the neighboring laboror was humorous, flavorful, and colorful.")`)
}})
```
# --seed--
## --seed-contents--
```py
def british_to_american(sentence):
return sentence
```
# --solutions--
```py
import re
def british_to_american(sentence):
lookup = {
"colour": "color",
"flavour": "flavor",
"honour": "honor",
"neighbour": "neighbor",
"labour": "labor",
"humour": "humor",
"centre": "center",
"fibre": "fiber",
"defence": "defense",
"offence": "offense",
"organise": "organize",
"recognise": "recognize",
"analyse": "analyze"
}
result = sentence
for british, american in lookup.items():
def replace(match, american=american):
return american[0].upper() + american[1:] if match.group()[0].isupper() else american
result = re.sub(british, replace, result, flags=re.IGNORECASE)
return result
```

View File

@ -0,0 +1,118 @@
---
id: 6a151d32d772271dd2448c2d
title: "Challenge 311: Spellcaster"
challengeType: 29
dashedName: challenge-311
---
# --description--
Given a string of spell codes you are casting, calculate the total score.
Each character in the string represents a spell:
| Code | Spell| Category | Base Score |
| - | - | - | - |
| `"f"` | Fire | Destruction | 3 |
| `"l"` | Lightning | Destruction | 3 |
| `"i"` | Ice | Control | 2 |
| `"w"` | Wind | Control | 2 |
| `"h"` | Heal | Restoration | 1 |
| `"s"` | Shield | Restoration | 1 |
A combo multiplier is applied based on how many spells in a row have been cast from different categories:
- The first spell always scores at base value.
- Each consecutive spell from a different category than the previous increases the multiplier by 1.
- Casting a spell from the same category as the previous resets the multiplier back to 1.
- The score for each spell is its base score multiplied by the current multiplier.
Return the total score from the sequence of spells.
# --hints--
`cast("fihwl")` should return `33`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(cast("fihwl"), 33)`)
}})
```
`cast("lwswfi")` should return `45`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(cast("lwswfi"), 45)`)
}})
```
`cast("wislhfl")` should return `37`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(cast("wislhfl"), 37)`)
}})
```
`cast("sihwlih")` should return `50`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(cast("sihwlih"), 50)`)
}})
```
`cast("wishlfihwslwifihl")` should return `101`.
```js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(cast("wishlfihwslwifihl"), 101)`)
}})
```
# --seed--
## --seed-contents--
```py
def cast(spells):
return spells
```
# --solutions--
```py
def cast(spells):
lookup = {
"f": ("destruction", 3),
"l": ("destruction", 3),
"i": ("control", 2),
"w": ("control", 2),
"h": ("restoration", 1),
"s": ("restoration", 1)
}
total = 0
multiplier = 1
prev_category = None
for spell in spells:
category, score = lookup[spell]
if prev_category and category != prev_category:
multiplier += 1
else:
multiplier = 1
total += score * multiplier
prev_category = category
return total
```

View File

@ -1181,6 +1181,74 @@
{
"id": "69f90c1329a94b37e2a2086d",
"title": "Challenge 294: Parentheses Combinations"
},
{
"id": "6a0dcc730cb92a616f86f0bf",
"title": "Challenge 295: Schema Validator Part 1"
},
{
"id": "6a0dcc730cb92a616f86f0c0",
"title": "Challenge 296: Schema Validator Part 2"
},
{
"id": "6a0dcc730cb92a616f86f0c1",
"title": "Challenge 297: Schema Validator Part 3"
},
{
"id": "6a0dcc730cb92a616f86f0c2",
"title": "Challenge 298: Schema Validator Part 4"
},
{
"id": "6a0dcc730cb92a616f86f0c3",
"title": "Challenge 299: Schema Validator Part 5"
},
{
"id": "6a0dcc730cb92a616f86f0c4",
"title": "Challenge 300: Schema Validator Part 6"
},
{
"id": "6a0dcc730cb92a616f86f0c5",
"title": "Challenge 301: Last Load"
},
{
"id": "6a0dcd03ee4e68698080ef66",
"title": "Challenge 302: Jet Lagged"
},
{
"id": "6a0dcd03ee4e68698080ef67",
"title": "Challenge 303: Roommates"
},
{
"id": "6a0dcd03ee4e68698080ef68",
"title": "Challenge 304: Itinerary Arrangements"
},
{
"id": "6a0dcd03ee4e68698080ef69",
"title": "Challenge 305: Idea Rankings"
},
{
"id": "6a0dcd03ee4e68698080ef6a",
"title": "Challenge 306: HTML Content Extractor"
},
{
"id": "6a0dcd03ee4e68698080ef6b",
"title": "Challenge 307: Zoning Regulations"
},
{
"id": "6a0dcd03ee4e68698080ef6c",
"title": "Challenge 308: Credit Card Validator"
},
{
"id": "6a0dcd03ee4e68698080ef6d",
"title": "Challenge 309: Number Sort"
},
{
"id": "6a151d32d772271dd2448c2c",
"title": "Challenge 310: British to American"
},
{
"id": "6a151d32d772271dd2448c2d",
"title": "Challenge 311: Spellcaster"
}
]
}

View File

@ -1180,6 +1180,74 @@
{
"id": "69f90c1329a94b37e2a2086d",
"title": "Challenge 294: Parentheses Combinations"
},
{
"id": "6a0dcc730cb92a616f86f0bf",
"title": "Challenge 295: Schema Validator Part 1"
},
{
"id": "6a0dcc730cb92a616f86f0c0",
"title": "Challenge 296: Schema Validator Part 2"
},
{
"id": "6a0dcc730cb92a616f86f0c1",
"title": "Challenge 297: Schema Validator Part 3"
},
{
"id": "6a0dcc730cb92a616f86f0c2",
"title": "Challenge 298: Schema Validator Part 4"
},
{
"id": "6a0dcc730cb92a616f86f0c3",
"title": "Challenge 299: Schema Validator Part 5"
},
{
"id": "6a0dcc730cb92a616f86f0c4",
"title": "Challenge 300: Schema Validator Part 6"
},
{
"id": "6a0dcc730cb92a616f86f0c5",
"title": "Challenge 301: Last Load"
},
{
"id": "6a0dcd03ee4e68698080ef66",
"title": "Challenge 302: Jet Lagged"
},
{
"id": "6a0dcd03ee4e68698080ef67",
"title": "Challenge 303: Roommates"
},
{
"id": "6a0dcd03ee4e68698080ef68",
"title": "Challenge 304: Itinerary Arrangements"
},
{
"id": "6a0dcd03ee4e68698080ef69",
"title": "Challenge 305: Idea Rankings"
},
{
"id": "6a0dcd03ee4e68698080ef6a",
"title": "Challenge 306: HTML Content Extractor"
},
{
"id": "6a0dcd03ee4e68698080ef6b",
"title": "Challenge 307: Zoning Regulations"
},
{
"id": "6a0dcd03ee4e68698080ef6c",
"title": "Challenge 308: Credit Card Validator"
},
{
"id": "6a0dcd03ee4e68698080ef6d",
"title": "Challenge 309: Number Sort"
},
{
"id": "6a151d32d772271dd2448c2c",
"title": "Challenge 310: British to American"
},
{
"id": "6a151d32d772271dd2448c2d",
"title": "Challenge 311: Spellcaster"
}
]
}

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 = 294;
const EXPECTED_CHALLENGE_COUNT = 311;
// 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)**