diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-and-run-simple-c-sharp-console-applications/647e21d08acb466c97ccbee8.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-and-run-simple-c-sharp-console-applications/647e21d08acb466c97ccbee8.md new file mode 100644 index 0000000000000000000000000000000000000000..646a035a2f10d727c56fe9fbfb9b96cd498d1c41 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-and-run-simple-c-sharp-console-applications/647e21d08acb466c97ccbee8.md @@ -0,0 +1,39 @@ +--- +id: 647e21d08acb466c97ccbee8 +title: Challenge Project - Develop foreach and if-elseif-else Structures to Process Array Data in C# +challengeType: 19 +dashedName: challenge-project-develop-foreach-and-if-elseif-else-structures-to-process-array-data-in-c-sharp +--- + +# --description-- + +This challenge will be partially completed on the Microsoft Learn platform. Follow these instructions to complete the challenge: + +1. Go to https://learn.microsoft.com/training/modules/challenge-project-arrays-iteration-selection/ and complete all the tasks for the "Challenge Project - Develop foreach and if-elseif-else Structures to Process Array Data in C#" module. This is **required** to earn the "Create and Run Simple C# Console Applications" trophy on Microsoft Learn, and qualify for the certification exam. +1. When you are finished, come back and correctly answer the question below. + +# --assignment-- + +Complete the Develop `foreach` and `if`-`elseif`-`else` Structures to Process Array Data in C# challenge project on Microsoft Learn. Then, answer the question below. + +# --questions-- + +## --text-- + +A developer is working with two other developers to update a collection of applications. The developers will use code comments during the update process. Which of the following describes an appropriate use of code comments? + +## --answers-- + +When updates are made, the developers use line and block comments to identify each individual code update. + +--- + +When updates are made, the developers leave all existing code comments intact. New comments are added to indicate when old comments no longer apply. + +--- + +When updates are made, the developers summarize changes using block comments. + +## --video-solution-- + +3 diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-and-run-simple-c-sharp-console-applications/647e21df8acb466c97ccbee9.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-and-run-simple-c-sharp-console-applications/647e21df8acb466c97ccbee9.md new file mode 100644 index 0000000000000000000000000000000000000000..8888f7942b7e2364f49edf1b425cebbc455374d0 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-and-run-simple-c-sharp-console-applications/647e21df8acb466c97ccbee9.md @@ -0,0 +1,39 @@ +--- +id: 647e21df8acb466c97ccbee9 +title: Create Readable Code with Conventions, Whitespace, and Comments in C# +challengeType: 19 +dashedName: create-readable-code-with-conventions-whitespace-and-comments-in-c-sharp +--- + +# --description-- + +This challenge will be partially completed on the Microsoft Learn platform. Follow these instructions to complete the challenge: + +1. Go to https://learn.microsoft.com/training/modules/csharp-readable-code/ and complete all the tasks for the "Create Readable Code with Conventions, Whitespace, and Comments in C#" module. This is **required** to earn the "Create and Run Simple C# Console Applications" trophy on Microsoft Learn, and qualify for the certification exam. +1. When you are finished, come back and correctly answer the question below. + +# --assignment-- + +Complete the Create Readable Code with Conventions, Whitespace, and Comments in C# module on Microsoft Learn. Then, answer the question below. + +# --questions-- + +## --text-- + +Which of the following is a bad reason to use a code comment? + +## --answers-- + +To describe the high-level intent of the code. + +--- + +To temporarily comment out a line of code while evaluating a feature in a different way. + +--- + +To explain how a new C# keyword works. + +## --video-solution-- + +3 diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-and-run-simple-c-sharp-console-applications/647e21eb8acb466c97ccbeea.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-and-run-simple-c-sharp-console-applications/647e21eb8acb466c97ccbeea.md new file mode 100644 index 0000000000000000000000000000000000000000..af271d24819813276166b5c4ff5f6ccb8c2d0d54 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-and-run-simple-c-sharp-console-applications/647e21eb8acb466c97ccbeea.md @@ -0,0 +1,39 @@ +--- +id: 647e21eb8acb466c97ccbeea +title: Guided Project - Develop foreach and if-elseif-else Structures to Process Array Data in C# +challengeType: 19 +dashedName: guided-project-develop-foreach-and-if-elseif-else-structures-to-process-array-data-in-c-sharp +--- + +# --description-- + +This challenge will be partially completed on the Microsoft Learn platform. Follow these instructions to complete the challenge: + +1. Go to https://learn.microsoft.com/training/modules/guided-project-arrays-iteration-selection/ and complete all the tasks for the "Guided Project - Develop foreach and if-elseif-else Structures to Process Array Data in C#" module. This is **required** to earn the "Create and Run Simple C# Console Applications" trophy on Microsoft Learn, and qualify for the certification exam. +1. When you are finished, come back and correctly answer the question below. + +# --assignment-- + +Complete the Develop `foreach` and `if`-`elseif`-`else` Structures to Process Array Data in C# guided project on Microsoft Learn. Then, answer the question below. + +# --questions-- + +## --text-- + +A developer writes an application that uses a `foreach` loop to iterate through an array containing 20 elements. After the application is complete, the developer learns that the array must be updated to include 40 elements. The application needs to examine all 40 array elements. Which of the following items describes the required code update? + +## --answers-- + +Create a second `foreach` loop that iterates through the additional items. + +--- + +No changes are required to the `foreach` loop. + +--- + +Place the original `foreach` loop inside the code block of a second `foreach` loop that iterates twice. + +## --video-solution-- + +2 diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-and-run-simple-c-sharp-console-applications/647e21f88acb466c97ccbeeb.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-and-run-simple-c-sharp-console-applications/647e21f88acb466c97ccbeeb.md new file mode 100644 index 0000000000000000000000000000000000000000..6ef0085eddc28d3b73e478da314dae593fec7959 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-and-run-simple-c-sharp-console-applications/647e21f88acb466c97ccbeeb.md @@ -0,0 +1,39 @@ +--- +id: 647e21f88acb466c97ccbeeb +title: Install and Configure Visual Studio Code +challengeType: 19 +dashedName: install-and-configure-visual-studio-code +--- + +# --description-- + +This challenge will be partially completed on the Microsoft Learn platform. Follow these instructions to complete the challenge: + +1. Go to https://learn.microsoft.com/training/modules/install-configure-visual-studio-code/ and complete all the tasks for the "Install and Configure Visual Studio Code" module. This is **required** to earn the "Create and Run Simple C# Console Applications" trophy on Microsoft Learn, and qualify for the certification exam. +1. When you are finished, come back and correctly answer the question below. + +# --assignment-- + +Complete the Install and Configure Visual Studio Code module on Microsoft Learn. Then, answer the question below. + +# --questions-- + +## --text-- + +Which of the following choices provides the best description of an Integrated Development Environment (IDE)? + +## --answers-- + +Visual Studio Code is an Integrated Development Environment. + +--- + +An Integrated Development Environment is tool that makes it easier to write code. + +--- + +An IDE is a suite of tools that supports the full software development lifecycle. + +## --video-solution-- + +3 diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-and-run-simple-c-sharp-console-applications/647e22058acb466c97ccbeec.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-and-run-simple-c-sharp-console-applications/647e22058acb466c97ccbeec.md new file mode 100644 index 0000000000000000000000000000000000000000..e527f8f5539beb7823c4d22b6b6833c4ed458e38 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-and-run-simple-c-sharp-console-applications/647e22058acb466c97ccbeec.md @@ -0,0 +1,40 @@ +--- +id: 647e22058acb466c97ccbeec +title: Store and Iterate Through Sequences of Data Using Arrays and the foreach Statement in C# +challengeType: 19 +dashedName: store-and-iterate-through-sequences-of-data-using-arrays-and-the-foreach-statement-in-c-sharp +--- + +# --description-- + +This challenge will be partially completed on the Microsoft Learn platform. Follow these instructions to complete the challenge: + +1. Go to https://learn.microsoft.com/training/modules/csharp-arrays/ and complete all the tasks for the "Store and Iterate Through Sequences of Data Using Arrays and the foreach Statement in C#" module. This is **required** to earn the "Create and Run Simple C# Console Applications" trophy on Microsoft Learn, and qualify for the certification exam. +1. When you are finished, come back and correctly answer the question below. + +# --assignment-- + +Complete the Store and Iterate Through Sequences of Data Using Arrays and the `foreach` Statement in C# module on Microsoft Learn. Then, answer the question below. + +# --questions-- + +## --text-- + +Which of the following foreach statements is syntactically correct? + +## --answers-- + +`foreach (int value of values)` + +--- + +`foreach (int value with values)` + +--- + +`foreach (int value in values)` + + +## --video-solution-- + +3 diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-and-run-simple-c-sharp-console-applications/647f87dc07d29547b3bee1bf.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-and-run-simple-c-sharp-console-applications/647f87dc07d29547b3bee1bf.md new file mode 100644 index 0000000000000000000000000000000000000000..e97d10a30443fd5bb4cea9a51f9ba1e0737cd31b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-and-run-simple-c-sharp-console-applications/647f87dc07d29547b3bee1bf.md @@ -0,0 +1,13 @@ +--- +id: 647f87dc07d29547b3bee1bf +title: Trophy - Create and Run Simple C# Console Applications +challengeType: 18 +dashedName: trophy-create-and-run-simple-c-sharp-console-applications +msTrophyId: learn.wwl.get-started-c-sharp-part-2.trophy +--- + +# --description-- + +Now that you've completed all of the "Create and Run Simple C# Console Applications" challenges, you should have earned the trophy for it on the Microsoft Learn platform. If you don't see this trophy when viewing your achievements page, you have not completed all the tasks and your trophy cannot be verified. + +Link your Microsoft username to your freeCodeCamp account and click the "Verify Trophy" button below to complete the challenge. This trophy is **required** to qualify for the certification exam. diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-methods-in-c-sharp-console-applications/647e22338acb466c97ccbeed.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-methods-in-c-sharp-console-applications/647e22338acb466c97ccbeed.md new file mode 100644 index 0000000000000000000000000000000000000000..c75d7a4ad86d6fc09f72d3c594af156c7ff777f1 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-methods-in-c-sharp-console-applications/647e22338acb466c97ccbeed.md @@ -0,0 +1,39 @@ +--- +id: 647e22338acb466c97ccbeed +title: Challenge Project - Create a Mini-Game +challengeType: 19 +dashedName: challenge-project-create-a-mini-game +--- + +# --description-- + +This challenge will be partially completed on the Microsoft Learn platform. Follow these instructions to complete the challenge: + +1. Go to https://learn.microsoft.com/training/modules/challenge-project-create-mini-game/ and complete all the tasks for the "Challenge Project - Create a Mini-Game" module. This is **required** to earn the "Create Methods in C# Console Applications" trophy on Microsoft Learn, and qualify for the certification exam. +1. When you are finished, come back and correctly answer the question below. + +# --assignment-- + +Complete the Create a Mini-Game challenge project on Microsoft Learn. Then, answer the question below. + +# --questions-- + +## --text-- + +A developer wants to create a method that returns a value in an array. Which of the following options would be a good choice for a method signature? + +## --answers-- + +`string GetValueAtIndex(string[] array, int index)` + +--- + +`bool GetValueAtIndex(string[] array, int index)` + +--- + +`int GetValueAtIndex(int index)` + +## --video-solution-- + +1 diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-methods-in-c-sharp-console-applications/647e223c8acb466c97ccbeee.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-methods-in-c-sharp-console-applications/647e223c8acb466c97ccbeee.md new file mode 100644 index 0000000000000000000000000000000000000000..38f129f813d22358572c5c6877ab6168b63d972c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-methods-in-c-sharp-console-applications/647e223c8acb466c97ccbeee.md @@ -0,0 +1,39 @@ +--- +id: 647e223c8acb466c97ccbeee +title: Create C# Methods that Return Values +challengeType: 19 +dashedName: create-c-sharp-methods-that-return-values +--- + +# --description-- + +This challenge will be partially completed on the Microsoft Learn platform. Follow these instructions to complete the challenge: + +1. Go to https://learn.microsoft.com/training/modules/create-c-sharp-methods-return-values/ and complete all the tasks for the "Create C# Methods that Return Values" module. This is **required** to earn the "Create Methods in C# Console Applications" trophy on Microsoft Learn, and qualify for the certification exam. +1. When you are finished, come back and correctly answer the question below. + +# --assignment-- + +Complete the Create C# Methods that Return Values module on Microsoft Learn. Then, answer the question below. + +# --questions-- + +## --text-- + +Which of the following options correctly returns a `string` value? + +## --answers-- + +`return "";` + +--- + +`return 'a';` + +--- + +`return 5;` + +## --video-solution-- + +1 diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-methods-in-c-sharp-console-applications/647e224b8acb466c97ccbeef.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-methods-in-c-sharp-console-applications/647e224b8acb466c97ccbeef.md new file mode 100644 index 0000000000000000000000000000000000000000..263085b4cef9251d4c1277bb13a3ba7b3c268e05 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-methods-in-c-sharp-console-applications/647e224b8acb466c97ccbeef.md @@ -0,0 +1,45 @@ +--- +id: 647e224b8acb466c97ccbeef +title: Create C# Methods with Parameters +challengeType: 19 +dashedName: create-c-sharp-methods-with-parameters +--- + +# --description-- + +This challenge will be partially completed on the Microsoft Learn platform. Follow these instructions to complete the challenge: + +1. Go to https://learn.microsoft.com/training/modules/create-c-sharp-methods-parameters/ and complete all the tasks for the "Create C# Methods with Parameters" module. This is **required** to earn the "Create Methods in C# Console Applications" trophy on Microsoft Learn, and qualify for the certification exam. +1. When you are finished, come back and correctly answer the question below. + +# --assignment-- + +Complete the Create C# Methods with Parameters module on Microsoft Learn. Then, answer the question below. + +# --questions-- + +## --text-- + +Given the method signature, + +```csharp +void Print(string name, string number = "", bool member = false) +``` + +Which of the following options correctly uses named and optional arguments? + +## --answers-- + +`Print("Tony", member: true);` + +--- + +`Print(number: "555", member: false)` + +--- + +`Print("Tony", false)` + +## --video-solution-- + +1 diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-methods-in-c-sharp-console-applications/647e225e8acb466c97ccbef0.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-methods-in-c-sharp-console-applications/647e225e8acb466c97ccbef0.md new file mode 100644 index 0000000000000000000000000000000000000000..f1e077c1f6486603f7e7420bec493ca8bc5c160d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-methods-in-c-sharp-console-applications/647e225e8acb466c97ccbef0.md @@ -0,0 +1,40 @@ +--- +id: 647e225e8acb466c97ccbef0 +title: Guided Project - Plan a Petting Zoo Visit +challengeType: 19 +dashedName: guided-project-plan-a-petting-zoo-visit +--- + +# --description-- + +This challenge will be partially completed on the Microsoft Learn platform. Follow these instructions to complete the challenge: + +1. Go to https://learn.microsoft.com/training/modules/guided-project-visit-petting-zoo/ and complete all the tasks for the "Guided Project - Plan a Petting Zoo Visit" module. This is **required** to earn the "Create Methods in C# Console Applications" trophy on Microsoft Learn, and qualify for the certification exam. +1. When you are finished, come back and correctly answer the question below. + +# --assignment-- + +Complete the Plan a Petting Zoo Visit guided project on Microsoft Learn. Then, answer the question below. + +# --questions-- + +## --text-- + +What is the purpose of defining an optional parameter in a method? + +## --answers-- + +To cause a method to perform a different task. + +--- + +To overload a method. + +--- + +To simplify the required parameters when a parameter isn't significant to the result. + +## --video-solution-- + +3 + diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-methods-in-c-sharp-console-applications/647e226a8acb466c97ccbef1.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-methods-in-c-sharp-console-applications/647e226a8acb466c97ccbef1.md new file mode 100644 index 0000000000000000000000000000000000000000..0c51c1c9951a877613d6d3d335fc7a73d5dda602 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-methods-in-c-sharp-console-applications/647e226a8acb466c97ccbef1.md @@ -0,0 +1,39 @@ +--- +id: 647e226a8acb466c97ccbef1 +title: Write Your First C# Method +challengeType: 19 +dashedName: write-your-first-c-sharp-method +--- + +# --description-- + +This challenge will be partially completed on the Microsoft Learn platform. Follow these instructions to complete the challenge: + +1. Go to https://learn.microsoft.com/training/modules/write-first-c-sharp-method/ and complete all the tasks for the "Write Your First C# Method" module. This is **required** to earn the "Create Methods in C# Console Applications" trophy on Microsoft Learn, and qualify for the certification exam. +1. When you are finished, come back and correctly answer the question below. + +# --assignment-- + +Complete the Write Your First C# Method module on Microsoft Learn. Then, answer the question below. + +# --questions-- + +## --text-- + +Which of the following correctly declares a method? + +## --answers-- + +`DisplayNumbers();` + +--- + +`void DisplayNumbers{};` + +--- + +`void DisplayNumbers() { }` + +## --video-solution-- + +3 diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-methods-in-c-sharp-console-applications/647f877f07d29547b3bee1be.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-methods-in-c-sharp-console-applications/647f877f07d29547b3bee1be.md new file mode 100644 index 0000000000000000000000000000000000000000..7e8c5c7e33b939f9def5250823b26a93c8d291f4 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/create-methods-in-c-sharp-console-applications/647f877f07d29547b3bee1be.md @@ -0,0 +1,13 @@ +--- +id: 647f877f07d29547b3bee1be +title: Trophy - Create Methods in C# Console Applications +challengeType: 18 +dashedName: trophy-create-methods-in-c-sharp-console-applications +msTrophyId: learn.wwl.get-started-c-sharp-part-5.trophy +--- + +# --description-- + +Now that you've completed all of the "Create Methods in C# Console Applications" challenges, you should have earned the trophy for it on the Microsoft Learn platform. If you don't see this trophy when viewing your achievements page, you have not completed all the tasks and your trophy cannot be verified. + +Link your Microsoft username to your freeCodeCamp account and click the "Verify Trophy" button below to complete the challenge. This trophy is **required** to qualify for the certification exam. diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ab367417b2b2512af0.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ab367417b2b2512af0.md new file mode 100644 index 0000000000000000000000000000000000000000..e53400c96c6d03ba4464df405215ce9d1b74feab --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ab367417b2b2512af0.md @@ -0,0 +1,84 @@ +--- +id: 587d78ab367417b2b2512af0 +title: 'Use display: flex to Position Two Boxes' +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pVaDAv/cgz3QS7' +forumTopicId: 301105 +dashedName: use-display-flex-to-position-two-boxes +--- + +# --description-- + +This section uses alternating challenge styles to show how to use CSS to position elements in a flexible way. First, a challenge will explain theory, then a practical challenge using a simple tweet component will apply the flexbox concept. + +Placing the CSS property `display: flex;` on an element allows you to use other flex properties to build a responsive page. + +# --instructions-- + +Add the CSS property `display` to `#box-container` and set its value to `flex`. + +# --hints-- + +`#box-container` should have the `display` property set to a value of `flex`. + +```js +const boxContainer = document.querySelector('#box-container'); +const displayStyle = window.getComputedStyle(boxContainer)['display']; +assert.strictEqual(displayStyle, 'flex'); +``` + +# --seed-- + +## --seed-contents-- + +```html + +
+
+
+
+``` + +# --solutions-- + +```html + +
+
+
+
+``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ab367417b2b2512af1.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ab367417b2b2512af1.md new file mode 100644 index 0000000000000000000000000000000000000000..e8abc41886b4bb355a7c33f9d75ec9a90d7f7bd1 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ab367417b2b2512af1.md @@ -0,0 +1,278 @@ +--- +id: 587d78ab367417b2b2512af1 +title: Add Flex Superpowers to the Tweet Embed +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pVaDAv/c9W7MhM' +forumTopicId: 301100 +dashedName: add-flex-superpowers-to-the-tweet-embed +--- + +# --description-- + +To the right is the tweet embed that will be used as a practical example. Some of the elements would look better with a different layout. The last challenge demonstrated `display: flex`. Here you'll add it to several components in the tweet embed to start adjusting their positioning. + +# --instructions-- + +Add the CSS property `display: flex` to all of the following items - note that the selectors are already set up in the CSS: + +`header`, the header's `.profile-name`, the header's `.follow-btn`, the header's `h3` and `h4`, the `footer`, and the footer's `.stats`. + +# --hints-- + +Your `.follow-btn` should be rendered on the page. Be sure to turn off any extensions such as ad blockers. + +```js +const followButton = document.querySelector('.follow-btn'); +const displayStyle = window.getComputedStyle(followButton)['display']; +assert.isNotNull(followButton); +assert.notStrictEqual(displayStyle, 'none'); +``` + +Your `header` should have a `display` property set to `flex`. + +```js +const header = document.querySelector('header'); +const displayStyle = window.getComputedStyle(header)['display']; +assert.strictEqual(displayStyle, 'flex'); +``` + +Your `footer` should have a `display` property set to `flex`. + +```js +const footer = document.querySelector('footer'); +const displayStyle = window.getComputedStyle(footer)['display']; +assert.strictEqual(displayStyle, 'flex'); +``` + +Your `h3` should have a `display` property set to `flex`. + +```js +const h3Element = document.querySelector('h3'); +const displayStyle = window.getComputedStyle(h3Element)['display']; +assert.strictEqual(displayStyle, 'flex'); +``` + +Your `h4` should have a `display` property set to `flex`. + +```js +const h4Element = document.querySelector('h4'); +const displayStyle = window.getComputedStyle(h4Element)['display']; +assert.strictEqual(displayStyle, 'flex'); +``` + +Your `.profile-name` should have a `display` property set to `flex`. + +```js +const profileName = document.querySelector('.profile-name'); +const displayStyle = window.getComputedStyle(profileName)['display']; +assert.strictEqual(displayStyle, 'flex'); +``` + +Your `.follow-btn` should have a `display` property set to `flex`. + +```js +const followButton = document.querySelector('.follow-btn'); +const displayStyle = window.getComputedStyle(followButton)['display']; +assert.strictEqual(displayStyle, 'flex'); +``` + +Your `.stats` should have a `display` property set to `flex`. + +```js +const stats = document.querySelector('.stats'); +const displayStyle = window.getComputedStyle(stats)['display']; +assert.strictEqual(displayStyle, 'flex'); +``` + +# --seed-- + +## --seed-contents-- + +```html + +
+ Quincy Larson's profile picture +
+

Quincy Larson

+

@ossia

+
+
+ +
+
+
+

+ I meet so many people who are in search of that one trick that will help + them work smart. Even if you work smart, you still have to work hard. +

+ 1:32 PM - 12 Jan 2018 +
+
+ +``` + +# --solutions-- + +```html + +
+ Quincy Larson's profile picture +
+

Quincy Larson

+

@ossia

+
+
+ +
+
+
+

+ I meet so many people who are in search of that one trick that will help + them work smart. Even if you work smart, you still have to work hard. +

+ 1:32 PM - 12 Jan 2018 +
+
+ +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ab367417b2b2512af2.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ab367417b2b2512af2.md new file mode 100644 index 0000000000000000000000000000000000000000..cb64d5cad90ed3ac91119971c7ea85637784ec9a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ab367417b2b2512af2.md @@ -0,0 +1,88 @@ +--- +id: 587d78ab367417b2b2512af2 +title: Use the flex-direction Property to Make a Row +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pVaDAv/cBEkbfJ' +forumTopicId: 301110 +dashedName: use-the-flex-direction-property-to-make-a-row +--- + +# --description-- + +Adding `display: flex` to an element turns it into a flex container. This makes it possible to align any children of that element into rows or columns. You do this by adding the `flex-direction` property to the parent item and setting it to row or column. Creating a row will align the children horizontally, and creating a column will align the children vertically. + +Other options for `flex-direction` are `row-reverse` and `column-reverse`. + +**Note:** The default value for the `flex-direction` property is `row`. + +# --instructions-- + +Add the CSS property `flex-direction` to the `#box-container` element, and give it a value of `row-reverse`. + +# --hints-- + +The `#box-container` element should have a `flex-direction` property set to `row-reverse`. + +```js +const boxContainer = document.querySelector('#box-container'); +const flexDirection = window.getComputedStyle(boxContainer)['flex-direction']; +assert.strictEqual(flexDirection, 'row-reverse'); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
+
+
+``` + +# --solutions-- + +```html + + +
+
+
+
+``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ab367417b2b2512af3.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ab367417b2b2512af3.md new file mode 100644 index 0000000000000000000000000000000000000000..19e44444979ec81c8b789fda5c9b79baa4882988 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ab367417b2b2512af3.md @@ -0,0 +1,241 @@ +--- +id: 587d78ab367417b2b2512af3 +title: Apply the flex-direction Property to Create Rows in the Tweet Embed +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pVaDAv/cJb8yuq' +forumTopicId: 301104 +dashedName: apply-the-flex-direction-property-to-create-rows-in-the-tweet-embed +--- + +# --description-- + +The `header` and `footer` in the tweet embed example have child items that could be arranged as rows using the `flex-direction` property. This tells CSS to align the children horizontally. + +# --instructions-- + +Add the CSS property `flex-direction` to both the `header` and `footer` and set the value to `row`. + +# --hints-- + +Your `.follow-btn` should be rendered on the page. Be sure to turn off any extensions such as ad blockers. + +```js +const followButton = document.querySelector('.follow-btn'); +const displayStyle = window.getComputedStyle(followButton)['display']; +assert.isNotNull(followButton); +assert.notStrictEqual(displayStyle, 'none'); +``` + +The `header` should have a `flex-direction` property set to `row`. + +```js +assert.match(code, /header\s*?{[^}]*?flex-direction:\s*?row;/g); +``` + +The `footer` should have a `flex-direction` property set to `row`. + +```js +assert.match(code, /footer\s*?{[^}]*?flex-direction:\s*?row;/g); +``` + +# --seed-- + +## --seed-contents-- + +```html + +
+ Quincy Larson's profile picture +
+

Quincy Larson

+

@ossia

+
+
+ +
+
+
+

+ I meet so many people who are in search of that one trick that will help + them work smart. Even if you work smart, you still have to work hard. +

+ 1:32 PM - 12 Jan 2018 +
+
+ +``` + +# --solutions-- + +```html + +
+ Quincy Larson's profile picture +
+

Quincy Larson

+

@ossia

+
+
+ +
+
+
+

+ I meet so many people who are in search of that one trick that will help + them work smart. Even if you work smart, you still have to work hard. +

+ 1:32 PM - 12 Jan 2018 +
+
+ +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ac367417b2b2512af4.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ac367417b2b2512af4.md new file mode 100644 index 0000000000000000000000000000000000000000..5677f7f0344fa2be1d523d5c2e6bdc677ff5733b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ac367417b2b2512af4.md @@ -0,0 +1,84 @@ +--- +id: 587d78ac367417b2b2512af4 +title: Use the flex-direction Property to Make a Column +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pVaDAv/cZmWeA4' +forumTopicId: 301109 +dashedName: use-the-flex-direction-property-to-make-a-column +--- + +# --description-- + +The last two challenges used the `flex-direction` property set to `row`. This property can also create a column by vertically stacking the children of a flex container. + +# --instructions-- + +Add the CSS property `flex-direction` to the `#box-container` element, and give it a value of `column`. + +# --hints-- + +The `#box-container` element should have a `flex-direction` property set to `column`. + +```js +const boxContainer = document.querySelector('#box-container'); +const flexDirection = window.getComputedStyle(boxContainer)['flex-direction']; +assert.strictEqual(flexDirection, 'column'); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
+
+
+``` + +# --solutions-- + +```html + + +
+
+
+
+``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ac367417b2b2512af5.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ac367417b2b2512af5.md new file mode 100644 index 0000000000000000000000000000000000000000..791aabc4cf5a2a347c63766a6facb28f2af21cb6 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ac367417b2b2512af5.md @@ -0,0 +1,233 @@ +--- +id: 587d78ac367417b2b2512af5 +title: Apply the flex-direction Property to Create a Column in the Tweet Embed +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pVaDAv/cnzdVC9' +forumTopicId: 301103 +dashedName: apply-the-flex-direction-property-to-create-a-column-in-the-tweet-embed +--- + +# --description-- + +The tweet embed `header` and `footer` used the `flex-direction` property earlier with a row value. Similarly, the items inside the `.profile-name` element would work well stacked as a column. + +# --instructions-- + +Add the CSS property `flex-direction` to the header's `.profile-name` element and set the value to `column`. + +# --hints-- + +Your `.follow-btn` should be rendered on the page. Be sure to turn off any extensions such as ad blockers. + +```js +const followButton = document.querySelector('.follow-btn'); +const displayStyle = window.getComputedStyle(followButton)['display']; +assert.isNotNull(followButton); +assert.notStrictEqual(displayStyle, 'none'); +``` + +The `.profile-name` element should have a `flex-direction` property set to `column`. + +```js +const profileName = document.querySelector('.profile-name'); +const flexDirection = window.getComputedStyle(profileName)['flex-direction']; +assert.strictEqual(flexDirection, 'column'); +``` + +# --seed-- + +## --seed-contents-- + +```html + +
+ Quincy Larson's profile picture +
+

Quincy Larson

+

@ossia

+
+
+ +
+
+
+

+ I meet so many people who are in search of that one trick that will help + them work smart. Even if you work smart, you still have to work hard. +

+ 1:32 PM - 12 Jan 2018 +
+
+ +``` + +# --solutions-- + +```html + +
+ Quincy Larson's profile picture +
+

Quincy Larson

+

@ossia

+
+
+ +
+
+
+

+ I meet so many people who are in search of that one trick that will help + them work smart. Even if you work smart, you still have to work hard. +

+ 1:32 PM - 12 Jan 2018 +
+
+ +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ac367417b2b2512af6.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ac367417b2b2512af6.md new file mode 100644 index 0000000000000000000000000000000000000000..6f686d3640c35b5dc20ea3a54b1aff9ed67a2cc4 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ac367417b2b2512af6.md @@ -0,0 +1,98 @@ +--- +id: 587d78ac367417b2b2512af6 +title: Align Elements Using the justify-content Property +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pVaDAv/c43gnHm' +forumTopicId: 301102 +dashedName: align-elements-using-the-justify-content-property +--- + +# --description-- + +Sometimes the flex items within a flex container do not fill all the space in the container. It is common to want to tell CSS how to align and space out the flex items a certain way. Fortunately, the `justify-content` property has several options to do this. But first, there is some important terminology to understand before reviewing those options. + +For more info about flex-box properties read here + +Recall that setting a flex container as a row places the flex items side-by-side from left-to-right. A flex container set as a column places the flex items in a vertical stack from top-to-bottom. For each, the direction the flex items are arranged is called the **main axis**. For a row, this is a horizontal line that cuts through each item. And for a column, the main axis is a vertical line through the items. + +There are several options for how to space the flex items along the line that is the main axis. One of the most commonly used is `justify-content: center;`, which aligns all the flex items to the center inside the flex container. Other options include: + + + +# --instructions-- + +An example helps show this property in action. Add the CSS property `justify-content` to the `#box-container` element, and give it a value of `center`. + +**Bonus** +Try the other options for the `justify-content` property in the code editor to see their differences. But note that a value of `center` is the only one that will pass this challenge. + +# --hints-- + +The `#box-container` element should have a `justify-content` property set to a value of `center`. + +```js +const boxContainer = document.querySelector('#box-container'); +const justifyDirection = + window.getComputedStyle(boxContainer)['justify-content']; +assert.strictEqual(justifyDirection, 'center'); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
+
+
+``` + +# --solutions-- + +```html + + +
+
+
+
+``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ac367417b2b2512af7.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ac367417b2b2512af7.md new file mode 100644 index 0000000000000000000000000000000000000000..1928ecba6a781cef87fa46e010b10abc6bcf7689 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ac367417b2b2512af7.md @@ -0,0 +1,236 @@ +--- +id: 587d78ac367417b2b2512af7 +title: Use the justify-content Property in the Tweet Embed +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pVaDAv/c43GgTa' +forumTopicId: 301115 +dashedName: use-the-justify-content-property-in-the-tweet-embed +--- + +# --description-- + +The last challenge showed an example of the `justify-content` property. For the tweet embed, this property can be applied to align the items in the `.profile-name` element. + +# --instructions-- + +Add the CSS property `justify-content` to the header's `.profile-name` element and set the value to any of the options from the last challenge. + +# --hints-- + +Your `.follow-btn` should be rendered on the page. Be sure to turn off any extensions such as ad blockers. + +```js +const followButton = document.querySelector('.follow-btn'); +const displayStyle = window.getComputedStyle(followButton)['display']; +assert.isNotNull(followButton); +assert.notStrictEqual(displayStyle, 'none'); +``` + +The `.profile-name` element should have the `justify-content` property set to any of these values: `center`, `flex-start`, `flex-end`, `space-between`, `space-around`, or `space-evenly`. + +```js +assert.match( + code, + /header\s.profile-name\s*{\s*?.*?\s*?.*?\s*?\s*?.*?\s*?justify-content\s*:\s*(center|flex-start|flex-end|space-between|space-around|space-evenly)\s*;/g +); +``` + +# --seed-- + +## --seed-contents-- + +```html + +
+ Quincy Larson's profile picture +
+

Quincy Larson

+

@ossia

+
+
+ +
+
+
+

+ I meet so many people who are in search of that one trick that will help + them work smart. Even if you work smart, you still have to work hard. +

+ 1:32 PM - 12 Jan 2018 +
+
+ +``` + +# --solutions-- + +```html + +
+ Quincy Larson's profile picture +
+

Quincy Larson

+

@ossia

+
+
+ +
+
+
+

+ I meet so many people who are in search of that one trick that will help + them work smart. Even if you work smart, you still have to work hard. +

+ 1:32 PM - 12 Jan 2018 +
+
+ +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ad367417b2b2512af8.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ad367417b2b2512af8.md new file mode 100644 index 0000000000000000000000000000000000000000..6fa5c2e0480d8148c5b07f6bbbdd1fd0628d1eac --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ad367417b2b2512af8.md @@ -0,0 +1,97 @@ +--- +id: 587d78ad367417b2b2512af8 +title: Align Elements Using the align-items Property +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pVaDAv/c8aggtk' +forumTopicId: 301101 +dashedName: align-elements-using-the-align-items-property +--- + +# --description-- + +The `align-items` property is similar to `justify-content`. Recall that the `justify-content` property aligned flex items along the main axis. For rows, the main axis is a horizontal line and for columns it is a vertical line. + +Flex containers also have a **cross axis** which is the opposite of the main axis. For rows, the cross axis is vertical and for columns, the cross axis is horizontal. + +CSS offers the `align-items` property to align flex items along the cross axis. For a row, it tells CSS how to push the items in the entire row up or down within the container. And for a column, how to push all the items left or right within the container. + +The different values available for `align-items` include: + + + +# --instructions-- + +An example helps show this property in action. Add the CSS property `align-items` to the `#box-container` element, and give it a value of `center`. + +**Bonus** +Try the other options for the `align-items` property in the code editor to see their differences. But note that a value of `center` is the only one that will pass this challenge. + +# --hints-- + +The `#box-container` element should have an `align-items` property set to a value of `center`. + +```js +const boxContainer = document.querySelector('#box-container'); +const alignment = window.getComputedStyle(boxContainer)['align-items']; +assert.strictEqual(alignment, 'center'); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+

Hello

+

Goodbye

+
+``` + +# --solutions-- + +```html + + +
+

Hello

+

Goodbye

+
+``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ad367417b2b2512af9.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ad367417b2b2512af9.md new file mode 100644 index 0000000000000000000000000000000000000000..9b57cb764adaa63430b44b95c867819605a8538c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ad367417b2b2512af9.md @@ -0,0 +1,237 @@ +--- +id: 587d78ad367417b2b2512af9 +title: Use the align-items Property in the Tweet Embed +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pVaDAv/cd3PNfq' +forumTopicId: 301106 +dashedName: use-the-align-items-property-in-the-tweet-embed +--- + +# --description-- + +The last challenge introduced the `align-items` property and gave an example. This property can be applied to a few tweet embed elements to align the flex items inside them. + +# --instructions-- + +Add the CSS property `align-items` to the header's `.follow-btn` element. Set the value to `center`. + +# --hints-- + +Your `.follow-btn` should be rendered on the page. Be sure to turn off any extensions such as ad blockers. + +```js +const followButton = document.querySelector('.follow-btn'); +const displayStyle = window.getComputedStyle(followButton)['display']; +assert.isNotNull(followButton); +assert.notStrictEqual(displayStyle, 'none'); +``` + +The `.follow-btn` element should have the `align-items` property set to a value of `center`. + +```js +const followButton = document.querySelector('.follow-btn'); +const alignItems = window.getComputedStyle(followButton)['align-items']; +assert.strictEqual(alignItems, 'center'); +``` + +# --seed-- + +## --seed-contents-- + +```html + +
+ Quincy Larson's profile picture +
+

Quincy Larson

+

@ossia

+
+
+ +
+
+
+

+ I meet so many people who are in search of that one trick that will help + them work smart. Even if you work smart, you still have to work hard. +

+ 1:32 PM - 12 Jan 2018 +
+
+ +``` + +# --solutions-- + +```html + +
+ Quincy Larson's profile picture +
+

Quincy Larson

+

@ossia

+
+
+ +
+
+
+

+ I meet so many people who are in search of that one trick that will help + them work smart. Even if you work smart, you still have to work hard. +

+ 1:32 PM - 12 Jan 2018 +
+
+ +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ad367417b2b2512afa.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ad367417b2b2512afa.md new file mode 100644 index 0000000000000000000000000000000000000000..b86b7adaafb22cb87ac98e24b0a33755ab65daca --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ad367417b2b2512afa.md @@ -0,0 +1,140 @@ +--- +id: 587d78ad367417b2b2512afa +title: Use the flex-wrap Property to Wrap a Row or Column +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pVaDAv/cQv9ZtG' +forumTopicId: 301114 +dashedName: use-the-flex-wrap-property-to-wrap-a-row-or-column +--- + +# --description-- + +CSS flexbox has a feature to split a flex container into multiple rows (or columns). By default, a flex container will fit all flex items together. For example, a row will all be on one line. + +However, using the `flex-wrap` property tells CSS to wrap items. This means extra items move into a new row or column. The break point of where the wrapping happens depends on the size of the items and the size of the container. + +CSS also has options for the direction of the wrap: + + + +# --instructions-- + +The current layout has too many boxes for one row. Add the CSS property `flex-wrap` to the `#box-container` element, and give it a value of `wrap`. + +# --hints-- + +The `#box-container` element should have the `flex-wrap` property set to a value of `wrap`. + +```js +const boxContainer = document.querySelector('#box-container'); +const flexWrap = window.getComputedStyle(boxContainer)['flex-wrap']; +assert.strictEqual(flexWrap, 'wrap'); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
+
+
+
+
+
+
+``` + +# --solutions-- + +```html + + +
+
+
+
+
+
+
+
+``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ad367417b2b2512afb.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ad367417b2b2512afb.md new file mode 100644 index 0000000000000000000000000000000000000000..556bf32f213e74eb7aed6c490348269f98205080 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ad367417b2b2512afb.md @@ -0,0 +1,98 @@ +--- +id: 587d78ad367417b2b2512afb +title: Use the flex-shrink Property to Shrink Items +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pVaDAv/cd3PBfr' +forumTopicId: 301113 +dashedName: use-the-flex-shrink-property-to-shrink-items +--- + +# --description-- + +So far, all the properties in the challenges apply to the flex container (the parent of the flex items). However, there are several useful properties for the flex items. + +The first is the `flex-shrink` property. When it's used, it allows an item to shrink if the flex container is too small. Items shrink when the width of the parent container is smaller than the combined widths of all the flex items within it. + +The `flex-shrink` property takes numbers as values. The higher the number, the more it will shrink compared to the other items in the container. For example, if one item has a `flex-shrink` value of `1` and the other has a `flex-shrink` value of `3`, the one with the value of `3` will shrink three times as much as the other. + +# --instructions-- + +Add the CSS property `flex-shrink` to both `#box-1` and `#box-2`. Give `#box-1` a value of `1` and `#box-2` a value of `2`. + +# --hints-- + +The `#box-1` element should have the `flex-shrink` property set to a value of `1`. + +```js +const boxOne = document.querySelector('#box-1'); +const flexShrink = window.getComputedStyle(boxOne)['flex-shrink']; +assert.equal(flexShrink, '1'); +``` + +The `#box-2` element should have the `flex-shrink` property set to a value of `2`. + +```js +const boxTwo = document.querySelector('#box-2'); +const flexShrink = window.getComputedStyle(boxTwo)['flex-shrink']; +assert.equal(flexShrink, '2'); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
+
+
+``` + +# --solutions-- + +```html + + +
+
+
+
+``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ae367417b2b2512afc.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ae367417b2b2512afc.md new file mode 100644 index 0000000000000000000000000000000000000000..6e6282772a23677b38b500741f68abc40117257f --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ae367417b2b2512afc.md @@ -0,0 +1,94 @@ +--- +id: 587d78ae367417b2b2512afc +title: Use the flex-grow Property to Expand Items +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pVaDAv/c2p78cg' +forumTopicId: 301111 +dashedName: use-the-flex-grow-property-to-expand-items +--- + +# --description-- + +The opposite of `flex-shrink` is the `flex-grow` property. Recall that `flex-shrink` controls the size of the items when the container shrinks. The `flex-grow` property controls the size of items when the parent container expands. + +Using a similar example from the last challenge, if one item has a `flex-grow` value of `1` and the other has a `flex-grow` value of `3`, the one with the value of `3` will grow three times as much as the other. + +# --instructions-- + +Add the CSS property `flex-grow` to both `#box-1` and `#box-2`. Give `#box-1` a value of `1` and `#box-2` a value of `2`. + +# --hints-- + +The `#box-1` element should have the `flex-grow` property set to a value of `1`. + +```js +const boxOne = document.querySelector('#box-1'); +const flexGrow = window.getComputedStyle(boxOne)['flex-grow']; +assert.equal(flexGrow, '1'); +``` + +The `#box-2` element should have the `flex-grow` property set to a value of `2`. + +```js +const boxTwo = document.querySelector('#box-2'); +const flexGrow = window.getComputedStyle(boxTwo)['flex-grow']; +assert.equal(flexGrow, '2'); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
+
+
+``` + +# --solutions-- + +```html + + +
+
+
+
+``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ae367417b2b2512afd.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ae367417b2b2512afd.md new file mode 100644 index 0000000000000000000000000000000000000000..f85b3ad59bb4290b4bf9b30c6e453e57d33a2f47 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ae367417b2b2512afd.md @@ -0,0 +1,106 @@ +--- +id: 587d78ae367417b2b2512afd +title: Use the flex-basis Property to Set the Initial Size of an Item +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pVaDAv/c3d9nCa' +forumTopicId: 301108 +dashedName: use-the-flex-basis-property-to-set-the-initial-size-of-an-item +--- + +# --description-- + +The `flex-basis` property specifies the initial size of the item before CSS makes adjustments with `flex-shrink` or `flex-grow`. + +The units used by the `flex-basis` property are the same as other size properties (`px`, `em`, `%`, etc.). The value `auto` sizes items based on the content. + +# --instructions-- + +Set the initial size of the boxes using `flex-basis`. Add the CSS property `flex-basis` to both `#box-1` and `#box-2`. Give `#box-1` a value of `10em` and `#box-2` a value of `20em`. + +# --hints-- + +The `#box-1` element should have the `flex-basis` property. + +```js +const boxOne = document.querySelector('#box-1'); +const flexBasis = window.getComputedStyle(boxOne)['flex-basis']; +assert.notStrictEqual(flexBasis, 'auto'); +``` + +The `#box-1` element should have a `flex-basis` value of `10em`. + +```js +assert.match(code, /#box-1\s*?{\s*?.*?\s*?.*?\s*?flex-basis:\s*?10em;/g); +``` + +The `#box-2` element should have the `flex-basis` property. + +```js +const boxTwo = document.querySelector('#box-2'); +const flexBasis = window.getComputedStyle(boxTwo)['flex-basis']; +assert.notStrictEqual(flexBasis, 'auto'); +``` + +The `#box-2` element should have a `flex-basis` value of `20em`. + +```js +assert.match(code, /#box-2\s*?{\s*?.*?\s*?.*?\s*?flex-basis:\s*?20em;/g); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
+
+
+``` + +# --solutions-- + +```html + + +
+
+
+
+``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ae367417b2b2512afe.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ae367417b2b2512afe.md new file mode 100644 index 0000000000000000000000000000000000000000..173848ba1ed7fc59b97664f110261216a4111e08 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ae367417b2b2512afe.md @@ -0,0 +1,112 @@ +--- +id: 587d78ae367417b2b2512afe +title: Use the flex Shorthand Property +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pVaDAv/cbpW2tE' +forumTopicId: 301112 +dashedName: use-the-flex-shorthand-property +--- + +# --description-- + +There is a shortcut available to set several flex properties at once. The `flex-grow`, `flex-shrink`, and `flex-basis` properties can all be set together by using the `flex` property. + +For example, `flex: 1 0 10px;` will set the item to `flex-grow: 1;`, `flex-shrink: 0;`, and `flex-basis: 10px;`. + +The default property settings are `flex: 0 1 auto;`. + +# --instructions-- + +Add the CSS property `flex` to both `#box-1` and `#box-2`. Give `#box-1` the values so its `flex-grow` is `2`, its `flex-shrink` is `2`, and its `flex-basis` is `150px`. Give `#box-2` the values so its `flex-grow` is `1`, its `flex-shrink` is `1`, and its `flex-basis` is `150px`. + +These values will cause `#box-1` to grow to fill the extra space at twice the rate of `#box-2` when the container is greater than 300px and shrink at twice the rate of `#box-2` when the container is less than 300px. 300px is the combined size of the `flex-basis` values of the two boxes. + +# --hints-- + +The `#box-1` element should have the `flex` property set to a value of `2 2 150px`. + +```js +const boxOne = document.querySelector('#box-1'); +const flexGrow = window.getComputedStyle(boxOne)['flex-grow']; +const flexShrink = window.getComputedStyle(boxOne)['flex-shrink']; +const flexBasis = window.getComputedStyle(boxOne)['flex-basis']; + +assert.equal(flexGrow, '2'); +assert.equal(flexShrink, '2'); +assert.equal(flexBasis, '150px'); +``` + +The `#box-2` element should have the `flex` property set to a value of `1 1 150px`. + +```js +const boxTwo = document.querySelector('#box-2'); +const flexGrow = window.getComputedStyle(boxTwo)['flex-grow']; +const flexShrink = window.getComputedStyle(boxTwo)['flex-shrink']; +const flexBasis = window.getComputedStyle(boxTwo)['flex-basis']; + +assert.equal(flexGrow, '1'); +assert.equal(flexShrink, '1'); +assert.equal(flexBasis, '150px'); +``` + +Your code should use the `flex` property for `#box-1` and `#box-2`. + +```js +assert.lengthOf(code.match(/flex:\s*?\d\s+?\d\s+?150px;/g), 2); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
+
+
+``` + +# --solutions-- + +```html + + +
+
+
+
+``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ae367417b2b2512aff.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ae367417b2b2512aff.md new file mode 100644 index 0000000000000000000000000000000000000000..5df8a4075660943857bf131fc21aa7ee33ff42a7 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78ae367417b2b2512aff.md @@ -0,0 +1,94 @@ +--- +id: 587d78ae367417b2b2512aff +title: Use the order Property to Rearrange Items +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pVaDAv/cMbvNAG' +forumTopicId: 301116 +dashedName: use-the-order-property-to-rearrange-items +--- + +# --description-- + +The `order` property is used to tell CSS the order of how flex items appear in the flex container. By default, items will appear in the same order they come in the source HTML. The property takes numbers as values, and negative numbers can be used. + +# --instructions-- + +Add the CSS property `order` to both `#box-1` and `#box-2`. Give `#box-1` a value of `2` and give `#box-2` a value of `1`. + +# --hints-- + +The `#box-1` element should have the `order` property set to a value of `2`. + +```js +const boxOne = document.querySelector('#box-1'); +const order = window.getComputedStyle(boxOne)['order']; +assert.strictEqual(order, '2'); +``` + +The `#box-2` element should have the `order` property set to a value of `1`. + +```js +const boxTwo = document.querySelector('#box-2'); +const order = window.getComputedStyle(boxTwo)['order']; +assert.strictEqual(order, '1'); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
+
+
+``` + +# --solutions-- + +```html + + +
+
+
+
+``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78af367417b2b2512b00.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78af367417b2b2512b00.md new file mode 100644 index 0000000000000000000000000000000000000000..19ed4bbfad73c4f8d6071aa9d80aaca9381216fb --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-flexbox/587d78af367417b2b2512b00.md @@ -0,0 +1,96 @@ +--- +id: 587d78af367417b2b2512b00 +title: Use the align-self Property +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pVaDAv/cMbvzfv' +forumTopicId: 301107 +dashedName: use-the-align-self-property +--- + +# --description-- + +The final property for flex items is `align-self`. This property allows you to adjust each item's alignment individually, instead of setting them all at once. This is useful since other common adjustment techniques using the CSS properties `float`, `clear`, and `vertical-align` do not work on flex items. + +`align-self` accepts the same values as `align-items` and will override any value set by the `align-items` property. + +# --instructions-- + +Add the CSS property `align-self` to both `#box-1` and `#box-2`. Give `#box-1` a value of `center` and give `#box-2` a value of `flex-end`. + +# --hints-- + +The `#box-1` element should have the `align-self` property set to a value of `center`. + +```js +const boxOne = document.querySelector('#box-1'); +const alignment = window.getComputedStyle(boxOne)['align-self']; +assert.strictEqual(alignment, 'center'); +``` + +The `#box-2` element should have the `align-self` property set to a value of `flex-end`. + +```js +const boxTwo = document.querySelector('#box-2'); +const alignment = window.getComputedStyle(boxTwo)['align-self']; +assert.strictEqual(alignment, 'flex-end'); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
+
+
+``` + +# --solutions-- + +```html + + +
+
+
+
+``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a858944d96184f06fd60d61.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a858944d96184f06fd60d61.md new file mode 100644 index 0000000000000000000000000000000000000000..55e25e0f24e1ca143f9a7be3aa2303a406b67258 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a858944d96184f06fd60d61.md @@ -0,0 +1,78 @@ +--- +id: 5a858944d96184f06fd60d61 +title: Create Your First CSS Grid +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pByETK/cqwREC4' +forumTopicId: 301129 +dashedName: create-your-first-css-grid +--- + +# --description-- + +Turn any HTML element into a grid container by setting its `display` property to `grid`. This gives you the ability to use all the other properties associated with CSS Grid. + +**Note:** In CSS Grid, the parent element is referred to as the container and its children are called items. + +# --instructions-- + +Change the display of the div with the `container` class to `grid`. + +# --hints-- + +`container` class should have a `display` property with a value of `grid`. + +```js +assert.match(code, /.container\s*?{[\s\S]*display\s*?:\s*?grid\s*?;[\s\S]*}/gi); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +# --solutions-- + +```html + +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a9036d038fddaf9a66b5d32.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a9036d038fddaf9a66b5d32.md new file mode 100644 index 0000000000000000000000000000000000000000..39a8acd17e4d3390da898504c99e65c9498bc7bb --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a9036d038fddaf9a66b5d32.md @@ -0,0 +1,89 @@ +--- +id: 5a9036d038fddaf9a66b5d32 +title: Add Columns with grid-template-columns +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pByETK/c7NzDHv' +forumTopicId: 301117 +dashedName: add-columns-with-grid-template-columns +--- + +# --description-- + +Simply creating a grid element doesn't get you very far. You need to define the structure of the grid as well. To add some columns to the grid, use the `grid-template-columns` property on a grid container as demonstrated below: + +```css +.container { + display: grid; + grid-template-columns: 50px 50px; +} +``` + +This will give your grid two columns that are each 50px wide. The number of parameters given to the `grid-template-columns` property indicates the number of columns in the grid, and the value of each parameter indicates the width of each column. + +# --instructions-- + +Give the grid container three columns that are each `100px` wide. + +# --hints-- + +`container` class should have a `grid-template-columns` property with three units of `100px`. + +```js +const templateColumns = new __helpers.CSSHelp(document).getStyle( + '.container' +)?.gridTemplateColumns; +assert.strictEqual(templateColumns, '100px 100px 100px'); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +# --solutions-- + +```html + +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a9036e138fddaf9a66b5d33.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a9036e138fddaf9a66b5d33.md new file mode 100644 index 0000000000000000000000000000000000000000..92bac316f492dbf867ce4ffc3b42107f8ee021f7 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a9036e138fddaf9a66b5d33.md @@ -0,0 +1,81 @@ +--- +id: 5a9036e138fddaf9a66b5d33 +title: Add Rows with grid-template-rows +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pByETK/cbp9Pua' +forumTopicId: 301119 +dashedName: add-rows-with-grid-template-rows +--- + +# --description-- + +The grid you created in the last challenge will set the number of rows automatically. To adjust the rows manually, use the `grid-template-rows` property in the same way you used `grid-template-columns` in the previous challenge. + +# --instructions-- + +Add two rows to the grid that are `50px` tall each. + +# --hints-- + +`container` class should have a `grid-template-rows` property with two units of `50px`. + +```js +assert.match( + code, + /.container\s*?{[\s\S]*grid-template-rows\s*?:\s*?50px\s*?50px\s*?;[\s\S]*}/gi +); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +# --solutions-- + +```html + +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a9036ee38fddaf9a66b5d34.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a9036ee38fddaf9a66b5d34.md new file mode 100644 index 0000000000000000000000000000000000000000..158843b6695bbbaadb817ab9dc683a2c684e5a46 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a9036ee38fddaf9a66b5d34.md @@ -0,0 +1,96 @@ +--- +id: 5a9036ee38fddaf9a66b5d34 +title: Use CSS Grid units to Change the Size of Columns and Rows +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pByETK/cvE8phd' +forumTopicId: 301134 +dashedName: use-css-grid-units-to-change-the-size-of-columns-and-rows +--- + +# --description-- + +You can use absolute and relative units like `px` and `em` in CSS Grid to define the size of rows and columns. You can use these as well: + +`fr`: sets the column or row to a fraction of the available space, + +`auto`: sets the column or row to the width or height of its content automatically, + +`%`: adjusts the column or row to the percent width of its container. + +Here's the code that generates the output in the preview: + +```css +grid-template-columns: auto 50px 10% 2fr 1fr; +``` + +This snippet creates five columns. The first column is as wide as its content, the second column is 50px, the third column is 10% of its container, and for the last two columns; the remaining space is divided into three sections, two are allocated for the fourth column, and one for the fifth. + +# --instructions-- + +Make a grid with three columns whose widths are as follows: 1fr, 100px, and 2fr. + +# --hints-- + +Your `container` class should have a `grid-template-columns` property that has three columns with the following widths: `1fr`, `100px`, and `2fr`. + +```js +assert.match( + code, + /.container\s*?{[\s\S]*grid-template-columns\s*?:\s*?1fr\s*?100px\s*?2fr\s*?;[\s\S]*}/gi +); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +# --solutions-- + +```html + +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a9036ee38fddaf9a66b5d35.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a9036ee38fddaf9a66b5d35.md new file mode 100644 index 0000000000000000000000000000000000000000..c3f197c5f5bb0f07023fc1db34e9a093a3deb3a3 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a9036ee38fddaf9a66b5d35.md @@ -0,0 +1,89 @@ +--- +id: 5a9036ee38fddaf9a66b5d35 +title: Create a Column Gap Using grid-column-gap +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pByETK/cVZ8vfD' +forumTopicId: 301124 +dashedName: create-a-column-gap-using-grid-column-gap +--- + +# --description-- + +So far in the grids you have created, the columns have all been tight up against each other. Sometimes you want a gap in between the columns. To add a gap between the columns, use the `grid-column-gap` property like this: + +```css +grid-column-gap: 10px; +``` + +This creates 10px of empty space between all of our columns. + +# --instructions-- + +Give the columns in the grid a `20px` gap. + +# --hints-- + +`container` class should have a `grid-column-gap` property that has the value of `20px`. + +```js +assert.match( + code, + /.container\s*?{[\s\S]*grid-column-gap\s*?:\s*?20px\s*?;[\s\S]*}/gi +); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +# --solutions-- + +```html + +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a9036ee38fddaf9a66b5d36.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a9036ee38fddaf9a66b5d36.md new file mode 100644 index 0000000000000000000000000000000000000000..cecfccc770d2e783dcef3683b59899d7f1f70494 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a9036ee38fddaf9a66b5d36.md @@ -0,0 +1,83 @@ +--- +id: 5a9036ee38fddaf9a66b5d36 +title: Create a Row Gap using grid-row-gap +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pByETK/cPbJ2Cv' +forumTopicId: 301125 +dashedName: create-a-row-gap-using-grid-row-gap +--- + +# --description-- + +You can add a gap in between the rows of a grid using `grid-row-gap` in the same way that you added a gap in between columns in the previous challenge. + +# --instructions-- + +Create a gap for the rows that is `5px` tall. + +# --hints-- + +`container` class should have a `grid-row-gap` property that has the value of `5px`. + +```js +assert.match( + code, + /.container\s*?{[\s\S]*grid-row-gap\s*?:\s*?5px\s*?;[\s\S]*}/gi +); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +# --solutions-- + +```html + +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a9036ee38fddaf9a66b5d37.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a9036ee38fddaf9a66b5d37.md new file mode 100644 index 0000000000000000000000000000000000000000..a57a40bbd26c5df6d5bb2469b09c8927dbef8e36 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a9036ee38fddaf9a66b5d37.md @@ -0,0 +1,82 @@ +--- +id: 5a9036ee38fddaf9a66b5d37 +title: Add Gaps Faster with grid-gap +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pByETK/ca2qVtv' +forumTopicId: 301118 +dashedName: add-gaps-faster-with-grid-gap +--- + +# --description-- + +`grid-gap` is a shorthand property for `grid-row-gap` and `grid-column-gap` from the previous two challenges that's more convenient to use. If `grid-gap` has one value, it will create a gap between all rows and columns. However, if there are two values, it will use the first one to set the gap between the rows and the second value for the columns. + +# --instructions-- + +Use `grid-gap` to introduce a `10px` gap between the rows and `20px` gap between the columns. + +# --hints-- + +`container` class should have a `grid-gap` property that introduces a `10px` gap between the rows and a `20px` gap between the columns. + +```js +assert.match( + code, + /.container\s*?{[\s\S]*grid-gap\s*?:\s*?10px\s+?20px\s*?;[\s\S]*}/gi +); +``` + +# --seed-- + +## --seed-contents-- + +```html + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +# --solutions-- + +```html + +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a90372638fddaf9a66b5d38.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a90372638fddaf9a66b5d38.md new file mode 100644 index 0000000000000000000000000000000000000000..69e7fa5bb60c55cc38119494ed7198127eba62dc --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a90372638fddaf9a66b5d38.md @@ -0,0 +1,156 @@ +--- +id: 5a90372638fddaf9a66b5d38 +title: Use grid-column to Control Spacing +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pByETK/cnzkDSr' +forumTopicId: 301136 +dashedName: use-grid-column-to-control-spacing +--- + +# --description-- + +Up to this point, all the properties that have been discussed are for grid containers. The `grid-column` property is the first one for use on the grid items themselves. + +The hypothetical horizontal and vertical lines that create the grid are referred to as lines. These lines are numbered starting with 1 at the top left corner of the grid and move right for columns and down for rows, counting upward. + +This is what the lines look like for a 3x3 grid: + +

column lines

1

2

3

4

row lines

1

2

3

4

+ +To control the number of columns an item will consume, you can use the `grid-column` property in conjunction with the line numbers you want the item to start and stop at. + +Here's an example: + +```css +grid-column: 1 / 3; +``` + +This will make the item start at the first vertical line of the grid on the left and span to the 3rd line of the grid, consuming two columns. + +# --instructions-- + +Make the item with the class `item5` consume the last two columns of the grid. + +# --hints-- + +`item5` class should have a `grid-column` property. + +```js +const styleElement = document.querySelector('style:not(.fcc-hide-header)'); +assert.match( + __helpers.removeWhiteSpace(styleElement.textContent), + /\.item5{.*grid-column:.*}/g +); +``` + +`item5` class should have a `grid-column` property which results in it consuming the last two columns of the grid. + +```js +const itemFive = document.querySelector('.item5'); +const colStart = getComputedStyle(itemFive).gridColumnStart; +const colEnd = getComputedStyle(itemFive).gridColumnEnd; +const result = colStart.toString() + colEnd.toString(); +const correctResults = [ + '24', + '2-1', + '2span 2', + '2span2', + 'span 2-1', + '-12', + 'span 2span 2', + 'span 2auto', + 'autospan 2' +]; +assert.include(correctResults, result); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +# --solutions-- + +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a90373638fddaf9a66b5d39.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a90373638fddaf9a66b5d39.md new file mode 100644 index 0000000000000000000000000000000000000000..0765ba7d81194f19713db9664d5c417c05c2491d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a90373638fddaf9a66b5d39.md @@ -0,0 +1,141 @@ +--- +id: 5a90373638fddaf9a66b5d39 +title: Use grid-row to Control Spacing +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pByETK/c9WBLU4' +forumTopicId: 301137 +dashedName: use-grid-row-to-control-spacing +--- + +# --description-- + +Of course, you can make items consume multiple rows just like you can with columns. You define the horizontal lines you want an item to start and stop at using the `grid-row` property on a grid item. + +# --instructions-- + +Make the element with the `item5` class consume the last two rows. + +# --hints-- + +`item5` class should have a `grid-row` property. + +```js +const styleElement = document.querySelector('style:not(.fcc-hide-header)'); +assert.match( + __helpers.removeWhiteSpace(styleElement.textContent), + /\.item5{.*grid-row:.*}/g +); +``` + +`item5` class should have a `grid-row` property which results in it consuming the last two rows of the grid. + +```js +const itemFive = document.querySelector('.item5'); +const rowStart = getComputedStyle(itemFive).gridRowStart; +const rowEnd = getComputedStyle(itemFive).gridRowEnd; +const result = rowStart.toString() + rowEnd.toString(); +const correctResults = [ + '24', + '2-1', + '2span 2', + '2span2', + 'span 2-1', + '-12', + 'span 2span 2', + 'span 2auto', + 'autospan 2' +]; +assert.include(correctResults, result); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +# --solutions-- + +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a90374338fddaf9a66b5d3a.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a90374338fddaf9a66b5d3a.md new file mode 100644 index 0000000000000000000000000000000000000000..530ba569e3a1383e801aea92624c5fb94bc9b0f8 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a90374338fddaf9a66b5d3a.md @@ -0,0 +1,92 @@ +--- +id: 5a90374338fddaf9a66b5d3a +title: Align an Item Horizontally using justify-self +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pByETK/cJbpKHq' +forumTopicId: 301122 +dashedName: align-an-item-horizontally-using-justify-self +--- + +# --description-- + +In CSS Grid, the content of each item is located in a box which is referred to as a cell. You can align the content's position within its cell horizontally using the `justify-self` property on a grid item. By default, this property has a value of `stretch`, which will make the content fill the whole width of the cell. This CSS Grid property accepts other values as well: + +`start`: aligns the content at the left of the cell, + +`center`: aligns the content in the center of the cell, + +`end`: aligns the content at the right of the cell. + +# --instructions-- + +Use the `justify-self` property to center the item with the class `item2`. + +# --hints-- + +`item2` class should have a `justify-self` property that has the value of `center`. + +```js +assert.match( + code, + /.item2\s*?{[\s\S]*justify-self\s*?:\s*?center\s*?;[\s\S]*}/gi +); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +# --solutions-- + +```html + +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a90375238fddaf9a66b5d3b.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a90375238fddaf9a66b5d3b.md new file mode 100644 index 0000000000000000000000000000000000000000..89270352eaa620ac0b5b2c65b898703a5d688854 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a90375238fddaf9a66b5d3b.md @@ -0,0 +1,83 @@ +--- +id: 5a90375238fddaf9a66b5d3b +title: Align an Item Vertically using align-self +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pByETK/cmzd4fz' +forumTopicId: 301123 +dashedName: align-an-item-vertically-using-align-self +--- + +# --description-- + +Just as you can align an item horizontally, there's a way to align an item vertically as well. To do this, you use the `align-self` property on an item. This property accepts all of the same values as `justify-self` from the last challenge. + +# --instructions-- + +Align the item with the class `item3` vertically at the `end`. + +# --hints-- + +`item3` class should have a `align-self` property that has the value of `end`. + +```js +assert.match(code, /.item3\s*?{[\s\S]*align-self\s*?:\s*?end\s*?;[\s\S]*}/gi); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +# --solutions-- + +```html + +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a90376038fddaf9a66b5d3c.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a90376038fddaf9a66b5d3c.md new file mode 100644 index 0000000000000000000000000000000000000000..6b8691666f6a13158e2c095d4f5989866d490cf0 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a90376038fddaf9a66b5d3c.md @@ -0,0 +1,84 @@ +--- +id: 5a90376038fddaf9a66b5d3c +title: Align All Items Horizontally using justify-items +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pByETK/cJbpECn' +forumTopicId: 301120 +dashedName: align-all-items-horizontally-using-justify-items +--- + +# --description-- + +Sometimes you want all the items in your CSS Grid to share the same alignment. You can use the previously learned properties and align them individually, or you can align them all at once horizontally by using `justify-items` on your grid container. This property can accept all the same values you learned about in the previous two challenges, the difference being that it will move **all** the items in our grid to the desired alignment. + +# --instructions-- + +Use this property to center all our items horizontally. + +# --hints-- + +`container` class should have a `justify-items` property that has the value of `center`. + +```js +assert.match( + code, + /.container\s*?{[\s\S]*justify-items\s*?:\s*?center\s*?;[\s\S]*}/gi +); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +# --solutions-- + +```html + +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fdf869fb03452672e45b.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fdf869fb03452672e45b.md new file mode 100644 index 0000000000000000000000000000000000000000..d9eeedf40e63c9f1e5dcfee1d5f92bc05dbb78b9 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fdf869fb03452672e45b.md @@ -0,0 +1,84 @@ +--- +id: 5a94fdf869fb03452672e45b +title: Align All Items Vertically using align-items +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pByETK/ckzPeUv' +forumTopicId: 301121 +dashedName: align-all-items-vertically-using-align-items +--- + +# --description-- + +Using the `align-items` property on a grid container will set the vertical alignment for all the items in our grid. + +# --instructions-- + +Use it now to move all the items to the end of each cell. + +# --hints-- + +`container` class should have a `align-items` property that has the value of `end`. + +```js +assert.match( + code, + /.container\s*?{[\s\S]*align-items\s*?:\s*?end\s*?;[\s\S]*}/gi +); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +# --solutions-- + +```html + +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fe0569fb03452672e45c.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fe0569fb03452672e45c.md new file mode 100644 index 0000000000000000000000000000000000000000..6269a4f196ce551b7e10c88cde3c0b08f63f545b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fe0569fb03452672e45c.md @@ -0,0 +1,130 @@ +--- +id: 5a94fe0569fb03452672e45c +title: Divide the Grid Into an Area Template +challengeType: 0 +forumTopicId: 301130 +dashedName: divide-the-grid-into-an-area-template +--- + +# --description-- + +You can group cells of your grid together into an area and give the area a custom name. Do this by using `grid-template-areas` on the container like this: + +```css +grid-template-areas: + 'header header header' + 'advert content content' + 'advert footer footer'; +``` + +The code above groups the cells of the grid into four areas: `header`, `advert`, `content`, and `footer`. Every word represents a cell and every pair of quotation marks represent a row. + +# --instructions-- + +Change the template so the `footer` area spans the entire bottom row. Defining the areas won't have any visual effect right now. Later, you will make an item use an area to see how it works. + +# --hints-- + +`container` class should have a `grid-template-areas` property similar to the example but with the `footer` area spanning the whole bottom row. + +```js +assert.match( + __helpers.removeCssComments(code), + /.container\s*?{[\s\S]*grid-template-areas\s*?:\s*?["|']\s*?header\s*?header\s*?header\s*?["|']\s*?["|']\s*?advert\s*?content\s*?content\s*?["|']\s*?["|']\s*?footer\s*?footer\s*?footer\s*?["|']\s*?;[\s\S]*}/gi +); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +# --solutions-- + +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fe1369fb03452672e45d.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fe1369fb03452672e45d.md new file mode 100644 index 0000000000000000000000000000000000000000..a50e2e3b0aa10ca3f7698fb4bed3c1116046be3f --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fe1369fb03452672e45d.md @@ -0,0 +1,97 @@ +--- +id: 5a94fe1369fb03452672e45d +title: Place Items in Grid Areas Using the grid-area Property +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pByETK/cRrqmtV' +forumTopicId: 301132 +dashedName: place-items-in-grid-areas-using-the-grid-area-property +--- + +# --description-- + +After creating an area template for your grid container, as shown in the previous challenge, you can place an item in your custom area by referencing the name you gave it. To do this, you use the `grid-area` property on an item like this: + +```css +.item1 { + grid-area: header; +} +``` + +This lets the grid know that you want the `item1` class to go in the area named `header`. In this case, the item will use the entire top row because that whole row is named as the `header` area. + +# --instructions-- + +Place an element with the `item5` class in the `footer` area using the `grid-area` property. + +# --hints-- + +`item5` class should have a `grid-area` property that has the value of `footer`. + +```js +assert.match( + __helpers.removeCssComments(code), + /.item5\s*?{[\s\S]*grid-area\s*?:\s*?footer\s*?;[\s\S]*}/gi +); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +# --solutions-- + +```html + +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fe2669fb03452672e45e.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fe2669fb03452672e45e.md new file mode 100644 index 0000000000000000000000000000000000000000..d57a4e168710f57f248f9f5379866c2a88563dac --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fe2669fb03452672e45e.md @@ -0,0 +1,100 @@ +--- +id: 5a94fe2669fb03452672e45e +title: Use grid-area Without Creating an Areas Template +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pByETK/c6N7VhK' +forumTopicId: 301135 +dashedName: use-grid-area-without-creating-an-areas-template +--- + +# --description-- + +The `grid-area` property you learned in the last challenge can be used in another way. If your grid doesn't have an areas template to reference, you can create an area on the fly for an item to be placed like this: + +```css +item1 { + grid-area: 1/1/2/4; +} +``` + +This is using the line numbers you learned about earlier to define where the area for this item will be. The numbers in the example above represent these values: + +```css +grid-area: horizontal line to start at / vertical line to start at / horizontal + line to end at / vertical line to end at; +``` + +So the item in the example will consume the rows between lines 1 and 2, and the columns between lines 1 and 4. + +# --instructions-- + +Using the `grid-area` property, place the element with `item5` class between the third and fourth horizontal lines and between the first and fourth vertical lines. + +# --hints-- + +The `item5` class should have a `grid-area` property to make it fill the whole area between the third and fourth horizontal lines, and first and fourth vertical lines. + +```js +assert.match( + code, + /.item5\s*?{[\s\S]*grid-area\s*?:\s*?3\s*?\/\s*?1\s*?\/\s*?4\s*?\/\s*?4\s*?;[\s\S]*}/gi +); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +# --solutions-- + +```html + +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fe3669fb03452672e45f.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fe3669fb03452672e45f.md new file mode 100644 index 0000000000000000000000000000000000000000..11268bc81f5cbceafeed2f3faf2aa647765f0e8b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fe3669fb03452672e45f.md @@ -0,0 +1,106 @@ +--- +id: 5a94fe3669fb03452672e45f +title: Reduce Repetition Using the repeat Function +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pByETK/cQvqyHR' +forumTopicId: 301133 +dashedName: reduce-repetition-using-the-repeat-function +--- + +# --description-- + +When you used `grid-template-columns` and `grid-template-rows` to define the structure of a grid, you entered a value for each row or column you created. + +Let's say you want a grid with 100 rows of the same height. It isn't very practical to insert 100 values individually. Fortunately, there's a better way - by using the `repeat` function to specify the number of times you want your column or row to be repeated, followed by a comma and the value you want to repeat. + +Here's an example that would create the 100 row grid, each row at 50px tall. + +```css +grid-template-rows: repeat(100, 50px); +``` + +You can also repeat multiple values with the repeat function and insert the function amongst other values when defining a grid structure. Here's what that looks like: + +```css +grid-template-columns: repeat(2, 1fr 50px) 20px; +``` + +This translates to: + +```css +grid-template-columns: 1fr 50px 1fr 50px 20px; +``` + +**Note:** The `1fr 50px` is repeated twice followed by 20px. + +# --instructions-- + +Use `repeat` to remove repetition from the `grid-template-columns` property. + +# --hints-- + +`container` class should have a `grid-template-columns` property that is set to repeat 3 columns with the width of `1fr`. + +```js +assert.match( + code, + /.container\s*?{[\s\S]*grid-template-columns\s*?:\s*?repeat\s*?\(\s*?3\s*?,\s*?1fr\s*?\)\s*?;[\s\S]*}/gi +); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +# --solutions-- + +```html + +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fe4469fb03452672e460.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fe4469fb03452672e460.md new file mode 100644 index 0000000000000000000000000000000000000000..d755d1f4dba6567c9af63bb9cb640a1be8e8b73f --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fe4469fb03452672e460.md @@ -0,0 +1,90 @@ +--- +id: 5a94fe4469fb03452672e460 +title: Limit Item Size Using the minmax Function +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pByETK/cD97RTv' +forumTopicId: 301131 +dashedName: limit-item-size-using-the-minmax-function +--- + +# --description-- + +There's another built-in function to use with `grid-template-columns` and `grid-template-rows` called `minmax`. It's used to limit the size of items when the grid container changes size. To do this you need to specify the acceptable size range for your item. Here is an example: + +```css +grid-template-columns: 100px minmax(50px, 200px); +``` + +In the code above, `grid-template-columns` is set to create two columns; the first is 100px wide, and the second has the minimum width of 50px and the maximum width of 200px. + +# --instructions-- + +Using the `minmax` function, replace the `1fr` in the `repeat` function with a column size that has the minimum width of `90px` and the maximum width of `1fr`, and resize the preview panel to see the effect. + +# --hints-- + +`container` class should have a `grid-template-columns` property that is set to repeat 3 columns with the minimum width of `90px` and maximum width of `1fr`. + +```js +assert.match( + code, + /.container\s*?{[\s\S]*grid-template-columns\s*?:\s*?repeat\s*?\(\s*?3\s*?,\s*?minmax\s*?\(\s*?90px\s*?,\s*?1fr\s*?\)\s*?\)\s*?;[\s\S]*}/gi +); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +# --solutions-- + +```html + +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fe5469fb03452672e461.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fe5469fb03452672e461.md new file mode 100644 index 0000000000000000000000000000000000000000..9a55800b117b6205f7486f765456cba416674ed4 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fe5469fb03452672e461.md @@ -0,0 +1,159 @@ +--- +id: 5a94fe5469fb03452672e461 +title: Create Flexible Layouts Using auto-fill +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pByETK/cmzdycW' +forumTopicId: 301126 +dashedName: create-flexible-layouts-using-auto-fill +--- + +# --description-- + +The repeat function comes with an option called auto-fill. This allows you to automatically insert as many rows or columns of your desired size as possible depending on the size of the container. You can create flexible layouts when combining `auto-fill` with `minmax`, like this: + +```css +repeat(auto-fill, minmax(60px, 1fr)); +``` + +When the container changes size, this setup keeps inserting 60px columns and stretching them until it can insert another one. **Note:** If your container can't fit all your items on one row, it will move them down to a new one. + +# --instructions-- + +In the first grid, use `auto-fill` with `repeat` to fill the grid with columns that have a minimum width of `60px` and maximum of `1fr`. Then resize the preview to see auto-fill in action. + +# --hints-- + +`container` class should have a `grid-template-columns` property with `repeat` and `auto-fill` that will fill the grid with columns that have a minimum width of `60px` and maximum of `1fr`. + +```js +assert.match( + code, + /.container\s*?{[\s\S]*grid-template-columns\s*?:\s*?repeat\s*?\(\s*?auto-fill\s*?,\s*?minmax\s*?\(\s*?60px\s*?,\s*?1fr\s*?\)\s*?\)\s*?;[\s\S]*}/gi +); +``` + +# --seed-- + +## --seed-contents-- + +```html + +
+
1
+
2
+
3
+
4
+
5
+
+
+
1
+
2
+
3
+
4
+
5
+
+``` + +# --solutions-- + +```html + +
+
1
+
2
+
3
+
4
+
5
+
+
+
1
+
2
+
3
+
4
+
5
+
+``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fe6269fb03452672e462.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fe6269fb03452672e462.md new file mode 100644 index 0000000000000000000000000000000000000000..ee551ab2d55037f213f7610e6e2aedd664bb530a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fe6269fb03452672e462.md @@ -0,0 +1,107 @@ +--- +id: 5a94fe6269fb03452672e462 +title: Create Flexible Layouts Using auto-fit +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pByETK/c3dPph8' +forumTopicId: 301127 +dashedName: create-flexible-layouts-using-auto-fit +--- + +# --description-- + +`auto-fit` works almost identically to `auto-fill`. The only difference is that when the container's size exceeds the size of all the items combined, `auto-fill` keeps inserting empty rows or columns and pushes your items to the side, while `auto-fit` collapses those empty rows or columns and stretches your items to fit the size of the container. + +**Note:** If your container can't fit all your items on one row, it will move them down to a new one. + +# --instructions-- + +In the second grid, use `auto-fit` with `repeat` to fill the grid with columns that have a minimum width of `60px` and maximum of `1fr`. Then resize the preview to see the difference. + +# --hints-- + +`container2` class should have a `grid-template-columns` property with `repeat` and `auto-fit` that will fill the grid with columns that have a minimum width of `60px` and a maximum of `1fr`. + +```js +assert.match( + code, + /.container2\s*?{[\s\S]*grid-template-columns\s*?:\s*?repeat\s*?\(\s*?auto-fit\s*?,\s*?minmax\s*?\(\s*?60px\s*?,\s*?1fr\s*?\)\s*?\)\s*?;[\s\S]*}/gi +); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+
+
1
+
2
+
3
+
4
+
5
+
+``` + +# --solutions-- + +```html + +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fe7769fb03452672e463.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fe7769fb03452672e463.md new file mode 100644 index 0000000000000000000000000000000000000000..bcf82806b3f744d7884ae4721bb804aceb10ae9f --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fe7769fb03452672e463.md @@ -0,0 +1,171 @@ +--- +id: 5a94fe7769fb03452672e463 +title: Use Media Queries to Create Responsive Layouts +challengeType: 0 +videoUrl: 'https://scrimba.com/p/pByETK/cMbqeHk' +forumTopicId: 301138 +dashedName: use-media-queries-to-create-responsive-layouts +--- + +# --description-- + +CSS Grid can be an easy way to make your site more responsive by using media queries to rearrange grid areas, change dimensions of a grid, and rearrange the placement of items. + +In the preview, when the viewport width is 300px or more, the number of columns changes from 1 to 2. The advertisement area then occupies the left column completely. + +# --instructions-- + +When the viewport width is `400px` or more, make the header area occupy the top row completely and the footer area occupy the bottom row completely. + +# --hints-- + +When the viewport is `400px` or more, `container` class should have a `grid-template-areas` property in which the header and footer areas occupy the top and bottom rows respectively and advert and content occupy the left and right columns of the middle row. + +```js +assert.match( + __helpers.removeCssComments(code), + /@media\s*?\(\s*?min-width\s*?:\s*?400px\s*?\)[\s\S]*.container\s*?{[\s\S]*grid-template-areas\s*?:\s*?["|']\s*?header\s*?header\s*?["|']\s*?["|']\s*?advert\s*?content\s*?["|']\s*?["|']\s*?footer\s*?footer\s*?["|']\s*?;[\s\S]*}/gi +); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
header
+
advert
+
content
+
footer
+
+``` + +# --solutions-- + +```html + + +
+
header
+
advert
+
content
+
footer
+
+``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fe8569fb03452672e464.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fe8569fb03452672e464.md new file mode 100644 index 0000000000000000000000000000000000000000..ca919727b126a50b7c1c8b814a91e0658ed11c18 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/css-grid/5a94fe8569fb03452672e464.md @@ -0,0 +1,109 @@ +--- +id: 5a94fe8569fb03452672e464 +title: Create Grids within Grids +challengeType: 0 +forumTopicId: 301128 +dashedName: create-grids-within-grids +--- + +# --description-- + +Turning an element into a grid only affects the behavior of its direct descendants. So by turning a direct descendant into a grid, you have a grid within a grid. + +For example, by setting the `display` and `grid-template-columns` properties of the element with the `item3` class, you create a grid within your grid. + +# --instructions-- + +Turn the element with the `item3` class into a grid with two columns with a width of `auto` and `1fr` using `display` and `grid-template-columns`. + +# --hints-- + +`item3` class should have a `grid-template-columns` property with `auto` and `1fr` as values. + +```js +assert.match( + code, + /.item3\s*?{[\s\S]*grid-template-columns\s*?:\s*?auto\s*?1fr\s*?;[\s\S]*}/gi +); +``` + +`item3` class should have a `display` property with the value of `grid`. + +```js +assert.match(code, /.item3\s*?{[\s\S]*display\s*?:\s*?grid\s*?;[\s\S]*}/gi); +``` + +# --seed-- + +## --seed-contents-- + +```html + + +
+
header
+
advert
+
+
paragraph1
+
paragraph2
+
+
footer
+
+``` + +# --solutions-- + +```html + +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6814d8e1516e86b171929de4.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6814d8e1516e86b171929de4.md new file mode 100644 index 0000000000000000000000000000000000000000..b1a2041b2fee2de2bd7c213ddc47c765a5ca725e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6814d8e1516e86b171929de4.md @@ -0,0 +1,90 @@ +--- +id: 6814d8e1516e86b171929de4 +title: "Challenge 1: Vowel Balance" +challengeType: 28 +dashedName: challenge-1 +--- + +# --description-- + +Given a string, determine whether the number of vowels in the first half of the string is equal to the number of vowels in the second half. + +- The string can contain any characters. +- The letters `a`, `e`, `i`, `o`, and `u`, in either uppercase or lowercase, are considered vowels. +- If there's an odd number of characters in the string, ignore the center character. + +# --hints-- + +`isBalanced("racecar")` should return `true`. + +```js +assert.isTrue(isBalanced("racecar")); +``` + +`isBalanced("Lorem Ipsum")` should return `true`. + +```js +assert.isTrue(isBalanced("Lorem Ipsum")); +``` + +`isBalanced("Kitty Ipsum")` should return `false`. + +```js +assert.isFalse(isBalanced("Kitty Ipsum")); +``` + +`isBalanced("string")` should return `false`. + +```js +assert.isFalse(isBalanced("string")); +``` + +`isBalanced(" ")` should return `true`. + +```js +assert.isTrue(isBalanced(" ")); +``` + +`isBalanced("abcdefghijklmnopqrstuvwxyz")` should return `false`. + +```js +assert.isFalse(isBalanced("abcdefghijklmnopqrstuvwxyz")); +``` + +`isBalanced("123A#b!E&*456-o.U")` should return `true`. + +```js +assert.isTrue(isBalanced("123A#b!E&*456-o.U")); +``` + +# --seed-- + +## --seed-contents-- + +```js +function isBalanced(s) { + + return s; +} +``` + +# --solutions-- + +```js +function isBalanced(s) { + const vowels = 'aeiou'; + const half = Math.floor(s.length / 2); + + let firstHalf = s.slice(0, half); + let secondHalf = s.length % 2 === 0 ? s.slice(half) : s.slice(half + 1); + + const countVowels = str => + str + .toLowerCase() + .split('') + .filter(c => vowels.includes(c)) + .length; + + return countVowels(firstHalf) === countVowels(secondHalf); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/681cb05adab50c87ddb2e513.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/681cb05adab50c87ddb2e513.md new file mode 100644 index 0000000000000000000000000000000000000000..f964e3aed86362e0800279dd81ec1682e928c91a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/681cb05adab50c87ddb2e513.md @@ -0,0 +1,138 @@ +--- +id: 681cb05adab50c87ddb2e513 +title: "Challenge 2: Base Check" +challengeType: 28 +dashedName: challenge-2 +--- + +# --description-- + +Given a string representing a number, and an integer base from 2 to 36, determine whether the number is valid in that base. + +- The string may contain integers, and uppercase or lowercase characters. +- The check should be case-insensitive. +- The base can be any number 2-36. +- A number is valid if every character is a valid digit in the given base. +- Example of valid digits for bases: + - Base 2: 0-1 + - Base 8: 0-7 + - Base 10: 0-9 + - Base 16: 0-9 and A-F + - Base 36: 0-9 and A-Z + +# --hints-- + +`isValidNumber("10101", 2)` should return `true`. + +```js +assert.isTrue(isValidNumber("10101", 2)) +``` + +`isValidNumber("10201", 2)` should return `false`. + +```js +assert.isFalse(isValidNumber("10201", 2)) +``` + +`isValidNumber("76543210", 8)` should return `true`. + +```js +assert.isTrue(isValidNumber("76543210", 8)) +``` + +`isValidNumber("9876543210", 8)` should return `false`. + +```js +assert.isFalse(isValidNumber("9876543210", 8)) +``` + +`isValidNumber("9876543210", 10)` should return `true`. + +```js +assert.isTrue(isValidNumber("9876543210", 10)) +``` + +`isValidNumber("ABC", 10)` should return `false`. + +```js +assert.isFalse(isValidNumber("ABC", 10)) +``` + +`isValidNumber("ABC", 16)` should return `true`. + +```js +assert.isTrue(isValidNumber("ABC", 16)) +``` + +`isValidNumber("Z", 36)` should return `true`. + +```js +assert.isTrue(isValidNumber("Z", 36)) +``` + +`isValidNumber("ABC", 20)` should return `true`. + +```js +assert.isTrue(isValidNumber("ABC", 20)) +``` + +`isValidNumber("4B4BA9", 16)` should return `true`. + +```js +assert.isTrue(isValidNumber("4B4BA9", 16)) +``` + +`isValidNumber("5G3F8F", 16)` should return `false`. + +```js +assert.isFalse(isValidNumber("5G3F8F", 16)) +``` + +`isValidNumber("5G3F8F", 17)` should return `true`. + +```js +assert.isTrue(isValidNumber("5G3F8F", 17)) +``` + +`isValidNumber("abc", 10)` should return `false`. + +```js +assert.isFalse(isValidNumber("abc", 10)) +``` + +`isValidNumber("abc", 16)` should return `true`. + +```js +assert.isTrue(isValidNumber("abc", 16)) +``` + +`isValidNumber("AbC", 16)` should return `true`. + +```js +assert.isTrue(isValidNumber("AbC", 16)) +``` + +`isValidNumber("z", 36)` should return `true`. + +```js +assert.isTrue(isValidNumber("z", 36)) +``` + +# --seed-- + +## --seed-contents-- + +```js +function isValidNumber(n, base) { + + return n; +} +``` + +# --solutions-- + +```js +function isValidNumber(n, base) { + return new RegExp(`^[${'0123456789abcdefghijklmnopqrstuvwxyz'.substring(0, base)}]+\$`, "i").test(n); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/681cb1a2dab50c87ddb2e514.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/681cb1a2dab50c87ddb2e514.md new file mode 100644 index 0000000000000000000000000000000000000000..595bf951d567fc5a64ae48007cb9322a910b1092 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/681cb1a2dab50c87ddb2e514.md @@ -0,0 +1,76 @@ +--- +id: 681cb1a2dab50c87ddb2e514 +title: "Challenge 3: Fibonacci Sequence" +challengeType: 28 +dashedName: challenge-3 +--- + +# --description-- + +The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. When starting with `0` and `1`, the first 10 numbers in the sequence are `0`, `1`, `1`, `2`, `3`, `5`, `8`, `13`, `21`, `34`. + +Given an array containing the first two numbers of a Fibonacci sequence, and an integer representing the length of the sequence, return an array containing the sequence of the given length. + +- Your function should handle sequences of any length greater than or equal to zero. +- If the length is zero, return an empty array. +- Note that the starting numbers are part of the sequence. + +# --hints-- + +`fibonacciSequence([0, 1], 20)` should return `[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]`. + +```js +assert.deepEqual(fibonacciSequence([0, 1], 20), [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]); +``` + +`fibonacciSequence([21, 32], 1)` should return `[21]`. + +```js +assert.deepEqual(fibonacciSequence([21, 32], 1), [21]); +``` + +`fibonacciSequence([0, 1], 0)` should return `[]`. + +```js +assert.deepEqual(fibonacciSequence([0, 1], 0), []); +``` + +`fibonacciSequence([10, 20], 2)` should return `[10, 20]`. + +```js +assert.deepEqual(fibonacciSequence([10, 20], 2), [10, 20]); +``` + +`fibonacciSequence([123456789, 987654321], 5)` should return `[123456789, 987654321, 1111111110, 2098765431, 3209876541]`. + +```js +assert.deepEqual(fibonacciSequence([123456789, 987654321], 5), [123456789, 987654321, 1111111110, 2098765431, 3209876541]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function fibonacciSequence(startSequence, length) { + + return length; +} +``` + +# --solutions-- + +```js +function fibonacciSequence(startSequence, length) { + if (length === 0) return []; + if (length === 1) return [startSequence[0]]; + if (length === 2) return [...startSequence]; + + const sequence = [...startSequence]; + while (sequence.length < length) { + const nextValue = sequence[sequence.length - 1] + sequence[sequence.length - 2]; + sequence.push(nextValue); + } + return sequence; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/681cb1afdab50c87ddb2e515.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/681cb1afdab50c87ddb2e515.md new file mode 100644 index 0000000000000000000000000000000000000000..d5873732ee1302e7f4253300078a755924c077f2 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/681cb1afdab50c87ddb2e515.md @@ -0,0 +1,63 @@ +--- +id: 681cb1afdab50c87ddb2e515 +title: "Challenge 4: S P A C E J A M" +challengeType: 28 +dashedName: challenge-4 +--- + +# --description-- + +Given a string, remove all spaces from the string, insert two spaces between every character, convert all alphabetical letters to uppercase, and return the result. + +- Non-alphabetical characters should remain unchanged (except for spaces). + +# --hints-- + +`spaceJam("freeCodeCamp")` should return `"F R E E C O D E C A M P"`. + +```js +assert.equal(spaceJam("freeCodeCamp"), "F R E E C O D E C A M P"); +``` + +`spaceJam(" free Code Camp ")` should return `"F R E E C O D E C A M P"`. + +```js +assert.equal(spaceJam(" free Code Camp "), "F R E E C O D E C A M P"); +``` + +`spaceJam("Hello World?!")` should return `"H E L L O W O R L D ? !"`. + +```js +assert.equal(spaceJam("Hello World?!"), "H E L L O W O R L D ? !"); +``` + +`spaceJam("C@t$ & D0g$")` should return `"C @ T $ & D 0 G $"`. + +```js +assert.equal(spaceJam("C@t$ & D0g$"), "C @ T $ & D 0 G $"); +``` + +`spaceJam("allyourbase")` should return `"A L L Y O U R B A S E"`. + +```js +assert.equal(spaceJam("all your base"), "A L L Y O U R B A S E"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function spaceJam(s) { + + return s; +} +``` + +# --solutions-- + +```js +function spaceJam(s) { + return s.toUpperCase().replace(/\s+/g, '').split('').join(' '); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/681cb1afdab50c87ddb2e516.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/681cb1afdab50c87ddb2e516.md new file mode 100644 index 0000000000000000000000000000000000000000..ef4348fc19a79b42e47dfd35ab4d9fa9bbfaa92c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/681cb1afdab50c87ddb2e516.md @@ -0,0 +1,72 @@ +--- +id: 681cb1afdab50c87ddb2e516 +title: "Challenge 5: Jbelmud Text" +challengeType: 28 +dashedName: challenge-5 +--- + +# --description-- + +Given a string, return a jumbled version of that string where each word is transformed using the following constraints: + +- The first and last letters of the words remain in place +- All letters between the first and last letter are sorted alphabetically. +- The input strings will contain no punctuation, and will be entirely lowercase. + +# --hints-- + +`jbelmu("hello world")` should return `"hello wlord"`. + +```js +assert.equal(jbelmu("hello world"), "hello wlord"); +``` + +`jbelmu("i love jumbled text")` should return `"i love jbelmud text"`. + +```js +assert.equal(jbelmu("i love jumbled text"), "i love jbelmud text"); +``` + +`jbelmu("freecodecamp is my favorite place to learn to code")` should return `"faccdeeemorp is my faiortve pacle to laern to cdoe"`. + +```js +assert.equal(jbelmu("freecodecamp is my favorite place to learn to code"), "faccdeeemorp is my faiortve pacle to laern to cdoe"); +``` + +`jbelmu("the quick brown fox jumps over the lazy dog")` should return `"the qciuk borwn fox jmpus oevr the lazy dog"`. + +```js +assert.equal(jbelmu("the quick brown fox jumps over the lazy dog"), "the qciuk borwn fox jmpus oevr the lazy dog"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function jbelmu(text) { + + return text; +} +``` + +# --solutions-- + +```js +function jbelmu(text) { + return text + .split(' ') + .map((word) => { + if (word.length <= 3) return word; + const first = word[0]; + const last = word[word.length - 1]; + const middle = word + .slice(1, -1) + .split('') + .sort() + .join(''); + return first + middle + last; + }) + .join(' '); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/681cb1afdab50c87ddb2e517.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/681cb1afdab50c87ddb2e517.md new file mode 100644 index 0000000000000000000000000000000000000000..bbd5d744028f0f6932d11958c02f64d098f41037 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/681cb1afdab50c87ddb2e517.md @@ -0,0 +1,72 @@ +--- +id: 681cb1afdab50c87ddb2e517 +title: "Challenge 6: Anagram Checker" +challengeType: 28 +dashedName: challenge-6 +--- + +# --description-- + +Given two strings, determine if they are anagrams of each other (contain the same characters in any order). + +- Ignore casing and white space. + +# --hints-- + +`areAnagrams("listen", "silent")` should return `true`. + +```js +assert.isTrue(areAnagrams("listen", "silent")); +``` + +`areAnagrams("School master", "The classroom")` should return `true`. + +```js +assert.isTrue(areAnagrams("School master", "The classroom")); +``` + +`areAnagrams("A gentleman", "Elegant man")` should return `true`. + +```js +assert.isTrue(areAnagrams("A gentleman", "Elegant man")); +``` + +`areAnagrams("Hello", "World")` should return `false`. + +```js +assert.isFalse(areAnagrams("Hello", "World")); +``` + +`areAnagrams("apple", "banana")` should return `false`. + +```js +assert.isFalse(areAnagrams("apple", "banana")); +``` + +`areAnagrams("cat", "dog")` should return `false`. + +```js +assert.isFalse(areAnagrams("cat", "dog")); +``` + +# --seed-- + +## --seed-contents-- + +```js +function areAnagrams(str1, str2) { + + return str1; +} +``` + +# --solutions-- + +```js +function areAnagrams(str1, str2) { + const clean = (str) => + str.replace(/\s+/g, '').toLowerCase().split('').sort().join(''); + + return clean(str1) === clean(str2); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/681cb1b0dab50c87ddb2e518.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/681cb1b0dab50c87ddb2e518.md new file mode 100644 index 0000000000000000000000000000000000000000..763409a30950e981f607e642ffbb488d5321659c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/681cb1b0dab50c87ddb2e518.md @@ -0,0 +1,64 @@ +--- +id: 681cb1b0dab50c87ddb2e518 +title: "Challenge 7: Targeted Sum" +challengeType: 28 +dashedName: challenge-7 +--- + +# --description-- + +Given an array of numbers and an integer target, find two unique numbers in the array that add up to the target value. Return an array with the indices of those two numbers, or `"Target not found"` if no two numbers sum up to the target. + +- The returned array should have the indices in ascending order. + +# --hints-- + +`findTarget([2, 7, 11, 15], 9)` should return `[0, 1]`. + +```js +assert.deepEqual(findTarget([2, 7, 11, 15], 9), [0, 1]); +``` + +`findTarget([3, 2, 4, 5], 6)` should return `[1, 2]`. + +```js +assert.deepEqual(findTarget([3, 2, 4, 5], 6), [1, 2]); +``` + +`findTarget([1, 3, 5, 6, 7, 8], 15)` should return `[4, 5]`. + +```js +assert.deepEqual(findTarget([1, 3, 5, 6, 7, 8], 15), [4, 5]); +``` + +`findTarget([1, 3, 5, 7], 14)` should return `"Target not found"`. + +```js +assert.equal(findTarget([1, 3, 5, 7], 14), "Target not found"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function findTarget(arr, target) { + + return arr; +} +``` + +# --solutions-- + +```js +function findTarget(arr, target) { + for (let i = 0; i < arr.length; i++) { + for (let j = i + 1; j < arr.length; j++) { + if (arr[i] + arr[j] === target) { + return [i, j]; + } + } + } + return 'Target not found' +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/681cb1b0dab50c87ddb2e519.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/681cb1b0dab50c87ddb2e519.md new file mode 100644 index 0000000000000000000000000000000000000000..a3b45995eb7efb4d118c204589b2ed80efbe49aa --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/681cb1b0dab50c87ddb2e519.md @@ -0,0 +1,51 @@ +--- +id: 681cb1b0dab50c87ddb2e519 +title: "Challenge 8: Factorializer" +challengeType: 28 +dashedName: challenge-8 +--- + +# --description-- + +Given an integer from zero to 20, return the factorial of that number. The factorial of a number is the product of all the numbers between 1 and the given number. + +- The factorial of zero is 1. + +# --hints-- + +`factorial(0)` should return `1`. + +```js +assert.equal(factorial(0), 1); +``` + +`factorial(5)` should return `120`. + +```js +assert.equal(factorial(5), 120); +``` + +`factorial(20)` should return `2432902008176640000`. + +```js +assert.equal(factorial(20), 2432902008176640000); +``` + +# --seed-- + +## --seed-contents-- + +```js +function factorial(n) { + + return n; +} +``` + +# --solutions-- + +```js +function factorial(n) { + return n == 0 ? 1 : n * factorial(n - 1); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/681cb1b0dab50c87ddb2e51a.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/681cb1b0dab50c87ddb2e51a.md new file mode 100644 index 0000000000000000000000000000000000000000..39e38c0410318619c43f58f4c7a544001155ba2e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/681cb1b0dab50c87ddb2e51a.md @@ -0,0 +1,65 @@ +--- +id: 681cb1b0dab50c87ddb2e51a +title: "Challenge 9: Sum of Squares" +challengeType: 28 +dashedName: challenge-9 +--- + +# --description-- + +Given a positive integer up to 1,000, return the sum of all the integers squared from 1 up to the number. + +# --hints-- + +`sumOfSquares(5)` should return `55`. + +```js +assert.equal(sumOfSquares(5), 55); +``` + +`sumOfSquares(10)` should return `385`. + +```js +assert.equal(sumOfSquares(10), 385); +``` + +`sumOfSquares(25)` should return `5525`. + +```js +assert.equal(sumOfSquares(25), 5525); +``` + +`sumOfSquares(500)` should return `41791750`. + +```js +assert.equal(sumOfSquares(500), 41791750); +``` + +`sumOfSquares(1000)` should return `333833500`. + +```js +assert.equal(sumOfSquares(1000), 333833500); +``` + +# --seed-- + +## --seed-contents-- + +```js +function sumOfSquares(n) { + + return n; +} +``` + +# --solutions-- + +```js +function sumOfSquares(n) { + let total = 1; + for(let i = 2; i <= n; i++) { + total += i * i; + } + return total; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/681cb1b0dab50c87ddb2e51b.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/681cb1b0dab50c87ddb2e51b.md new file mode 100644 index 0000000000000000000000000000000000000000..a292c759519a9330dc73df65e8d70b0b638e9416 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/681cb1b0dab50c87ddb2e51b.md @@ -0,0 +1,70 @@ +--- +id: 681cb1b0dab50c87ddb2e51b +title: "Challenge 10: 3 Strikes" +challengeType: 28 +dashedName: challenge-10 +--- + +# --description-- + +Given an integer between 1 and 10,000, return a count of how many numbers from 1 up to that integer whose square contains at least one digit 3. + +# --hints-- + +`squaresWithThree(1)` should return `0`. + +```js +assert.equal(squaresWithThree(1), 0); +``` + +`squaresWithThree(10)` should return `1`. + +```js +assert.equal(squaresWithThree(10), 1); +``` + +`squaresWithThree(100)` should return `19`. + +```js +assert.equal(squaresWithThree(100), 19); +``` + +`squaresWithThree(1000)` should return `326`. + +```js +assert.equal(squaresWithThree(1000), 326); +``` + +`squaresWithThree(10000)` should return `4531`. + +```js +assert.equal(squaresWithThree(10000), 4531); +``` + +# --seed-- + +## --seed-contents-- + +```js +function squaresWithThree(n) { + + return n; +} +``` + +# --solutions-- + +```js +function squaresWithThree(n) { + let count = 0; + + for (let i = 1; i <= n; i++) { + const square = i * i; + if (square.toString().includes('3')) { + count++; + } + } + + return count; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68216eb60f957572e7c340c4.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68216eb60f957572e7c340c4.md new file mode 100644 index 0000000000000000000000000000000000000000..2eab8726d1bb71237438cddce48c49e1da5673fa --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68216eb60f957572e7c340c4.md @@ -0,0 +1,67 @@ +--- +id: 68216eb60f957572e7c340c4 +title: "Challenge 11: Mile Pace" +challengeType: 28 +dashedName: challenge-11 +--- + +# --description-- + +Given a number of miles ran, and a time in `"MM:SS"` (minutes:seconds) it took to run those miles, return a string for the average time it took to run each mile in the format `"MM:SS"`. + +- Add leading zeros when needed. + +# --hints-- + +`milePace(3, "24:00")` should return `"08:00"`. + +```js +assert.equal(milePace(3, "24:00"), "08:00"); +``` + +`milePace(1, "06:45")` should return `"06:45"`. + +```js +assert.equal(milePace(1, "06:45"), "06:45"); +``` + +`milePace(2, "07:00")` should return `"03:30"`. + +```js +assert.equal(milePace(2, "07:00"), "03:30"); +``` + +`milePace(26.2, "120:35")` should return `"04:36"`. + +```js +assert.equal(milePace(26.2, "120:35"), "04:36"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function milePace(miles, duration) { + + return miles; +} +``` + +# --solutions-- + +```js +function milePace(miles, duration) { + const [minutes, seconds] = duration.split(':').map(Number); + const totalSeconds = minutes * 60 + seconds; + const avgSecondsPerMile = totalSeconds / miles; + + const avgMinutes = Math.floor(avgSecondsPerMile / 60); + const avgSeconds = Math.round(avgSecondsPerMile % 60); + + const paddedMinutes = avgMinutes.toString().padStart(2, '0'); + const paddedSeconds = avgSeconds.toString().padStart(2, '0'); + + return `${paddedMinutes}:${paddedSeconds}`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68216ef80f957572e7c340c5.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68216ef80f957572e7c340c5.md new file mode 100644 index 0000000000000000000000000000000000000000..5dc7a7c4353bcdb36f09dcf8d08f4ab827a56030 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68216ef80f957572e7c340c5.md @@ -0,0 +1,69 @@ +--- +id: 68216ef80f957572e7c340c5 +title: "Challenge 12: Message Decoder" +challengeType: 28 +dashedName: challenge-12 +--- + +# --description-- + +Given a secret message string, and an integer representing the number of letters that were used to shift the message to encode it, return the decoded string. + +- A positive number means the message was shifted forward in the alphabet. +- A negative number means the message was shifted backward in the alphabet. +- Case matters, decoded characters should retain the case of their encoded counterparts. +- Non-alphabetical characters should not get decoded. + +# --hints-- + +`decode("Xlmw mw e wigvix qiwweki.", 4)` should return `"This is a secret message."` + +```js +assert.equal(decode("Xlmw mw e wigvix qiwweki.", 4), "This is a secret message."); +``` + +`decode("Byffi Qilfx!", 20)` should return `"Hello World!"` + +```js +assert.equal(decode("Byffi Qilfx!", 20), "Hello World!"); +``` + +`decode("Zqd xnt njzx?", -1)` should return `"Are you okay?"` + +```js +assert.equal(decode("Zqd xnt njzx?", -1), "Are you okay?"); +``` + +`decode("oannLxmnLjvy", 9)` should return `"freeCodeCamp"` + +```js +assert.equal(decode("oannLxmnLjvy", 9), "freeCodeCamp"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function decode(message, shift) { + + return message; +} +``` + +# --solutions-- + +```js +function decode(message, shift) { + return message.split('').map(char => { + if (/[a-zA-Z]/.test(char)) { + const base = char === char.toLowerCase() ? 'a'.charCodeAt(0) : 'A'.charCodeAt(0); + const charCode = char.charCodeAt(0); + const offset = (charCode - base - shift + 26) % 26; + return String.fromCharCode(base + offset); + } else { + return char; + } + }).join(''); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebc9237de8297eaee78f.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebc9237de8297eaee78f.md new file mode 100644 index 0000000000000000000000000000000000000000..f4ac398d1e73052332e368e7123702d097a25cad --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebc9237de8297eaee78f.md @@ -0,0 +1,97 @@ +--- +id: 6821ebc9237de8297eaee78f +title: "Challenge 13: Unnatural Prime" +challengeType: 28 +dashedName: challenge-13 +--- + +# --description-- + +Given an integer, determine if that number is a prime number or a negative prime number. + +- A prime number is a positive integer greater than 1 that is only divisible by 1 and itself. +- A negative prime number is the negative version of a positive prime number. +- `1` and `0` are not considered prime numbers. + +# --hints-- + +`isUnnaturalPrime(1)` should return `false`. + +```js +assert.isFalse(isUnnaturalPrime(1)); +``` + +`isUnnaturalPrime(-1)` should return `false`. + +```js +assert.isFalse(isUnnaturalPrime(-1)); +``` + +`isUnnaturalPrime(19)` should return `true`. + +```js +assert.isTrue(isUnnaturalPrime(19)); +``` + +`isUnnaturalPrime(-23)` should return `true`. + +```js +assert.isTrue(isUnnaturalPrime(-23)); +``` + +`isUnnaturalPrime(0)` should return `false`. + +```js +assert.isFalse(isUnnaturalPrime(0)); +``` + +`isUnnaturalPrime(97)` should return `true`. + +```js +assert.isTrue(isUnnaturalPrime(97)); +``` + +`isUnnaturalPrime(-61)` should return `true`. + +```js +assert.isTrue(isUnnaturalPrime(-61)); +``` + +`isUnnaturalPrime(99)` should return `false`. + +```js +assert.isFalse(isUnnaturalPrime(99)); +``` + +`isUnnaturalPrime(-44)` should return `false`. + +```js +assert.isFalse(isUnnaturalPrime(-44)); +``` + +# --seed-- + +## --seed-contents-- + +```js +function isUnnaturalPrime(n) { + + return n; +} +``` + +# --solutions-- + +```js +function isUnnaturalPrime(n) { + const abs = Math.abs(n); + + if (abs <= 1) return false; + + for (let i = 2; i <= Math.sqrt(abs); i++) { + if (abs % i === 0) return false; + } + + return true; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebce237de8297eaee790.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebce237de8297eaee790.md new file mode 100644 index 0000000000000000000000000000000000000000..f8c92bce37d269c7f1f1366b9c3609f53a9e2883 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebce237de8297eaee790.md @@ -0,0 +1,117 @@ +--- +id: 6821ebce237de8297eaee790 +title: "Challenge 14: Character Battle" +challengeType: 28 +dashedName: challenge-14 +--- + +# --description-- + +Given two strings representing your army and an opposing army, each character from your army battles the character at the same position from the opposing army using the following rules: + +- Characters `a-z` have a strength of `1-26`, respectively. +- Characters `A-Z` have a strength of `27-52`, respectively. +- Digits `0-9` have a strength of their face value. +- All other characters have a value of zero. +- Each character can only fight one battle. + +For each battle, the stronger character wins. The army with more victories, wins the war. Return the following values: + +- `"Opponent retreated"` if your army has more characters than the opposing army. +- `"We retreated"` if the opposing army has more characters than yours. +- `"We won"` if your army won more battles. +- `"We lost"` if the opposing army won more battles. +- `"It was a tie"` if both armies won the same number of battles. + +# --hints-- + +`battle("Hello", "World")` should return `"We lost"`. + +```js +assert.equal(battle("Hello", "World"), "We lost"); +``` + +`battle("pizza", "salad")` should return `"We won"`. + +```js +assert.equal(battle("pizza", "salad"), "We won"); +``` + +`battle("C@T5", "D0G$")` should return `"We won"`. + +```js +assert.equal(battle("C@T5", "D0G$"), "We won"); +``` + +`battle("kn!ght", "orc")` should return `"Opponent retreated"`. + +```js +assert.equal(battle("kn!ght", "orc"), "Opponent retreated"); +``` + +`battle("PC", "Mac")` should return `"We retreated"`. + +```js +assert.equal(battle("PC", "Mac"), "We retreated"); +``` + +`battle("Wizards", "Dragons")` should return `"It was a tie"`. + +```js +assert.equal(battle("Wizards", "Dragons"), "It was a tie"); +``` + +`battle("Mr. Smith", "Dr. Jones")` should return `"It was a tie"`. + +```js +assert.equal(battle("Mr. Smith", "Dr. Jones"), "It was a tie"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function battle(myArmy, opposingArmy) { + + return myArmy; +} +``` + +# --solutions-- + +```js +function getStrength(soldier) { + const soldiers = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; + let strength = 0; + + if (/\d/.test(soldier)) { + strength = parseInt(soldier); + } else if (soldiers.includes(soldier)) { + strength = soldiers.indexOf(soldier) + 1; + } + + return strength; +} + +function battle(myArmy, opposingArmy) { + if (myArmy.length > opposingArmy.length) return 'Opponent retreated'; + if (opposingArmy.length > myArmy.length) return 'We retreated'; + + let myWins = 0; + let theirWins = 0; + + for (let i = 0; i < myArmy.length; i++) { + const mySoldier = myArmy[i]; + const theirSoldier = opposingArmy[i]; + + const myStrength = getStrength(mySoldier); + const theirStrength = getStrength(theirSoldier); + + if (myStrength > theirStrength) myWins++; + if (theirStrength > myStrength) theirWins++; + } + + return myWins > theirWins ? 'We won' : theirWins > myWins ? 'We lost' : 'It was a tie'; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebd4237de8297eaee791.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebd4237de8297eaee791.md new file mode 100644 index 0000000000000000000000000000000000000000..23061c12b74d1addf2175b727d30cb52ad32ac09 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebd4237de8297eaee791.md @@ -0,0 +1,75 @@ +--- +id: 6821ebd4237de8297eaee791 +title: "Challenge 15: camelCase" +challengeType: 28 +dashedName: challenge-15 +--- + +# --description-- + +Given a string, return its camel case version using the following rules: + +- Words in the string argument are separated by one or more characters from the following set: space (` `), dash (`-`), or underscore (`_`). Treat any sequence of these as a word break. +- The first word should be all lowercase. +- Each subsequent word should start with an uppercase letter, with the rest of it lowercase. +- All spaces and separators should be removed. + +# --hints-- + +`toCamelCase("hello world")` should return `"helloWorld"`. + +```js +assert.equal(toCamelCase("hello world"), "helloWorld"); +``` + +`toCamelCase("HELLO WORLD")` should return `"helloWorld"`. + +```js +assert.equal(toCamelCase("HELLO WORLD"), "helloWorld"); +``` + +`toCamelCase("secret agent-X")` should return `"secretAgentX"`. + +```js +assert.equal(toCamelCase("secret agent-X"), "secretAgentX"); +``` + +`toCamelCase("FREE cODE cAMP")` should return `"freeCodeCamp"`. + +```js +assert.equal(toCamelCase("FREE cODE cAMP"), "freeCodeCamp"); +``` + +`toCamelCase("ye old-_-sea faring_buccaneer_-_with a - peg__leg----and a_parrot_ _named- _squawk")` should return `"yeOldSeaFaringBuccaneerWithAPegLegAndAParrotNamedSquawk"`. + +```js +assert.equal(toCamelCase("ye old-_-sea faring_buccaneer_-_with a - peg__leg----and a_parrot_ _named- _squawk"), "yeOldSeaFaringBuccaneerWithAPegLegAndAParrotNamedSquawk"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function toCamelCase(s) { + + return s; +} +``` + +# --solutions-- + +```js +function toCamelCase(s) { + const words = s.replace(/[_\- ]+/g, ' ').split(' '); + + return words.map((word, i) => { + if (i === 0) { + return word.toLowerCase(); + } else { + const tempWord = word.split(''); + return tempWord.shift().toUpperCase() + tempWord.join('').toLowerCase(); + } + }).join('') +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebda237de8297eaee792.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebda237de8297eaee792.md new file mode 100644 index 0000000000000000000000000000000000000000..9fe99d2cd8838dd6e090a23e88f9135b1312db92 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebda237de8297eaee792.md @@ -0,0 +1,63 @@ +--- +id: 6821ebda237de8297eaee792 +title: "Challenge 16: Reverse Parenthesis" +challengeType: 28 +dashedName: challenge-16 +--- + +# --description-- + +Given a string that contains properly nested parentheses, return the decoded version of the string using the following rules: + +- All characters inside each pair of parentheses should be reversed. +- Parentheses should be removed from the final result. +- If parentheses are nested, the innermost pair should be reversed first, and then its result should be included in the reversal of the outer pair. +- Assume all parentheses are evenly balanced and correctly nested. + +# --hints-- + +`decode("(f(b(dc)e)a)")` should return `"abcdef"`. + +```js +assert.equal(decode("(f(b(dc)e)a)"), "abcdef"); +``` + +`decode("((is?)(a(t d)h)e(n y( uo)r)aC)")` should return `"Can you read this?"`. + +```js +assert.equal(decode("((is?)(a(t d)h)e(n y( uo)r)aC)"), "Can you read this?"); +``` + +`decode("f(Ce(re))o((e(aC)m)d)p")` should return `"freeCodeCamp"`. + +```js +assert.equal(decode("f(Ce(re))o((e(aC)m)d)p"), "freeCodeCamp"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function decode(s) { + + return s; +} +``` + +# --solutions-- + +```js +function decode(s) { + while (s.includes(')')) { + const closeIndex = s.indexOf(')'); + const openIndex = s.lastIndexOf('(', closeIndex); + const before = s.slice(0, openIndex); + const group = s.slice(openIndex + 1, closeIndex).split('').reverse().join(''); + const after = s.slice(closeIndex + 1); + s = before + group + after; + } + + return s; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebdf237de8297eaee793.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebdf237de8297eaee793.md new file mode 100644 index 0000000000000000000000000000000000000000..7f90e08d2e658be7f614f5e4be5383468587b521 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebdf237de8297eaee793.md @@ -0,0 +1,87 @@ +--- +id: 6821ebdf237de8297eaee793 +title: "Challenge 17: Unorder of Operations" +challengeType: 28 +dashedName: challenge-17 +--- + +# --description-- + +Given an array of integers and an array of string operators, apply the operations to the numbers sequentially from left-to-right. Repeat the operations as needed until all numbers are used. Return the final result. + +For example, given `[1, 2, 3, 4, 5]` and `['+', '*']`, return the result of evaluating `1 + 2 * 3 + 4 * 5` from left-to-right ignoring standard order of operations. + +- Valid operators are `+`, `-`, `*`, `/`, and `%`. + +# --hints-- + +`evaluate([5, 6, 7, 8, 9], ['+', '-'])` should return `3` + +```js +assert.equal(evaluate([5, 6, 7, 8, 9], ['+', '-']), 3); +``` + +`evaluate([17, 61, 40, 24, 38, 14], ['+', '%'])` should return `38` + +```js +assert.equal(evaluate([17, 61, 40, 24, 38, 14], ['+', '%']), 38); +``` + +`evaluate([20, 2, 4, 24, 12, 3], ['*', '/'])` should return `60` + +```js +assert.equal(evaluate([20, 2, 4, 24, 12, 3], ['*', '/']), 60); +``` + +`evaluate([11, 4, 10, 17, 2], ['*', '*', '%'])` should return `30` + +```js +assert.equal(evaluate([11, 4, 10, 17, 2], ['*', '*', '%']), 30); +``` + +`evaluate([33, 11, 29, 13], ['/', '-'])` should return `-2` + +```js +assert.equal(evaluate([33, 11, 29, 13], ['/', '-']), -2); +``` + +# --seed-- + +## --seed-contents-- + +```js +function evaluate(numbers, operators) { + + return numbers; +} +``` + +# --solutions-- + +```js +function doMath(a, b, operator) { + switch (operator) { + case "+": + return a + b; + case "-": + return a - b; + case "*": + return a * b; + case "/": + return a / b; + default: + return a % b; + } +} + +function evaluate(numbers, operators) { + let total = numbers[0]; + + for (let i = 1; i < numbers.length; i++) { + const operator = operators[(i - 1) % operators.length]; + total = doMath(total, numbers[i], operator); + } + + return total; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebe4237de8297eaee794.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebe4237de8297eaee794.md new file mode 100644 index 0000000000000000000000000000000000000000..3c7d9e3ab555dc288999cc07842cecb41ef7ed25 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebe4237de8297eaee794.md @@ -0,0 +1,74 @@ +--- +id: 6821ebe4237de8297eaee794 +title: "Challenge 18: Second Best" +challengeType: 28 +dashedName: challenge-18 +--- + +# --description-- + +Given an array of integers representing the price of different laptops, and an integer representing your budget, return: + +1. The second-most expensive laptop in the list if it is within your budget, or +2. The most expensive laptop you can afford otherwise, or +3. `0` if no laptops are within your budget. + +- Duplicate prices should be ignored. + +# --hints-- + +`getLaptopCost([1500, 2000, 1800, 1400], 1900)` should return `1800` + +```js +assert.equal(getLaptopCost([1500, 2000, 1800, 1400], 1900), 1800); +``` + +`getLaptopCost([1500, 2000, 2000, 1800, 1400], 1900)` should return `1800` + +```js +assert.equal(getLaptopCost([1500, 2000, 2000, 1800, 1400], 1900), 1800); +``` + +`getLaptopCost([2099, 1599, 1899, 1499], 2200)` should return `1899` + +```js +assert.equal(getLaptopCost([2099, 1599, 1899, 1499], 2200), 1899); +``` + +`getLaptopCost([2099, 1599, 1899, 1499], 1000)` should return `0` + +```js +assert.equal(getLaptopCost([2099, 1599, 1899, 1499], 1000), 0); +``` + +`getLaptopCost([1200, 1500, 1600, 1800, 1400, 2000], 1450)` should return `1400` + +```js +assert.equal(getLaptopCost([1200, 1500, 1600, 1800, 1400, 2000], 1450), 1400); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getLaptopCost(laptops, budget) { + + return laptops; +} +``` + +# --solutions-- + +```js +function getLaptopCost(laptops, budget) { + laptops = [...new Set(laptops)].sort((a, b) => b - a); + + if (budget >= laptops[1]) return laptops[1]; + if (budget < laptops[laptops.length - 1]) return 0; + + for (let i = 2; i < laptops.length; i++) { + if (budget >= laptops[i]) return laptops[i]; + } +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebea237de8297eaee795.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebea237de8297eaee795.md new file mode 100644 index 0000000000000000000000000000000000000000..ad18df7cef3042531546f23a9cf7cc8d129c092a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebea237de8297eaee795.md @@ -0,0 +1,83 @@ +--- +id: 6821ebea237de8297eaee795 +title: "Challenge 19: Candlelight" +challengeType: 28 +dashedName: challenge-19 +--- + +# --description-- + +Given an integer representing the number of candles you start with, and an integer representing how many burned candles it takes to create a new one, return the number of candles you will have used after creating and burning as many as you can. + +For example, if given 7 candles and it takes 2 burned candles to make a new one: + +1. Burn 7 candles to get 7 leftovers, +2. Recycle 6 leftovers into 3 new candles (1 leftover remains), +3. Burn 3 candles to get 3 more leftovers (4 total), +4. Recycle 4 leftovers into 2 new candles, +5. Burn 2 candles to get 2 leftovers, +6. Recycle 2 leftovers into 1 new candle, +7. Burn 1 candle. + +You will have burned 13 total candles in the example. + +# --hints-- + +`burnCandles(7, 2)` should return `13` + +```js +assert.equal(burnCandles(7, 2), 13); +``` + +`burnCandles(10, 5)` should return `12` + +```js +assert.equal(burnCandles(10, 5), 12); +``` + +`burnCandles(20, 3)` should return `29` + +```js +assert.equal(burnCandles(20, 3), 29); +``` + +`burnCandles(17, 4)` should return `22` + +```js +assert.equal(burnCandles(17, 4), 22); +``` + +`burnCandles(2345, 3)` should return `3517` + +```js +assert.equal(burnCandles(2345, 3), 3517); +``` + +# --seed-- + +## --seed-contents-- + +```js +function burnCandles(candles, leftoversNeeded) { + + return candles; +} +``` + +# --solutions-- + +```js +function burnCandles(candles, leftoversNeeded) { + let totalBurned = 0; + let unusedLeftovers = 0; + + while (candles > 0) { + totalBurned += candles; + const leftovers = candles + unusedLeftovers; + candles = Math.floor(leftovers / leftoversNeeded); + unusedLeftovers = leftovers % leftoversNeeded; + } + + return totalBurned; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebee237de8297eaee796.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebee237de8297eaee796.md new file mode 100644 index 0000000000000000000000000000000000000000..d26733f1d1823aecfaf7e9e2478b824492a12046 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebee237de8297eaee796.md @@ -0,0 +1,61 @@ +--- +id: 6821ebee237de8297eaee796 +title: "Challenge 20: Array Duplicates" +challengeType: 28 +dashedName: challenge-20 +--- + +# --description-- + +Given an array of integers, return an array of integers that appear more than once in the initial array, sorted in ascending order. If no values appear more than once, return an empty array. + +- Only include one instance of each value in the returned array. + +# --hints-- + +`findDuplicates([1, 2, 3, 4, 5])` should return `[]`. + +```js +assert.deepEqual(findDuplicates([1, 2, 3, 4, 5]), []); +``` + +`findDuplicates([1, 2, 3, 4, 1, 2])` should return `[1, 2]`. + +```js +assert.deepEqual(findDuplicates([1, 2, 3, 4, 1, 2]), [1, 2]); +``` + +`findDuplicates([2, 34, 0, 1, -6, 23, 5, 3, 2, 5, 67, -6, 23, 2, 43, 2, 12, 0, 2, 4, 4])` should return `[-6, 0, 2, 4, 5, 23]`. + +```js +assert.deepEqual(findDuplicates([2, 34, 0, 1, -6, 23, 5, 3, 2, 5, 67, -6, 23, 2, 43, 2, 12, 0, 2, 4, 4]), [-6, 0, 2, 4, 5, 23]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function findDuplicates(arr) { + + return arr; +} +``` + +# --solutions-- + +```js +function findDuplicates(arr) { + const duplicates = []; + + for (let i = 0; i < arr.length - 1; i++) { + for (let j = i + 1; j < arr.length; j++) { + if (arr[i] === arr[j] && !duplicates.includes(arr[i])) { + duplicates.push(arr[i]); + } + } + } + + return duplicates.sort((a, b) => a - b); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebf3237de8297eaee797.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebf3237de8297eaee797.md new file mode 100644 index 0000000000000000000000000000000000000000..670086f48868b0688d2335df508ccfb007def6b1 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebf3237de8297eaee797.md @@ -0,0 +1,186 @@ +--- +id: 6821ebf3237de8297eaee797 +title: "Challenge 21: Hex Generator" +challengeType: 28 +dashedName: challenge-21 +--- + +# --description-- + +Given a named CSS color string, generate a random hexadecimal (hex) color code that is dominant in the given color. + +- The function should handle `"red"`, `"green"`, or `"blue"` as an input argument. +- If the input is not one of those, the function should return `"Invalid color"`. +- The function should return a random six-character hex color code where the input color value is greater than any of the others. +- Example of valid outputs for a given input: + +| Input | Output | +|---------|----------| +| `"red"` | `"FF0000"` | +| `"green"` | `"00FF00"` | +| `"blue"` | `"0000FF"` | + +# --hints-- + +`generateHex("yellow")` should return `"Invalid color"`. + +```js +assert.equal(generateHex("yellow"), "Invalid color"); +``` + +`generateHex("red")` should return a six-character string. + +```js +assert.lengthOf(generateHex("red"), 6); +``` + +`generateHex("red")` should return a valid six-character hex color code. + +```js +const hex = generateHex("red").toUpperCase(); +const isValidHex = /^[0-9A-F]{6}$/.test(hex); +assert.isTrue(isValidHex); +``` + +`generateHex("red")` should return a valid hex color with a higher red value than other colors. + +```js +const hex = generateHex("red").toUpperCase(); +const isValidHex = /^[0-9A-F]{6}$/.test(hex); +assert.isTrue(isValidHex); + +const r = parseInt(hex.slice(0, 2), 16); +const g = parseInt(hex.slice(2, 4), 16); +const b = parseInt(hex.slice(4, 6), 16); + +assert.isAbove(r, g); +assert.isAbove(r, b); +``` + +Calling `generateHex("red")` twice should return two different hex color values where red is dominant. + +```js +const hex1 = generateHex("red").toUpperCase(); +const isValidHex1 = /^[0-9A-F]{6}$/.test(hex1) +assert.isTrue(isValidHex1); + +const r1 = parseInt(hex1.slice(0, 2), 16); +const g1 = parseInt(hex1.slice(2, 4), 16); +const b1 = parseInt(hex1.slice(4, 6), 16); + +assert.isAbove(r1, g1); +assert.isAbove(r1, b1); + +const hex2 = generateHex("red").toUpperCase(); +const isValidHex2 = /^[0-9A-F]{6}$/.test(hex2); +assert.isTrue(isValidHex2); + +const r2 = parseInt(hex2.slice(0, 2), 16); +const g2 = parseInt(hex2.slice(2, 4), 16); +const b2 = parseInt(hex2.slice(4, 6), 16); + +assert.isAbove(r2, g2); +assert.isAbove(r2, b2); +assert.notEqual(hex1, hex2); +``` + +Calling `generateHex("green")` twice should return two different hex color values where green is dominant. + +```js +const hex1 = generateHex("green").toUpperCase(); +const isValidHex1 = /^[0-9A-F]{6}$/.test(hex1) +assert.isTrue(isValidHex1); + +const r1 = parseInt(hex1.slice(0, 2), 16); +const g1 = parseInt(hex1.slice(2, 4), 16); +const b1 = parseInt(hex1.slice(4, 6), 16); + +assert.isAbove(g1, r1); +assert.isAbove(g1, b1); + +const hex2 = generateHex("green").toUpperCase(); +const isValidHex2 = /^[0-9A-F]{6}$/.test(hex2); +assert.isTrue(isValidHex2); + +const r2 = parseInt(hex2.slice(0, 2), 16); +const g2 = parseInt(hex2.slice(2, 4), 16); +const b2 = parseInt(hex2.slice(4, 6), 16); + +assert.isAbove(g2, r2); +assert.isAbove(g2, b2); +assert.notEqual(hex1, hex2); +``` + +Calling `generateHex("blue")` twice should return two different hex color values where blue is dominant. + +```js +const hex1 = generateHex("blue").toUpperCase(); +const isValidHex1 = /^[0-9A-F]{6}$/.test(hex1) +assert.isTrue(isValidHex1); + +const r1 = parseInt(hex1.slice(0, 2), 16); +const g1 = parseInt(hex1.slice(2, 4), 16); +const b1 = parseInt(hex1.slice(4, 6), 16); + +assert.isAbove(b1, r1); +assert.isAbove(b1, g1); + +const hex2 = generateHex("blue").toUpperCase(); +const isValidHex2 = /^[0-9A-F]{6}$/.test(hex2); +assert.isTrue(isValidHex2); + +const r2 = parseInt(hex2.slice(0, 2), 16); +const g2 = parseInt(hex2.slice(2, 4), 16); +const b2 = parseInt(hex2.slice(4, 6), 16); + +assert.isAbove(b2, r2); +assert.isAbove(b2, g2); +assert.notEqual(hex1, hex2); +``` + +# --seed-- + +## --seed-contents-- + +```js +function generateHex(color) { + + return color; +} +``` + +# --solutions-- + +```js +function generateHex(color) { + const toHex = n => n.toString(16).padStart(2, "0").toUpperCase(); + + const dominant = Math.floor(Math.random() * 86) + 170; + const weak1 = Math.floor(Math.random() * 170); + const weak2 = Math.floor(Math.random() * 170); + + let r, g, b; + + switch (color) { + case "red": + r = dominant; + g = weak1; + b = weak2; + break; + case "green": + r = weak1; + g = dominant; + b = weak2; + break; + case "blue": + r = weak1; + g = weak2; + b = dominant; + break; + default: + return "Invalid color"; + } + + return `${toHex(r)}${toHex(g)}${toHex(b)}`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebf8237de8297eaee798.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebf8237de8297eaee798.md new file mode 100644 index 0000000000000000000000000000000000000000..991c2a90986f6da9046ca49fa76afc62dccb69a2 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebf8237de8297eaee798.md @@ -0,0 +1,84 @@ +--- +id: 6821ebf8237de8297eaee798 +title: "Challenge 22: Tribonacci Sequence" +challengeType: 28 +dashedName: challenge-22 +--- + +# --description-- + +The Tribonacci sequence is a series of numbers where each number is the sum of the three preceding ones. When starting with `0`, `0` and `1`, the first 10 numbers in the sequence are `0`, `0`, `1`, `1`, `2`, `4`, `7`, `13`, `24`, `44`. + +Given an array containing the first three numbers of a Tribonacci sequence, and an integer representing the length of the sequence, return an array containing the sequence of the given length. + +- Your function should handle sequences of any length greater than or equal to zero. +- If the length is zero, return an empty array. +- Note that the starting numbers are part of the sequence. + +# --hints-- + +`tribonacciSequence([0, 0, 1], 20)` should return `[0, 0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149, 274, 504, 927, 1705, 3136, 5768, 10609, 19513]`. + +```js +assert.deepEqual(tribonacciSequence([0, 0, 1], 20), [0, 0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149, 274, 504, 927, 1705, 3136, 5768, 10609, 19513]); +``` + +`tribonacciSequence([21, 32, 43], 1)` should return `[21]`. + + +```js +assert.deepEqual(tribonacciSequence([21, 32, 43], 1), [21]); +``` + +`tribonacciSequence([0, 0, 1], 0)` should return `[]`. + +```js +assert.deepEqual(tribonacciSequence([0, 0, 1], 0), []); +``` + +`tribonacciSequence([10, 20, 30], 2)` should return `[10, 20]`. + +```js +assert.deepEqual(tribonacciSequence([10, 20, 30], 2), [10, 20]); +``` + +`tribonacciSequence([10, 20, 30], 3)` should return `[10, 20, 30]`. + +```js +assert.deepEqual(tribonacciSequence([10, 20, 30], 3), [10, 20, 30]); +``` + +`tribonacciSequence([123, 456, 789], 8)` should return `[123, 456, 789, 1368, 2613, 4770, 8751, 16134]`. + +```js +assert.deepEqual(tribonacciSequence([123, 456, 789], 8), [123, 456, 789, 1368, 2613, 4770, 8751, 16134]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function tribonacciSequence(startSequence, length) { + + return length; +} +``` + +# --solutions-- + +```js +function tribonacciSequence(startSequence, length) { + if (length === 0) return []; + if (length === 1) return [startSequence[0]]; + if (length === 2) return [startSequence[0], startSequence[1]]; + if (length === 3) return [...startSequence]; + + const sequence = [...startSequence]; + while (sequence.length < length) { + const nextValue = sequence[sequence.length - 1] + sequence[sequence.length - 2] + + sequence[sequence.length - 3]; + sequence.push(nextValue); + } + return sequence; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebfd237de8297eaee799.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebfd237de8297eaee799.md new file mode 100644 index 0000000000000000000000000000000000000000..141d3f81c4dc5434a4132843ecec4764032e054d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebfd237de8297eaee799.md @@ -0,0 +1,72 @@ +--- +id: 6821ebfd237de8297eaee799 +title: "Challenge 23: RGB to Hex" +challengeType: 28 +dashedName: challenge-23 +--- + +# --description-- + +Given a CSS `rgb(r, g, b)` color string, return its hexadecimal equivalent. + +Here are some example outputs for a given input: + +| Input | Output | +|---------|----------| +| `"rgb(255, 255, 255)"`| `"#ffffff"` | +| `"rgb(1, 2, 3)"` | `"#010203"` | + +- Make any letters lowercase. +- Return a `#` followed by six characters. Don't use any shorthand values. + +# --hints-- + +`rgbToHex("rgb(255, 255, 255)")` should return `"#ffffff"`. + +```js +assert.equal(rgbToHex("rgb(255, 255, 255)"), "#ffffff"); +``` + +`rgbToHex("rgb(1, 11, 111)")` should return `"#010b6f"`. + +```js +assert.equal(rgbToHex("rgb(1, 11, 111)"), "#010b6f"); +``` + +`rgbToHex("rgb(173, 216, 230)")` should return `"#add8e6"`. + +```js +assert.equal(rgbToHex("rgb(173, 216, 230)"), "#add8e6"); +``` + +`rgbToHex("rgb(79, 123, 201)")` should return `"#4f7bc9"`. + +```js +assert.equal(rgbToHex("rgb(79, 123, 201)"), "#4f7bc9"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function rgbToHex(rgb) { + + return rgb; +} +``` + +# --solutions-- + +```js +function rgbToHex(rgb) { + const match = rgb.match(/\d+/g); + const [r, g, b] = match.map(num => + Math.max(0, Math.min(255, parseInt(num))) + .toString(16) + .padStart(2, '0') + ); + + return `#${r}${g}${b}`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ec02237de8297eaee79a.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ec02237de8297eaee79a.md new file mode 100644 index 0000000000000000000000000000000000000000..925eac9c65cecc0d928e36e89312f87545280e27 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ec02237de8297eaee79a.md @@ -0,0 +1,93 @@ +--- +id: 6821ec02237de8297eaee79a +title: "Challenge 24: Pangram" +challengeType: 28 +dashedName: challenge-24 +--- + +# --description-- + +Given a word or sentence and a string of lowercase letters, determine if the word or sentence uses all the letters from the given set at least once and no other letters. + +- Ignore non-alphabetical characters in the word or sentence. +- Ignore letter casing in the word or sentence. + +# --hints-- + +`isPangram("hello", "helo")` should return `true` + +```js +assert.isTrue(isPangram("hello", "helo")); +``` + +`isPangram("hello", "hel")` should return `false` + +```js +assert.isFalse(isPangram("hello", "hel")); +``` + +`isPangram("hello", "helow")` should return `false` + +```js +assert.isFalse(isPangram("hello", "helow")); +``` + +`isPangram("hello world", "helowrd")` should return `true` + +```js +assert.isTrue(isPangram("hello world", "helowrd")); +``` + +`isPangram("Hello World!", "helowrd")` should return `true` + +```js +assert.isTrue(isPangram("Hello World!", "helowrd")); +``` + +`isPangram("Hello World!", "heliowrd")` should return `false` + +```js +assert.isFalse(isPangram("Hello World!", "heliowrd")); +``` + +`isPangram("freeCodeCamp", "frcdmp")` should return `false` + +```js +assert.isFalse(isPangram("freeCodeCamp", "frcdmp")); +``` + +`isPangram("The quick brown fox jumps over the lazy dog.", "abcdefghijklmnopqrstuvwxyz")` should return `true` + +```js +assert.isTrue(isPangram("The quick brown fox jumps over the lazy dog.", "abcdefghijklmnopqrstuvwxyz")); +``` + +# --seed-- + +## --seed-contents-- + +```js +function isPangram(sentence, letters) { + + return sentence; +} +``` + +# --solutions-- + +```js +function isPangram(sentence, letters) { + const usedLetters = []; + for (let i = 0; i < sentence.length; i++) { + const letter = sentence[i].toLowerCase(); + if (!usedLetters.includes(letter) && /[a-z]/.test(letter)) { + usedLetters.push(letter); + } + } + + const sortedLetters = letters.split('').sort().join(''); + const sortedUsedLetters = usedLetters.sort().join(''); + + return sortedLetters === sortedUsedLetters; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68adce01c0e1144d0a902956.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68adce01c0e1144d0a902956.md new file mode 100644 index 0000000000000000000000000000000000000000..df852f1c7cf62dcafc304335bd86e8a8e08e6318 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68adce01c0e1144d0a902956.md @@ -0,0 +1,72 @@ +--- +id: 68adce01c0e1144d0a902956 +title: "Challenge 25: Vowel Repeater" +challengeType: 28 +dashedName: challenge-25 +--- + +# --description-- + +Given a string, return a new version of the string where each vowel is duplicated one more time than the previous vowel you encountered. For instance, the first vowel in the sentence should remain unchanged. The second vowel should appear twice in a row. The third vowel should appear three times in a row, and so on. + +- The letters `a`, `e`, `i`, `o`, and `u`, in either uppercase or lowercase, are considered vowels. +- The original vowel should keeps its case. +- Repeated vowels should be lowercase. +- All non-vowel characters should keep their original case. + +# --hints-- + +`repeatVowels("hello world")` should return `"helloo wooorld"`. + +```js +assert.equal(repeatVowels("hello world"), "helloo wooorld"); +``` + +`repeatVowels("freeCodeCamp")` should return `"freeeCooodeeeeCaaaaamp"`. + +```js +assert.equal(repeatVowels("freeCodeCamp"), "freeeCooodeeeeCaaaaamp"); +``` + +`repeatVowels("AEIOU")` should return `"AEeIiiOoooUuuuu"`. + +```js +assert.equal(repeatVowels("AEIOU"), "AEeIiiOoooUuuuu"); +``` + +`repeatVowels("I like eating ice cream in Iceland")` should return `"I liikeee eeeeaaaaatiiiiiing iiiiiiiceeeeeeee creeeeeeeeeaaaaaaaaaam iiiiiiiiiiin Iiiiiiiiiiiiceeeeeeeeeeeeelaaaaaaaaaaaaaand"`. + +```js +assert.equal(repeatVowels("I like eating ice cream in Iceland"), "I liikeee eeeeaaaaatiiiiiing iiiiiiiceeeeeeee creeeeeeeeeaaaaaaaaaam iiiiiiiiiiin Iiiiiiiiiiiiceeeeeeeeeeeeelaaaaaaaaaaaaaand"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function repeatVowels(str) { + + return str; +} +``` + +# --solutions-- + +```js +function repeatVowels(str) { + const vowels = "aeiouAEIOU"; + let count = 0; + let result = ""; + + for (let char of str) { + result += char; + if (vowels.includes(char)) { + result += char.repeat(count).toLowerCase(); + count++; + } + } + + return result; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68adce01c0e1144d0a902958.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68adce01c0e1144d0a902958.md new file mode 100644 index 0000000000000000000000000000000000000000..5f9ec517ed1363dfd629b023728120ab429d3058 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68adce01c0e1144d0a902958.md @@ -0,0 +1,90 @@ +--- +id: 68adce01c0e1144d0a902958 +title: "Challenge 26: IPv4 Validator" +challengeType: 28 +dashedName: challenge-26 +--- + +# --description-- + +Given a string, determine if it is a valid IPv4 Address. A valid IPv4 address consists of four integer numbers separated by dots (`.`). Each number must satisfy the following conditions: + +- It is between 0 and 255 inclusive. +- It does not have leading zeros (e.g. 0 is allowed, 01 is not). +- Only numeric characters are allowed. + +# --hints-- + +`isValidIPv4("192.168.1.1")` should return `true`. + +```js +assert.isTrue(isValidIPv4("192.168.1.1")); +``` + +`isValidIPv4("0.0.0.0")` should return `true`. + +```js +assert.isTrue(isValidIPv4("0.0.0.0")); +``` + +`isValidIPv4("255.01.50.111")` should return `false`. + +```js +assert.isFalse(isValidIPv4("255.01.50.111")); +``` + +`isValidIPv4("255.00.50.111")` should return `false`. + +```js +assert.isFalse(isValidIPv4("255.00.50.111")); +``` + +`isValidIPv4("256.101.50.115")` should return `false`. + +```js +assert.isFalse(isValidIPv4("256.101.50.115")); +``` + +`isValidIPv4("192.168.101.")` should return `false`. + +```js +assert.isFalse(isValidIPv4("192.168.101.")); +``` + +`isValidIPv4("192168145213")` should return `false`. + +```js +assert.isFalse(isValidIPv4("192168145213")); +``` + +# --seed-- + +## --seed-contents-- + +```js +function isValidIPv4(ipv4) { + + return ipv4; +} +``` + +# --solutions-- + +```js +function isValidIPv4(ipv4) { + const parts = ipv4.split("."); + + if (parts.length !== 4) return false; + + for (let part of parts) { + if (!/^\d+$/.test(part)) return false; + + const num = Number(part); + if (num < 0 || num > 255) return false; + + if (part.length > 1 && part.startsWith("0")) return false; + } + + return true; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68adce01c0e1144d0a90295a.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68adce01c0e1144d0a90295a.md new file mode 100644 index 0000000000000000000000000000000000000000..d9672c7a10408cce4ff7c94135a22a3a023a48d9 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68adce01c0e1144d0a90295a.md @@ -0,0 +1,74 @@ +--- +id: 68adce01c0e1144d0a90295a +title: "Challenge 27: Matrix Rotate" +challengeType: 28 +dashedName: challenge-27 +--- + +# --description-- + +Given a matrix (an array of arrays), rotate the matrix 90 degrees clockwise and return it. For instance, given `[[1, 2], [3, 4]]`, which looks like this: + +| 1 | 2 | +|---|---| +| 3 | 4 | + +You should return `[[3, 1], [4, 2]]`, which looks like this: + +| 3 | 1 | +|---|---| +| 4 | 2 | + +# --hints-- + +`rotate([[1]])` should return `[[1]]`. + +```js +assert.deepEqual(rotate([[1]]), [[1]]); +``` + +`rotate([[1, 2], [3, 4]])` should return `[[3, 1], [4, 2]]`. + +```js +assert.deepEqual(rotate([[1, 2], [3, 4]]), [[3, 1], [4, 2]]); +``` + +`rotate([[1, 2, 3], [4, 5, 6], [7, 8, 9]])` should return `[[7, 4, 1], [8, 5, 2], [9, 6, 3]]`. + +```js +assert.deepEqual(rotate([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), [[7, 4, 1], [8, 5, 2], [9, 6, 3]]); +``` + +`rotate([[0, 1, 0], [1, 0, 1], [0, 0, 0]])` should return `[[0, 1, 0], [0, 0, 1], [0, 1, 0]]`. + +```js +assert.deepEqual(rotate([[0, 1, 0], [1, 0, 1], [0, 0, 0]]), [[0, 1, 0], [0, 0, 1], [0, 1, 0]]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function rotate(matrix) { + + return matrix; +} +``` + +# --solutions-- + +```js +function rotate(matrix) { + const n = matrix.length; + const result = Array.from({ length: n }, () => Array(n).fill(0)); + + for (let i = 0; i < n; i++) { + for (let j = 0; j < n; j++) { + result[j][n - 1 - i] = matrix[i][j]; + } + } + + return result; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68adce01c0e1144d0a90295c.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68adce01c0e1144d0a90295c.md new file mode 100644 index 0000000000000000000000000000000000000000..c67d084f82f63767f20b4abba6473b11ae3aa6f3 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68adce01c0e1144d0a90295c.md @@ -0,0 +1,110 @@ +--- +id: 68adce01c0e1144d0a90295c +title: "Challenge 28: Roman Numeral Parser" +challengeType: 28 +dashedName: challenge-28 +--- + +# --description-- + +Given a string representing a Roman numeral, return its integer value. + +Roman numerals consist of the following symbols and values: + +| Symbol | Value | +|--------|-------| +| I | 1 | +| V | 5 | +| X | 10 | +| L | 50 | +| C | 100 | +| D | 500 | +| M | 1000 | + +- Numerals are read left to right. If a smaller numeral appears before a larger one, the value is subtracted. Otherwise, values are added. + +# --hints-- + +`parseRomanNumeral("III")` should return `3`. + +```js +assert.equal(parseRomanNumeral("III"), 3); +``` + +`parseRomanNumeral("IV")` should return `4`. + +```js +assert.equal(parseRomanNumeral("IV"), 4); +``` + +`parseRomanNumeral("XXVI")` should return `26`. + +```js +assert.equal(parseRomanNumeral("XXVI"), 26); +``` + +`parseRomanNumeral("XCIX")` should return `99`. + +```js +assert.equal(parseRomanNumeral("XCIX"), 99); +``` + +`parseRomanNumeral("CDLX")` should return `460`. + +```js +assert.equal(parseRomanNumeral("CDLX"), 460); +``` + +`parseRomanNumeral("DIV")` should return `504`. + +```js +assert.equal(parseRomanNumeral("DIV"), 504); +``` + +`parseRomanNumeral("MMXXV")` should return `2025`. + +```js +assert.equal(parseRomanNumeral("MMXXV"), 2025); +``` + +# --seed-- + +## --seed-contents-- + +```js +function parseRomanNumeral(numeral) { + + return numeral; +} +``` + +# --solutions-- + +```js +function parseRomanNumeral(numeral) { + const romanMap = { + I: 1, + V: 5, + X: 10, + L: 50, + C: 100, + D: 500, + M: 1000 + }; + + let total = 0; + + for (let i = 0; i < numeral.length; i++) { + const current = romanMap[numeral[i]]; + const next = romanMap[numeral[i + 1]]; + + if (next && current < next) { + total -= current; + } else { + total += current; + } + } + + return total; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68adce01c0e1144d0a90295e.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68adce01c0e1144d0a90295e.md new file mode 100644 index 0000000000000000000000000000000000000000..e8fb1bc953cacc7eb65045c7a8c542e128fee98b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68adce01c0e1144d0a90295e.md @@ -0,0 +1,91 @@ +--- +id: 68adce01c0e1144d0a90295e +title: "Challenge 29: Acronym Builder" +challengeType: 28 +dashedName: challenge-29 +--- + +# --description-- + +Given a string containing one or more words, return an acronym of the words using the following constraints: + +- The acronym should consist of the first letter of each word capitalized, unless otherwise noted. +- The acronym should ignore the first letter of these words unless they are the first word of the given string: `a`, `for`, `an`, `and`, `by`, and `of`. +- The acronym letters should be returned in the order they are given. +- The acronym should not contain any spaces. + +# --hints-- + +`buildAcronym("Search Engine Optimization")` should return `"SEO"`. + +```js +assert.equal(buildAcronym("Search Engine Optimization"), "SEO"); +``` + +`buildAcronym("Frequently Asked Questions")` should return `"FAQ"`. + +```js +assert.equal(buildAcronym("Frequently Asked Questions"), "FAQ"); +``` + +`buildAcronym("National Aeronautics and Space Administration")` should return `"NASA"`. + +```js +assert.equal(buildAcronym("National Aeronautics and Space Administration"), "NASA"); +``` + +`buildAcronym("Federal Bureau of Investigation")` should return `"FBI"`. + +```js +assert.equal(buildAcronym("Federal Bureau of Investigation"), "FBI"); +``` + +`buildAcronym("For your information")` should return `"FYI"`. + +```js +assert.equal(buildAcronym("Light Amplification by Stimulated Emission of Radiation"), "LASER"); +``` + +`buildAcronym("By the way")` should return `"BTW"`. + +```js +assert.equal(buildAcronym("By the way"), "BTW"); +``` + +`buildAcronym("An unstoppable herd of waddling penguins overtakes the icy mountains and sings happily")` should return `"AUHWPOTIMSH"`. + +```js +assert.equal(buildAcronym("An unstoppable herd of waddling penguins overtakes the icy mountains and sings happily"), "AUHWPOTIMSH"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function buildAcronym(str) { + + return str; +} +``` + +# --solutions-- + +```js +function buildAcronym(str) { + const smallWords = ["a", "for", "an", "and", "by", "of"]; + const words = str.split(" "); + let acronym = ""; + + for (let i = 0; i < words.length; i++) { + const word = words[i]; + const lowerWord = word.toLowerCase(); + + if (i === 0 || !smallWords.includes(lowerWord)) { + acronym += word[0].toUpperCase(); + } + } + + return acronym; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68af0687ef34c76c28ffa547.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68af0687ef34c76c28ffa547.md new file mode 100644 index 0000000000000000000000000000000000000000..a6d7b7851a6ffa99d3a3e835437bafafee7ddd01 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68af0687ef34c76c28ffa547.md @@ -0,0 +1,82 @@ +--- +id: 68af0687ef34c76c28ffa547 +title: "Challenge 30: Unique Characters" +challengeType: 28 +dashedName: challenge-30 +--- + +# --description-- + +Given a string, determine if all the characters in the string are unique. + +- Uppercase and lowercase letters should be considered different characters. + +# --hints-- + +`allUnique("abc")` should return `true`. + +```js +assert.isTrue(allUnique("abc")); +``` + +`allUnique("aA")` should return `true`. + +```js +assert.isTrue(allUnique("aA")); +``` + +`allUnique("QwErTy123!@")` should return `true`. + +```js +assert.isTrue(allUnique("QwErTy123!@")); +``` + +`allUnique("~!@#$%^&*()_+")` should return `true`. + +```js +assert.isTrue(allUnique("~!@#$%^&*()_+")); +``` + +`allUnique("hello")` should return `false`. + +```js +assert.isFalse(allUnique("hello")); +``` + +`allUnique("freeCodeCamp")` should return `false`. + +```js +assert.isFalse(allUnique("freeCodeCamp")); +``` + +`allUnique("!@#*$%^&*()aA")` should return `false`. + +```js +assert.isFalse(allUnique("!@#*$%^&*()aA")); +``` + +# --seed-- + +## --seed-contents-- + +```js +function allUnique(str) { + + return str; +} +``` + +# --solutions-- + +```js +function allUnique(str) { + let seen = ''; + for (let char of str) { + if (seen.includes(char)) { + return false; + } + seen += char; + } + return true; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68af0687ef34c76c28ffa549.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68af0687ef34c76c28ffa549.md new file mode 100644 index 0000000000000000000000000000000000000000..e6c3fed750efb017345bcf575c4fa72b95fc9db6 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68af0687ef34c76c28ffa549.md @@ -0,0 +1,69 @@ +--- +id: 68af0687ef34c76c28ffa549 +title: "Challenge 31: Array Diff" +challengeType: 28 +dashedName: challenge-31 +--- + +# --description-- + +Given two arrays with strings values, return a new array containing all the values that appear in only one of the arrays. + +- The returned array should be sorted in alphabetical order. + +# --hints-- + +`arrayDiff(["apple", "banana"], ["apple", "banana", "cherry"])` should return `["cherry"]`. + +```js +assert.deepEqual(arrayDiff(["apple", "banana"], ["apple", "banana", "cherry"]), ["cherry"]); +``` + +`arrayDiff(["apple", "banana", "cherry"], ["apple", "banana"])` should return `["cherry"]`. + +```js +assert.deepEqual(arrayDiff(["apple", "banana", "cherry"], ["apple", "banana"]), ["cherry"]); +``` + +`arrayDiff(["one", "two", "three", "four", "six"], ["one", "three", "eight"])` should return `["eight", "four", "six", "two"]`. + +```js +assert.deepEqual(arrayDiff(["one", "two", "three", "four", "six"], ["one", "three", "eight"]), ["eight", "four", "six", "two"]); +``` + +`arrayDiff(["two", "four", "five", "eight"], ["one", "two", "three", "four", "seven", "eight"])` should return `["five", "one", "seven", "three"]`. + +```js +assert.deepEqual(arrayDiff(["two", "four", "five", "eight"], ["one", "two", "three", "four", "seven", "eight"]), ["five", "one", "seven", "three"]); +``` + +`arrayDiff(["I", "like", "freeCodeCamp"], ["I", "like", "rocks"])` should return `["freeCodeCamp", "rocks"]`. + +```js +assert.deepEqual(arrayDiff(["I", "like", "freeCodeCamp"], ["I", "like", "rocks"]), ["freeCodeCamp", "rocks"]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function arrayDiff(arr1, arr2) { + + return arr1; +} +``` + +# --solutions-- + +```js +function arrayDiff(arr1, arr2) { + let unique1 = arr1.filter((v, i) => arr1.indexOf(v) === i); + let unique2 = arr2.filter((v, i) => arr2.indexOf(v) === i); + + let only1 = unique1.filter(v => !unique2.includes(v)); + let only2 = unique2.filter(v => !unique1.includes(v)); + + return [...only1, ...only2].sort(); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68af0687ef34c76c28ffa54b.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68af0687ef34c76c28ffa54b.md new file mode 100644 index 0000000000000000000000000000000000000000..51db59e80d12397b5752a03ae3dffa160f643fef --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68af0687ef34c76c28ffa54b.md @@ -0,0 +1,58 @@ +--- +id: 68af0687ef34c76c28ffa54b +title: "Challenge 32: Reverse Sentence" +challengeType: 28 +dashedName: challenge-32 +--- + +# --description-- + +Given a string of words, return a new string with the words in reverse order. For example, the first word should be at the end of the returned string, and the last word should be at the beginning of the returned string. + +- In the given string, words can be separated by one or more spaces. +- The returned string should only have one space between words. + +# --hints-- + +`reverseSentence("world hello")` should return `"hello world"`. + +```js +assert.equal(reverseSentence("world hello"), "hello world"); +``` + +`reverseSentence("push commit git")` should return `"git commit push"`. + +```js +assert.equal(reverseSentence("push commit git"), "git commit push"); +``` + +`reverseSentence("npm install sudo")` should return `"sudo install npm"`. + +```js +assert.equal(reverseSentence("npm install apt sudo"), "sudo apt install npm"); +``` + +`reverseSentence("import default function export")` should return `"export function default import"`. + +```js +assert.equal(reverseSentence("import default function export"), "export function default import"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function reverseSentence(sentence) { + + return sentence; +} +``` + +# --solutions-- + +```js +function reverseSentence(sentence) { + return sentence.split(/\s+/).reverse().join(" "); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68af0687ef34c76c28ffa54d.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68af0687ef34c76c28ffa54d.md new file mode 100644 index 0000000000000000000000000000000000000000..732d1828577715de9730903febb2cc68b268c7aa --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68af0687ef34c76c28ffa54d.md @@ -0,0 +1,89 @@ +--- +id: 68af0687ef34c76c28ffa54d +title: "Challenge 33: Screen Time" +challengeType: 28 +dashedName: challenge-33 +--- + +# --description-- + +Given an input array of seven integers, representing a week's time, where each integer is the amount of hours spent on your phone that day, determine if it is too much screen time based on these constraints: + +- If any single day has 10 hours or more, it's too much. +- If the average of any three days in a row is greater than or equal to 8 hours, it’s too much. +- If the average of the seven days is greater than or equal to 6 hours, it's too much. + +# --hints-- + +`tooMuchScreenTime([1, 2, 3, 4, 5, 6, 7])` should return `false`. + +```js +assert.isFalse(tooMuchScreenTime([1, 2, 3, 4, 5, 6, 7])); +``` + +`tooMuchScreenTime([7, 8, 8, 4, 2, 2, 3])` should return `false`. + +```js +assert.isFalse(tooMuchScreenTime([7, 8, 8, 4, 2, 2, 3])); +``` + +`tooMuchScreenTime([5, 6, 6, 6, 6, 6, 6])` should return `false`. + +```js +assert.isFalse(tooMuchScreenTime([5, 6, 6, 6, 6, 6, 6])); +``` + +`tooMuchScreenTime([1, 2, 3, 11, 1, 3, 4])` should return `true`. + +```js +assert.isTrue(tooMuchScreenTime([1, 2, 3, 11, 1, 3, 4])); +``` + +`tooMuchScreenTime([1, 2, 3, 10, 2, 1, 0])` should return `true`. + +```js +assert.isTrue(tooMuchScreenTime([1, 2, 3, 10, 2, 1, 0])); +``` + +`tooMuchScreenTime([3, 3, 5, 8, 8, 9, 4])` should return `true`. + +```js +assert.isTrue(tooMuchScreenTime([3, 3, 5, 8, 8, 9, 4])); +``` + +`tooMuchScreenTime([3, 9, 4, 8, 5, 7, 6])` should return `true`. + +```js +assert.isTrue(tooMuchScreenTime([3, 9, 4, 8, 5, 7, 6])); +``` + +# --seed-- + +## --seed-contents-- + +```js +function tooMuchScreenTime(hours) { + + return hours; +} +``` + +# --solutions-- + +```js +function tooMuchScreenTime(hours) { + for (let h of hours) { + if (h >= 10) return true; + } + + for (let i = 0; i <= 4; i++) { + const avg3 = (hours[i] + hours[i+1] + hours[i+2]) / 3; + if (avg3 >= 8) return true; + } + + const weeklyAvg = hours.reduce((sum, h) => sum + h, 0) / 7; + if (weeklyAvg >= 6) return true; + + return false; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68af0687ef34c76c28ffa54f.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68af0687ef34c76c28ffa54f.md new file mode 100644 index 0000000000000000000000000000000000000000..003f1a9c0c8a4668c6ee2876543ab293acc9587e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68af0687ef34c76c28ffa54f.md @@ -0,0 +1,82 @@ +--- +id: 68af0687ef34c76c28ffa54f +title: "Challenge 34: Missing Numbers" +challengeType: 28 +dashedName: challenge-34 +--- + +# --description-- + +Given an array of integers from 1 to `n`, inclusive, return an array of all the missing integers between 1 and `n` (where `n` is the largest number in the given array). + +- The given array may be unsorted and may contain duplicates. +- The returned array should be in ascending order. +- If no integers are missing, return an empty array. + +# --hints-- + +`findMissingNumbers([1, 3, 5])` should return `[2, 4]`. + +```js +assert.deepEqual(findMissingNumbers([1, 3, 5]), [2, 4]); +``` + +`findMissingNumbers([1, 2, 3, 4, 5])` should return `[]`. + +```js +assert.deepEqual(findMissingNumbers([1, 2, 3, 4, 5]), []); +``` + +`findMissingNumbers([1, 10])` should return `[2, 3, 4, 5, 6, 7, 8, 9]`. + +```js +assert.deepEqual(findMissingNumbers([1, 10]), [2, 3, 4, 5, 6, 7, 8, 9]); +``` + +`findMissingNumbers([10, 1, 10, 1, 10, 1])` should return `[2, 3, 4, 5, 6, 7, 8, 9]`. + +```js +assert.deepEqual(findMissingNumbers([10, 1, 10, 1, 10, 1]), [2, 3, 4, 5, 6, 7, 8, 9]); +``` + +`findMissingNumbers([3, 1, 4, 1, 5, 9])` should return `[2, 6, 7, 8]`. + +```js +assert.deepEqual(findMissingNumbers([1, 2, 3, 4, 5]), []); +``` + +`findMissingNumbers([1, 2, 3, 4, 5, 7, 8, 9, 10, 12, 6, 8, 9, 3, 2, 10, 7, 4])` should return `[11]`. + +```js +assert.deepEqual(findMissingNumbers([1, 2, 3, 4, 5, 7, 8, 9, 10, 12, 6, 8, 9, 3, 2, 10, 7, 4]), [11]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function findMissingNumbers(arr) { + + return arr; +} +``` + +# --solutions-- + +```js +function findMissingNumbers(arr) { + if (arr.length === 0) return []; + + const n = Math.max(...arr); + const set = new Set(arr); + const result = []; + + for (let i = 1; i <= n; i++) { + if (!set.has(i)) { + result.push(i); + } + } + return result; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b06e589bf227324381476f.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b06e589bf227324381476f.md new file mode 100644 index 0000000000000000000000000000000000000000..da1900b3ae5c58ec055aa8fc5d84f7ccdf72e44c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b06e589bf227324381476f.md @@ -0,0 +1,66 @@ +--- +id: 68b06e589bf227324381476f +title: "Challenge 35: Word Frequency" +challengeType: 28 +dashedName: challenge-35 +--- + +# --description-- + +Given a paragraph, return an array of the three most frequently occurring words. + +- Words in the paragraph will be separated by spaces. +- Ignore case in the given paragraph. For example, treat `Hello` and `hello` as the same word. +- Ignore punctuation in the given paragraph. Punctuation consists of commas (`,`), periods (`.`), and exclamation points (`!`). +- The returned array should have all lowercase words. +- The returned array should be in descending order with the most frequently occurring word first. + +# --hints-- + +`getWords("Coding in Python is fun because coding Python allows for coding in Python easily while coding")` should return `["coding", "python", "in"]`. + +```js +assert.deepEqual(getWords("Coding in Python is fun because coding Python allows for coding in Python easily while coding"), ["coding", "python", "in"]); +``` + +`getWords("I like coding. I like testing. I love debugging!")` should return `["i", "like", "coding"]`. + +```js +assert.deepEqual(getWords("I like coding. I like testing. I love debugging!"), ["i", "like", "coding"]); +``` + +`getWords("Debug, test, deploy. Debug, debug, test, deploy. Debug, test, test, deploy!")` should return `["debug", "test", "deploy"]`. + +```js +assert.deepEqual(getWords("Debug, test, deploy. Debug, debug, test, deploy. Debug, test, test, deploy!"), ["debug", "test", "deploy"]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getWords(paragraph) { + + return paragraph; +} +``` + +# --solutions-- + +```js +function getWords(paragraph) { + const cleaned = paragraph.replace(/[.,!]/g, "").toLowerCase(); + const words = cleaned.split(/\s+/); + + const freq = {}; + for (const word of words) { + if (word) { + freq[word] = (freq[word] || 0) + 1; + } + } + + const sorted = Object.keys(freq).sort((a, b) => freq[b] - freq[a]); + return sorted.slice(0, 3); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b06e589bf2273243814771.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b06e589bf2273243814771.md new file mode 100644 index 0000000000000000000000000000000000000000..089ef381aa681e7c56f2402b89c75704fb74c01e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b06e589bf2273243814771.md @@ -0,0 +1,77 @@ +--- +id: 68b06e589bf2273243814771 +title: "Challenge 36: Thermostat Adjuster" +challengeType: 28 +dashedName: challenge-36 +--- + +# --description-- + +Given the current temperature of a room and a target temperature, return a string indicating how to adjust the room temperature based on these constraints: + +- Return `"heat"` if the current temperature is below the target. +- Return `"cool"` if the current temperature is above the target. +- Return `"hold"` if the current temperature is equal to the target. + +# --hints-- + +`adjustThermostat(68, 72)` should return `"heat"`. + +```js +assert.equal(adjustThermostat(68, 72), "heat"); +``` + +`adjustThermostat(75, 72)` should return `"cool"`. + +```js +assert.equal(adjustThermostat(75, 72), "cool"); +``` + +`adjustThermostat(72, 72)` should return `"hold"`. + +```js +assert.equal(adjustThermostat(72, 72), "hold"); +``` + +`adjustThermostat(-20.5, -10.1)` should return `"heat"`. + +```js +assert.equal(adjustThermostat(-20.5, -10.1), "heat"); +``` + +`adjustThermostat(100, 99.9)` should return `"cool"`. + +```js +assert.equal(adjustThermostat(100, 99.9), "cool"); +``` + +`adjustThermostat(0.0, 0.0)` should return `"hold"`. + +```js +assert.equal(adjustThermostat(0.0, 0.0), "hold"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function adjustThermostat(temp, target) { + + return temp; +} +``` + +# --solutions-- + +```js +function adjustThermostat(temp, target) { + if (temp < target) { + return "heat"; + } else if (temp > target) { + return "cool"; + } else { + return "hold"; + } +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b06e589bf2273243814773.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b06e589bf2273243814773.md new file mode 100644 index 0000000000000000000000000000000000000000..855bef95d887944fea7c34b78b29ea6ae293df06 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b06e589bf2273243814773.md @@ -0,0 +1,67 @@ +--- +id: 68b06e589bf2273243814773 +title: "Challenge 37: Sentence Capitalizer" +challengeType: 28 +dashedName: challenge-37 +--- + +# --description-- + +Given a paragraph, return a new paragraph where the first letter of each sentence is capitalized. + +- All other characters should be preserved. +- Sentences can end with a period (`.`), one or more question marks (`?`), or one or more exclamation points (`!`). + +# --hints-- + +`capitalize("this is a simple sentence.")` should return `"This is a simple sentence."`. + +```js +assert.equal(capitalize("this is a simple sentence."), "This is a simple sentence."); +``` + +`capitalize("hello world. how are you?")` should return `"Hello world. How are you?"`. + +```js +assert.equal(capitalize("hello world. how are you?"), "Hello world. How are you?"); +``` + +`capitalize("i did today's coding challenge... it was fun!!")` should return `"I did today's coding challenge... It was fun!!"`. + +```js +assert.equal(capitalize("i did today's coding challenge... it was fun!!"), "I did today's coding challenge... It was fun!!"); +``` + +`capitalize("crazy!!!strange???unconventional...sentences.")` should return `"Crazy!!!Strange???Unconventional...Sentences."`. + +```js +assert.equal(capitalize("crazy!!!strange???unconventional...sentences."), "Crazy!!!Strange???Unconventional...Sentences."); +``` + +`capitalize("there's a space before this period . why is there a space before that period ?")` should return `"There's a space before this period . Why is there a space before that period ?"`. + +```js +assert.equal(capitalize("there's a space before this period . why is there a space before that period ?"), "There's a space before this period . Why is there a space before that period ?"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function capitalize(paragraph) { + + return paragraph; +} +``` + +# --solutions-- + +```js +function capitalize(paragraph) { + return paragraph.replace(/([.!?]+)(\s*)([a-z])/g, (match, punc, spaces, char) => { + return punc + spaces + char.toUpperCase(); + }) + .replace(/^([a-z])/, (match, char) => char.toUpperCase()); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b06e589bf2273243814775.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b06e589bf2273243814775.md new file mode 100644 index 0000000000000000000000000000000000000000..12dc13ff726153f13bbf0a17c17f504c9c00ab45 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b06e589bf2273243814775.md @@ -0,0 +1,69 @@ +--- +id: 68b06e589bf2273243814775 +title: "Challenge 38: Slug Generator" +challengeType: 28 +dashedName: challenge-38 +--- + +# --description-- + +Given a string, return a URL-friendly version of the string using the following constraints: + +- All letters should be lowercase. +- All characters that are not letters, numbers, or spaces should be removed. +- All spaces should be replaced with the URL-encoded space code `%20`. +- Consecutive spaces should be replaced with a single `%20`. +- The returned string should not have leading or trailing `%20`. + +# --hints-- + +`generateSlug("helloWorld")` should return `"helloworld"`. + +```js +assert.equal(generateSlug("helloWorld"), "helloworld"); +``` + +`generateSlug("hello world!")` should return `"hello%20world"`. + +```js +assert.equal(generateSlug("hello world!"), "hello%20world"); +``` + +`generateSlug(" hello-world ")` should return `"helloworld"`. + +```js +assert.equal(generateSlug(" hello-world "), "helloworld"); +``` + +`generateSlug("hello world")` should return `"hello%20world"`. + +```js +assert.equal(generateSlug("hello world"), "hello%20world"); +``` + +`generateSlug(" ?H^3-1*1]0! W[0%R#1]D ")` should return `"h3110%20w0r1d"`. + +```js +assert.equal(generateSlug(" ?H^3-1*1]0! W[0%R#1]D "), "h3110%20w0r1d"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function generateSlug(str) { + + return str; +} +``` + +# --solutions-- + +```js +function generateSlug(str) { + let cleaned = str.replace(/[^a-zA-Z0-9 ]+/g, ""); + cleaned = cleaned.replace(/\s+/g, " ").trim(); + return cleaned.toLowerCase().replace(/ /g, "%20"); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b06e589bf2273243814777.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b06e589bf2273243814777.md new file mode 100644 index 0000000000000000000000000000000000000000..f3f21899420725131373d3714c6a64634fe786fe --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b06e589bf2273243814777.md @@ -0,0 +1,68 @@ +--- +id: 68b06e589bf2273243814777 +title: "Challenge 39: Fill The Tank" +challengeType: 28 +dashedName: challenge-39 +--- + +# --description-- + +Given the size of a fuel tank, the current fuel level, and the price per gallon, return the cost to fill the tank all the way. + +- `tankSize` is the total capacity of the tank in gallons. +- `fuelLevel` is the current amount of fuel in the tank in gallons. +- `pricePerGallon` is the cost of one gallon of fuel. +- The returned value should be rounded to two decimal places in the format: `"$d.dd"`. + +# --hints-- + +`costToFill(20, 0, 4.00)` should return `"$80.00"`. + +```js +assert.equal(costToFill(20, 0, 4.00), "$80.00"); +``` + +`costToFill(15, 10, 3.50)` should return `"$17.50"`. + +```js +assert.equal(costToFill(15, 10, 3.50), "$17.50"); +``` + +`costToFill(18, 9, 3.25)` should return `"$29.25"`. + +```js +assert.equal(costToFill(18, 9, 3.25), "$29.25"); +``` + +`costToFill(12, 12, 4.99)` should return `"$0.00"`. + +```js +assert.equal(costToFill(12, 12, 4.99), "$0.00"); +``` + +`costToFill(15, 9.5, 3.98)` should return `"$21.89"`. + +```js +assert.equal(costToFill(15, 9.5, 3.98), "$21.89"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function costToFill(tankSize, fuelLevel, pricePerGallon) { + + return tankSize; +} +``` + +# --solutions-- + +```js +function costToFill(tankSize, fuelLevel, pricePerGallon) { + let gallonsNeeded = tankSize - fuelLevel; + let cost = gallonsNeeded * pricePerGallon; + return `$${cost.toFixed(2)}`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b1f72371a5ac895ac70a02.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b1f72371a5ac895ac70a02.md new file mode 100644 index 0000000000000000000000000000000000000000..777d4162982c412e8630b39a7b0f3e242c5e3f31 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b1f72371a5ac895ac70a02.md @@ -0,0 +1,65 @@ +--- +id: 68b1f72371a5ac895ac70a02 +title: "Challenge 40: Photo Storage" +challengeType: 28 +dashedName: challenge-40 +--- + +# --description-- + +Given a photo size in megabytes (MB), and hard drive capacity in gigabytes (GB), return the number of photos the hard drive can store using the following constraints: + +- 1 gigabyte equals 1000 megabytes. +- Return the number of whole photos the drive can store. + +# --hints-- + +`numberOfPhotos(1, 1)` should return `1000`. + +```js +assert.equal(numberOfPhotos(1, 1), 1000); +``` + +`numberOfPhotos(2, 1)` should return `500`. + +```js +assert.equal(numberOfPhotos(2, 1), 500); +``` + +`numberOfPhotos(4, 256)` should return `64000`. + +```js +assert.equal(numberOfPhotos(4, 256), 64000); +``` + +`numberOfPhotos(3.5, 750)` should return `214285`. + +```js +assert.equal(numberOfPhotos(3.5, 750), 214285); +``` + +`numberOfPhotos(3.5, 5.5)` should return `1571`. + +```js +assert.equal(numberOfPhotos(3.5, 5.5), 1571); +``` + +# --seed-- + +## --seed-contents-- + +```js +function numberOfPhotos(photoSizeMb, hardDriveSizeGb) { + + return photoSizeMb; +} +``` + +# --solutions-- + +```js +function numberOfPhotos(photoSizeMb, driveSizeGb) { + const driveSizeMb = driveSizeGb * 1000; + return Math.floor(driveSizeMb / photoSizeMb); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b1f72371a5ac895ac70a04.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b1f72371a5ac895ac70a04.md new file mode 100644 index 0000000000000000000000000000000000000000..8217feb020d6bd29d76bf22e30b08b73d6487d6b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b1f72371a5ac895ac70a04.md @@ -0,0 +1,91 @@ +--- +id: 68b1f72371a5ac895ac70a04 +title: "Challenge 41: File Storage" +challengeType: 28 +dashedName: challenge-41 +--- + +# --description-- + +Given a file size, a unit for the file size, and hard drive capacity in gigabytes (GB), return the number of files the hard drive can store using the following constraints: + +- The unit for the file size can be bytes (`"B"`), kilobytes (`"KB"`), or megabytes (`"MB"`). +- Return the number of whole files the drive can fit. +- Use the following conversions: + +| Unit | Equivalent | +|:----:|:----------:| +| 1 B | 1 B | +| 1 KB | 1000 B | +| 1 MB | 1000 KB | +| 1 GB | 1000 MB | + +For example, given `500`, `"KB"`, and `1` as arguments, determine how many 500 KB files can fit on a 1 GB hard drive. + +# --hints-- + +`numberOfFiles(500, "KB", 1)` should return `2000`. + +```js +assert.equal(numberOfFiles(500, "KB", 1), 2000); +``` + +`numberOfFiles(50000, "B", 1)` should return `20000`. + +```js +assert.equal(numberOfFiles(50000, "B", 1), 20000); +``` + +`numberOfFiles(5, "MB", 1)` should return `200`. + +```js +assert.equal(numberOfFiles(5, "MB", 1), 200); +``` + +`numberOfFiles(4096, "B", 1.5)` should return `366210`. + +```js +assert.equal(numberOfFiles(4096, "B", 1.5), 366210); +``` + +`numberOfFiles(220.5, "KB", 100)` should return `453514`. + +```js +assert.equal(numberOfFiles(220.5, "KB", 100), 453514); +``` + +`numberOfFiles(4.5, "MB", 750)` should return `166666`. + +```js +assert.equal(numberOfFiles(4.5, "MB", 750), 166666); +``` + +# --seed-- + +## --seed-contents-- + +```js +function numberOfFiles(fileSize, fileUnit, driveSizeGb) { + + return fileSize; +} +``` + +# --solutions-- + +```js +function numberOfFiles(fileSize, fileUnit, driveSizeGb) { + const driveSizeBytes = driveSizeGb * 1000 * 1000 * 1000; + + let fileSizeBytes; + if (fileUnit === "B") { + fileSizeBytes = fileSize; + } else if (fileUnit === "KB") { + fileSizeBytes = fileSize * 1000; + } else { + fileSizeBytes = fileSize * 1000 * 1000; + } + + return Math.floor(driveSizeBytes / fileSizeBytes); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b1f72371a5ac895ac70a06.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b1f72371a5ac895ac70a06.md new file mode 100644 index 0000000000000000000000000000000000000000..4f9cb7cf80e7f7933aaa7bba9b93a24d0086b75e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b1f72371a5ac895ac70a06.md @@ -0,0 +1,87 @@ +--- +id: 68b1f72371a5ac895ac70a06 +title: "Challenge 42: Video Storage" +challengeType: 28 +dashedName: challenge-42 +--- + +# --description-- + +Given a video size, a unit for the video size, a hard drive capacity, and a unit for the hard drive, return the number of videos the hard drive can store using the following constraints: + +- The unit for the video size can be bytes (`"B"`), kilobytes (`"KB"`), megabytes (`"MB"`), or gigabytes (`"GB"`). +- If not given one of the video units above, return `"Invalid video unit"`. +- The unit of the hard drive capacity can be gigabytes (`"GB"`) or terabytes (`"TB"`). +- If not given one of the hard drive units above, return `"Invalid drive unit"`. +- Return the number of whole videos the drive can fit. +- Use the following conversions: + +| Unit | Equivalent | +|:----:|:----------:| +| 1 B | 1 B | +| 1 KB | 1000 B | +| 1 MB | 1000 KB | +| 1 GB | 1000 MB | +| 1 TB | 1000 GB | + +For example, given `500`, `"MB"`, `100`, and `"GB"` as arguments, determine how many 500 MB videos can fit on a 100 GB hard drive. + +# --hints-- + +`numberOfVideos(500, "MB", 100, "GB")` should return `200`. + +```js +assert.equal(numberOfVideos(500, "MB", 100, "GB"), 200); +``` + +`numberOfVideos(1, "TB", 10, "TB")` should return `"Invalid video unit"`. + +```js +assert.equal(numberOfVideos(1, "TB", 10, "TB"), "Invalid video unit"); +``` + +`numberOfVideos(2000, "MB", 100000, "MB")` should return `"Invalid drive unit"`. + +```js +assert.equal(numberOfVideos(2000, "MB", 100000, "MB"), "Invalid drive unit"); +``` + +`numberOfVideos(500000, "KB", 2, "TB")` should return `4000`. + +```js +assert.equal(numberOfVideos(500000, "KB", 2, "TB"), 4000); +``` + +`numberOfVideos(1.5, "GB", 2.2, "TB")` should return `1466`. + +```js +assert.equal(numberOfVideos(1.5, "GB", 2.2, "TB"), 1466); +``` + +# --seed-- + +## --seed-contents-- + +```js +function numberOfVideos(videoSize, videoUnit, driveSize, driveUnit) { + + return videoSize; +} +``` + +# --solutions-- + +```js +function numberOfVideos(videoSize, videoUnit, driveSize, driveUnit) { + const videoUnits = { "KB": 1000, "MB": 1000 * 1000, "GB": 1000 * 1000 * 1000 }; + const driveUnits = { "GB": 1000 * 1000 * 1000, "TB": 1000 * 1000 * 1000 * 1000 }; + + if (!videoUnits[videoUnit]) return "Invalid video unit"; + if (!driveUnits[driveUnit]) return "Invalid drive unit"; + + const videoBytes = videoSize * videoUnits[videoUnit]; + const driveBytes = driveSize * driveUnits[driveUnit]; + + return Math.floor(driveBytes / videoBytes); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b1f72371a5ac895ac70a08.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b1f72371a5ac895ac70a08.md new file mode 100644 index 0000000000000000000000000000000000000000..6427508e05f7baed3b3d20fa381f667dc51a6407 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b1f72371a5ac895ac70a08.md @@ -0,0 +1,81 @@ +--- +id: 68b1f72371a5ac895ac70a08 +title: "Challenge 43: Digits vs Letters" +challengeType: 28 +dashedName: challenge-43 +--- + +# --description-- + +Given a string, return `"digits"` if the string has more digits than letters, `"letters"` if it has more letters than digits, and `"tie"` if it has the same amount of digits and letters. + +- Digits consist of `0-9`. +- Letters consist of `a-z` in upper or lower case. +- Ignore any other characters. + +# --hints-- + +`digitsOrLetters("abc123")` should return `"tie"`. + +```js +assert.equal(digitsOrLetters("abc123"), "tie"); +``` + +`digitsOrLetters("a1b2c3d")` should return `"letters"`. + +```js +assert.equal(digitsOrLetters("a1b2c3d"), "letters"); +``` + +`digitsOrLetters("1a2b3c4")` should return `"digits"`. + +```js +assert.equal(digitsOrLetters("1a2b3c4"), "digits"); +``` + +`digitsOrLetters("abc123!@#DEF")` should return `"letters"`. + +```js +assert.equal(digitsOrLetters("abc123!@#DEF"), "letters"); +``` + +`digitsOrLetters("H3110 W0R1D")` should return `"digits"`. + +```js +assert.equal(digitsOrLetters("H3110 W0R1D"), "digits"); +``` + +`digitsOrLetters("P455W0RD")` should return `"tie"`. + +```js +assert.equal(digitsOrLetters("P455W0RD"), "tie"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function digitsOrLetters(str) { + + return str; +} +``` + +# --solutions-- + +```js +function digitsOrLetters(str) { + let digitCount = 0; + let letterCount = 0; + + for (let char of str) { + if (/[0-9]/.test(char)) digitCount++; + else if (/[a-zA-Z]/.test(char)) letterCount++; + } + + if (digitCount > letterCount) return "digits"; + if (letterCount > digitCount) return "letters"; + return "tie"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b1f72371a5ac895ac70a0a.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b1f72371a5ac895ac70a0a.md new file mode 100644 index 0000000000000000000000000000000000000000..982cd62f8f20386b8ba0998dd6cdc93b8e805f1e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b1f72371a5ac895ac70a0a.md @@ -0,0 +1,79 @@ +--- +id: 68b1f72371a5ac895ac70a0a +title: "Challenge 44: String Mirror" +challengeType: 28 +dashedName: challenge-44 +--- + +# --description-- + +Given two strings, determine if the second string is a mirror of the first. + +- A string is considered a mirror if it contains the same letters in reverse order. +- Treat uppercase and lowercase letters as distinct. +- Ignore all non-alphabetical characters. + +# --hints-- + +`isMirror("helloworld", "helloworld")` should return `false`. + +```js +assert.isFalse(isMirror("helloworld", "helloworld")); +``` + +`isMirror("Hello World", "dlroW olleH")` should return `true`. + +```js +assert.isTrue(isMirror("Hello World", "dlroW olleH")); +``` + +`isMirror("RaceCar", "raCecaR")` should return `true`. + +```js +assert.isTrue(isMirror("RaceCar", "raCecaR")); +``` + +`isMirror("RaceCar", "RaceCar")` should return `false`. + +```js +assert.isFalse(isMirror("RaceCar", "RaceCar")); +``` + +`isMirror("Mirror", "rorrim")` should return `false`. + +```js +assert.isFalse(isMirror("Mirror", "rorrim")); +``` + +`isMirror("Hello World", "dlroW-olleH")` should return `true`. + +```js +assert.isTrue(isMirror("Hello World", "dlroW-olleH")); +``` + +`isMirror("Hello World", "!dlroW !olleH")` should return `true`. + +```js +assert.isTrue(isMirror("Hello World", "!dlroW !olleH")); +``` + +# --seed-- + +## --seed-contents-- + +```js +function isMirror(str1, str2) { + + return str1; +} +``` + +# --solutions-- + +```js +function isMirror(str1, str2) { + const clean1 = str1.replace(/[^a-zA-Z]/g, ""); + const clean2 = str2.replace(/[^a-zA-Z]/g, ""); + return clean1.split("").reverse().join("") === clean2; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7687dded630607aceccab.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7687dded630607aceccab.md new file mode 100644 index 0000000000000000000000000000000000000000..8edcd42f37311e7877f3fe08b57896a0326d4e6b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7687dded630607aceccab.md @@ -0,0 +1,83 @@ +--- +id: 68b7687dded630607aceccab +title: "Challenge 45: Perfect Square" +challengeType: 28 +dashedName: challenge-45 +--- + +# --description-- + +Given an integer, determine if it is a perfect square. + +- A number is a perfect square if you can multiply an integer by itself to achieve the number. For example, 9 is a perfect square because you can multiply 3 by itself to get it. + +# --hints-- + +`isPerfectSquare(9)` should return `true`. + +```js +assert.isTrue(isPerfectSquare(9)); +``` + +`isPerfectSquare(49)` should return `true`. + +```js +assert.isTrue(isPerfectSquare(49)); +``` + +`isPerfectSquare(1)` should return `true`. + +```js +assert.isTrue(isPerfectSquare(1)); +``` + +`isPerfectSquare(2)` should return `false`. + +```js +assert.isFalse(isPerfectSquare(2)); +``` + +`isPerfectSquare(99)` should return `false`. + +```js +assert.isFalse(isPerfectSquare(99)); +``` + +`isPerfectSquare(-9)` should return `false`. + +```js +assert.isFalse(isPerfectSquare(-9)); +``` + +`isPerfectSquare(0)` should return `true`. + +```js +assert.isTrue(isPerfectSquare(0)); +``` + +`isPerfectSquare(25281)` should return `true`. + +```js +assert.isTrue(isPerfectSquare(25281)); +``` + +# --seed-- + +## --seed-contents-- + +```js +function isPerfectSquare(n) { + + return n; +} +``` + +# --solutions-- + +```js +function isPerfectSquare(n) { + if (n < 0) return false; + const root = Math.floor(Math.sqrt(n)); + return root * root === n; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7687dded630607aceccad.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7687dded630607aceccad.md new file mode 100644 index 0000000000000000000000000000000000000000..ae2043684bf3871d7dc2caca462f3b4c67390e07 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7687dded630607aceccad.md @@ -0,0 +1,63 @@ +--- +id: 68b7687dded630607aceccad +title: "Challenge 46: 2nd Largest" +challengeType: 28 +dashedName: challenge-46 +--- + +# --description-- + +Given an array, return the second largest distinct number. + +# --hints-- + +`secondLargest([1, 2, 3, 4])` should return `3`. + +```js +assert.equal(secondLargest([1, 2, 3, 4]), 3); +``` + +`secondLargest([20, 139, 94, 67, 31])` should return `94`. + +```js +assert.equal(secondLargest([20, 139, 94, 67, 31]), 94); +``` + +`secondLargest([2, 3, 4, 6, 6])` should return `4`. + +```js +assert.equal(secondLargest([2, 3, 4, 6, 6]), 4); +``` + +`secondLargest([10, -17, 55.5, 44, 91, 0])` should return `55.5`. + +```js +assert.equal(secondLargest([10, -17, 55.5, 44, 91, 0]), 55.5); +``` + +`secondLargest([1, 0, -1, 0, 1, 0, -1, 1, 0])` should return `0`. + +```js +assert.equal(secondLargest([1, 0, -1, 0, 1, 0, -1, 1, 0]), 0); +``` + +# --seed-- + +## --seed-contents-- + +```js +function secondLargest(arr) { + + return arr; +} +``` + +# --solutions-- + +```js +function secondLargest(arr) { + const unique = [...new Set(arr)]; + unique.sort((a, b) => b - a); + return unique[1]; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7687dded630607aceccaf.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7687dded630607aceccaf.md new file mode 100644 index 0000000000000000000000000000000000000000..f81c6044fd30ce1e4193ad9d2a04df72e41df0b2 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7687dded630607aceccaf.md @@ -0,0 +1,75 @@ +--- +id: 68b7687dded630607aceccaf +title: "Challenge 47: Caught Speeding" +challengeType: 28 +dashedName: challenge-47 +--- + +# --description-- + +Given an array of numbers representing the speed at which vehicles were observed traveling, and a number representing the speed limit, return an array with two items, the number of vehicles that were speeding, followed by the average amount beyond the speed limit of those vehicles. + +- If there were no vehicles speeding, return `[0, 0]`. + +# --hints-- + +`speeding([50, 60, 55], 60)` should return `[0, 0]`. + +```js +assert.deepEqual(speeding([50, 60, 55], 60), [0, 0]); +``` + +`speeding([58, 50, 60, 55], 55)` should return `[2, 4]`. + +```js +assert.deepEqual(speeding([58, 50, 60, 55], 55), [2, 4]); +``` + +`speeding([61, 81, 74, 88, 65, 71, 68], 70)` should return `[4, 8.5]`. + +```js +assert.deepEqual(speeding([61, 81, 74, 88, 65, 71, 68], 70), [4, 8.5]); +``` + +`speeding([100, 105, 95, 102], 100)` should return `[2, 3.5]`. + +```js +assert.deepEqual(speeding([100, 105, 95, 102], 100), [2, 3.5]); +``` + +`speeding([40, 45, 44, 50, 112, 39], 55)` should return `[1, 57]`. + +```js +assert.deepEqual(speeding([40, 45, 44, 50, 112, 39], 55), [1, 57]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function speeding(speeds, limit) { + + return speeds; +} +``` + +# --solutions-- + +```js +function speeding(speeds, limit) { + let speeding = 0; + let totalOver = 0; + + for (let speed of speeds) { + if (speed > limit) { + speeding++; + totalOver += (speed - limit); + } + } + + if (speeding === 0) return [0, 0]; + + return [speeding, totalOver / speeding]; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7687dded630607aceccb1.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7687dded630607aceccb1.md new file mode 100644 index 0000000000000000000000000000000000000000..478fc96fe79a0bf8dc729e04aaae3fbe92f92055 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7687dded630607aceccb1.md @@ -0,0 +1,104 @@ +--- +id: 68b7687dded630607aceccb1 +title: "Challenge 48: Spam Detector" +challengeType: 28 +dashedName: challenge-48 +--- + +# --description-- + +Given a phone number in the format `"+A (BBB) CCC-DDDD"`, where each letter represents a digit as follows: + +- `A` represents the country code and can be any number of digits. +- `BBB` represents the area code and will always be three digits. +- `CCC` and `DDDD` represent the local number and will always be three and four digits long, respectively. + +Determine if it's a spam number based on the following criteria: + +- The country code is greater than 2 digits long or doesn't begin with a zero (`0`). +- The area code is greater than 900 or less than 200. +- The sum of first three digits of the local number appears within last four digits of the local number. +- The number has the same digit four or more times in a row (ignoring the formatting characters). + +# --hints-- + +`isSpam("+0 (200) 234-0182")` should return `false`. + +```js +assert.isFalse(isSpam("+0 (200) 234-0182")); +``` + +`isSpam("+091 (555) 309-1922")` should return `true`. + +```js +assert.isTrue(isSpam("+091 (555) 309-1922")); +``` + +`isSpam("+1 (555) 435-4792")` should return `true`. + +```js +assert.isTrue(isSpam("+1 (555) 435-4792")); +``` + +`isSpam("+0 (955) 234-4364")` should return `true`. + +```js +assert.isTrue(isSpam("+0 (955) 234-4364")); +``` + +`isSpam("+0 (155) 131-6943")` should return `true`. + +```js +assert.isTrue(isSpam("+0 (155) 131-6943")); +``` + +`isSpam("+0 (555) 135-0192")` should return `true`. + +```js +assert.isTrue(isSpam("+0 (555) 135-0192")); +``` + +`isSpam("+0 (555) 564-1987")` should return `true`. + +```js +assert.isTrue(isSpam("+0 (555) 564-1987")); +``` + +`isSpam("+00 (555) 234-0182")` should return `false`. + +```js +assert.isFalse(isSpam("+00 (555) 234-0182")); +``` + +# --seed-- + +## --seed-contents-- + +```js +function isSpam(number) { + + return number; +} +``` + +# --solutions-- + +```js +function isSpam(number) { + const match = number.match(/^\+(\d+)\s\((\d{3})\)\s(\d{3})-(\d{4})$/); + const [, countryCode, areaCode, ccc, dddd] = match; + const allDigits = countryCode + areaCode + ccc + dddd; + + if (countryCode.length > 2 || !countryCode.startsWith("0")) return true; + + const areaNum = parseInt(areaCode, 10); + if (areaNum > 900 || areaNum < 200) return true; + + const sumCCC = ccc.split("").reduce((a, b) => a + parseInt(b), 0); + if (dddd.includes(sumCCC.toString())) return true; + + if (/(\d)\1\1\1/.test(allDigits)) return true; + + return false; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7687dded630607aceccb3.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7687dded630607aceccb3.md new file mode 100644 index 0000000000000000000000000000000000000000..e931647e41feb0abd510951fc8c4b184c73ca46d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7687dded630607aceccb3.md @@ -0,0 +1,54 @@ +--- +id: 68b7687dded630607aceccb3 +title: "Challenge 49: CSV Header Parser" +challengeType: 28 +dashedName: challenge-49 +--- + +# --description-- + +Given the first line of a comma-separated values (CSV) file, return an array containing the headings. + +- The first line of a CSV file contains headings separated by commas. +- Remove any leading or trailing whitespace from each heading. + +# --hints-- + +`getHeadings("name,age,city")` should return `["name", "age", "city"]`. + +```js +assert.deepEqual(getHeadings("name,age,city"), ["name", "age", "city"]); +``` + +`getHeadings("first name,last name,phone")` should return `["first name", "last name", "phone"]`. + +```js +assert.deepEqual(getHeadings("first name,last name,phone"), ["first name", "last name", "phone"]); +``` + +`getHeadings("username , email , signup date ")` should return `["username", "email", "signup date"]`. + +```js +assert.deepEqual(getHeadings("username , email , signup date "), ["username", "email", "signup date"]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getHeadings(csv) { + + return csv; +} +``` + +# --solutions-- + +```js +function getHeadings(csv) { + return csv + .split(",") + .map(h => h.trim()); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7cadffed0e75a517da66f.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7cadffed0e75a517da66f.md new file mode 100644 index 0000000000000000000000000000000000000000..54065c756fbf3e9543cd41930c6d545c343eeb5d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7cadffed0e75a517da66f.md @@ -0,0 +1,62 @@ +--- +id: 68b7cadffed0e75a517da66f +title: "Challenge 50: Longest Word" +challengeType: 28 +dashedName: challenge-50 +--- + +# --description-- + +Given a sentence, return the longest word in the sentence. + +- Ignore periods (`.`) when determining word length. +- If multiple words are ties for the longest, return the first one that occurs. + +# --hints-- + +`getLongestWord("coding is fun")` should return `"coding"`. + +```js +assert.equal(getLongestWord("coding is fun"), "coding"); +``` + +`getLongestWord("Coding challenges are fun and educational.")` should return `"educational"`. + +```js +assert.equal(getLongestWord("Coding challenges are fun and educational."), "educational"); +``` + +`getLongestWord("This sentence has multiple long words.")` should return `"sentence"`. + +```js +assert.equal(getLongestWord("This sentence has multiple long words."), "sentence"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getLongestWord(sentence) { + + return sentence; +} +``` + +# --solutions-- + +```js +function getLongestWord(sentence) { + const words = sentence.split(' '); + + let longest = ''; + for (let word of words) { + const cleanWord = word.replace(/\./g, ''); + if (cleanWord.length > longest.length) { + longest = cleanWord; + } + } + + return longest; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7cadffed0e75a517da671.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7cadffed0e75a517da671.md new file mode 100644 index 0000000000000000000000000000000000000000..587dfb5f566a949a937c211b4d5a555b0b299957 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7cadffed0e75a517da671.md @@ -0,0 +1,48 @@ +--- +id: 68b7cadffed0e75a517da671 +title: "Challenge 51: Phone Number Formatter" +challengeType: 28 +dashedName: challenge-51 +--- + +# --description-- + +Given a string of eleven digits, return the string as a phone number in this format: `"+D (DDD) DDD-DDDD"`. + +# --hints-- + +`formatNumber("05552340182")` should return `"+0 (555) 234-0182"`. + +```js +assert.equal(formatNumber("05552340182"), "+0 (555) 234-0182"); +``` + +`formatNumber("15554354792")` should return `"+1 (555) 435-4792"`. + +```js +assert.equal(formatNumber("15554354792"), "+1 (555) 435-4792"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function formatNumber(number) { + + return number; +} +``` + +# --solutions-- + +```js +function formatNumber(number) { + const country = number[0]; + const area = number.slice(1, 4); + const prefix = number.slice(4, 7); + const line = number.slice(7); + + return `+${country} (${area}) ${prefix}-${line}`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7cadffed0e75a517da673.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7cadffed0e75a517da673.md new file mode 100644 index 0000000000000000000000000000000000000000..db2ac5e31589d96ff646e5d13fa8fe1aa51d3618 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7cadffed0e75a517da673.md @@ -0,0 +1,68 @@ +--- +id: 68b7cadffed0e75a517da673 +title: "Challenge 52: Binary to Decimal" +challengeType: 28 +dashedName: challenge-52 +--- + +# --description-- + +Given a string representing a binary number, return its decimal equivalent as a number. + +A binary number uses only the digits `0` and `1` to represent any number. To convert binary to decimal, multiply each digit by a power of `2` and add them together. Start by multiplying the rightmost digit by `2^0`, the next digit to the left by `2^1`, and so on. Once all digits have been multiplied by a power of `2`, add the result together. + +For example, the binary number `101` equals `5` in decimal because: + +```mathml +1 * 2^2 + 0 * 2^1 + 1 * 2^0 = 4 + 0 + 1 = 5 +``` + +# --hints-- + +`toDecimal("101")` should return `5`. + +```js +assert.equal(toDecimal("101"), 5); +``` + +`toDecimal("1010")` should return `10`. + +```js +assert.equal(toDecimal("1010"), 10); +``` + +`toDecimal("10010")` should return `18`. + +```js +assert.equal(toDecimal("10010"), 18); +``` + +`toDecimal("1010101")` should return `85`. + +```js +assert.equal(toDecimal("1010101"), 85); +``` + +# --seed-- + +## --seed-contents-- + +```js +function toDecimal(binary) { + + return binary; +} +``` + +# --solutions-- + +```js +function toDecimal(binary) { + let decimal = 0; + for (let i = 0; i < binary.length; i++) { + const bit = parseInt(binary[binary.length - 1 - i], 10); + decimal += bit * Math.pow(2, i); + } + return decimal; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7cadffed0e75a517da675.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7cadffed0e75a517da675.md new file mode 100644 index 0000000000000000000000000000000000000000..1b39c91dca6858f7e775e7bbf055b8376867b90f --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7cadffed0e75a517da675.md @@ -0,0 +1,72 @@ +--- +id: 68b7cadffed0e75a517da675 +title: "Challenge 53: Decimal to Binary" +challengeType: 28 +dashedName: challenge-53 +--- + +# --description-- + +Given a non-negative integer, return its binary representation as a string. + +A binary number uses only the digits `0` and `1` to represent any number. To convert a decimal number to binary, repeatedly divide the number by `2` and record the remainder. Repeat until the number is zero. Read the remainders last recorded to first. For example, to convert `12` to binary: + +```mathml +12 ÷ 2 = 6 remainder 0 +6 ÷ 2 = 3 remainder 0 +3 ÷ 2 = 1 remainder 1 +1 ÷ 2 = 0 remainder 1 +``` + +`12` in binary is `1100`. + +# --hints-- + +`toBinary(5)` should return `"101"`. + +```js +assert.equal(toBinary(5), "101"); +``` + +`toBinary(12)` should return `"1100"`. + +```js +assert.equal(toBinary(12), "1100"); +``` + +`toBinary(50)` should return `"110010"`. + +```js +assert.equal(toBinary(50), "110010"); +``` + +`toBinary(99)` should return `"1100011"`. + +```js +assert.equal(toBinary(99), "1100011"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function toBinary(decimal) { + + return decimal; +} +``` + +# --solutions-- + +```js +function toBinary(decimal) { + if (decimal === 0) return "0"; + let binary = ""; + while (decimal > 0) { + binary = (decimal % 2) + binary; + decimal = Math.floor(decimal / 2); + } + return binary; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7cadffed0e75a517da677.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7cadffed0e75a517da677.md new file mode 100644 index 0000000000000000000000000000000000000000..0e1e667a090a0181ec2f920b51357e58fb9e5007 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68b7cadffed0e75a517da677.md @@ -0,0 +1,105 @@ +--- +id: 68b7cadffed0e75a517da677 +title: "Challenge 54: P@ssw0rd Str3ngth!" +challengeType: 28 +dashedName: challenge-54 +--- + +# --description-- + +Given a password string, return `"weak"`, `"medium"`, or `"strong"` based on the strength of the password. + +A password is evaluated according to the following rules: + +- It is at least 8 characters long. +- It contains both uppercase and lowercase letters. +- It contains at least one number. +- It contains at least one special character from this set: `!`, `@`, `#`, `$`, `%`, `^`, `&`, or `*`. + +Return `"weak"` if the password meets fewer than two of the rules. +Return `"medium"` if the password meets 2 or 3 of the rules. +Return `"strong"` if the password meets all 4 rules. + +# --hints-- + +`checkStrength("123456")` should return `"weak"`. + +```js +assert.equal(checkStrength("123456"), "weak"); +``` + +`checkStrength("pass!!!")` should return `"weak"`. + +```js +assert.equal(checkStrength("pass!!!"), "weak"); +``` + +`checkStrength("Qwerty")` should return `"weak"`. + +```js +assert.equal(checkStrength("Qwerty"), "weak"); +``` + +`checkStrength("PASSWORD")` should return `"weak"`. + +```js +assert.equal(checkStrength("PASSWORD"), "weak"); +``` + +`checkStrength("PASSWORD!")` should return `"medium"`. + +```js +assert.equal(checkStrength("PASSWORD!"), "medium"); +``` + +`checkStrength("PassWord%^!")` should return `"medium"`. + +```js +assert.equal(checkStrength("PassWord%^!"), "medium"); +``` + +`checkStrength("qwerty12345")` should return `"medium"`. + +```js +assert.equal(checkStrength("qwerty12345"), "medium"); +``` + +`checkStrength("S3cur3P@ssw0rd")` should return `"strong"`. + +```js +assert.equal(checkStrength("S3cur3P@ssw0rd"), "strong"); +``` + +`checkStrength("C0d3&Fun!")` should return `"strong"`. + +```js +assert.equal(checkStrength("C0d3&Fun!"), "strong"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function checkStrength(password) { + + return password; +} +``` + +# --solutions-- + +```js +function checkStrength(password) { + let rulesMet = 0; + + if (password.length >= 8) rulesMet++; + if (/[a-z]/.test(password) && /[A-Z]/.test(password)) rulesMet++; + if (/\d/.test(password)) rulesMet++; + if (/[!@#$%^&*]/.test(password)) rulesMet++; + + if (rulesMet < 2) return "weak"; + if (rulesMet < 4) return "medium"; + return "strong"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68c1a929005bf54d342aa8d2.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68c1a929005bf54d342aa8d2.md new file mode 100644 index 0000000000000000000000000000000000000000..18304f999dc036a54524572668c0d1c439359dcf --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68c1a929005bf54d342aa8d2.md @@ -0,0 +1,97 @@ +--- +id: 68c1a929005bf54d342aa8d2 +title: "Challenge 55: Space Week Day 1: Stellar Classification" +challengeType: 28 +dashedName: challenge-55 +--- + +# --description-- + +October 4th marks the beginning of World Space Week. The next seven days will bring you astronomy-themed coding challenges. + +For today's challenge, you are given the surface temperature of a star in Kelvin (K) and need to determine its stellar classification based on the following ranges: + +- `"O"`: 30,000 K or higher +- `"B"`: 10,000 K - 29,999 K +- `"A"`: 7,500 K - 9,999 K +- `"F"`: 6,000 K - 7,499 K +- `"G"`: 5,200 K - 5,999 K +- `"K"`: 3,700 K - 5,199 K +- `"M"`: 0 K - 3,699 K + +- Return the classification of the given star. + +# --hints-- + +`classification(5778)` should return `"G"`. + +```js +assert.equal(classification(5778), "G"); +``` + +`classification(2400)` should return `"M"`. + +```js +assert.equal(classification(2400), "M"); +``` + +`classification(9999)` should return `"A"`. + +```js +assert.equal(classification(9999), "A"); +``` + +`classification(3700)` should return `"K"`. + +```js +assert.equal(classification(3700), "K"); +``` + +`classification(3699)` should return `"M"`. + +```js +assert.equal(classification(3699), "M"); +``` + +`classification(210000)` should return `"O"`. + +```js +assert.equal(classification(210000), "O"); +``` + +`classification(6000)` should return `"F"`. + +```js +assert.equal(classification(6000), "F"); +``` + +`classification(11432)` should return `"B"`. + +```js +assert.equal(classification(11432), "B"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function classification(temp) { + + return temp; +} +``` + +# --solutions-- + +```js +function classification(temp) { + if (temp >= 30000) return "O"; + if (temp >= 10000) return "B"; + if (temp >= 7500) return "A"; + if (temp >= 6000) return "F"; + if (temp >= 5200) return "G"; + if (temp >= 3700) return "K"; + return "M"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68c1a929005bf54d342aa8d3.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68c1a929005bf54d342aa8d3.md new file mode 100644 index 0000000000000000000000000000000000000000..9f91f8e94be80d6c55ef3abc7372ba219afa80e9 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68c1a929005bf54d342aa8d3.md @@ -0,0 +1,80 @@ +--- +id: 68c1a929005bf54d342aa8d3 +title: "Challenge 56: Space Week Day 2: Exoplanet Search" +challengeType: 28 +dashedName: challenge-56 +--- + +# --description-- + +For the second day of Space Week, you are given a string where each character represents the luminosity reading of a star. Determine if the readings have detected an exoplanet using the transit method. The transit method is when a planet passes in front of a star, reducing its observed luminosity. + +- Luminosity readings only comprise of characters `0-9` and `A-Z` where each reading corresponds to the following numerical values: +- Characters `0-9` correspond to luminosity levels `0-9`. +- Characters `A-Z` correspond to luminosity levels `10-35`. + +A star is considered to have an exoplanet if any single reading is less than or equal to 80% of the average of all readings. For example, if the average luminosity of a star is 10, it would be considered to have a exoplanet if any single reading is 8 or less. + +# --hints-- + +`hasExoplanet("665544554")` should return `false`. + +```js +assert.isFalse(hasExoplanet("665544554")); +``` + +`hasExoplanet("FGFFCFFGG")` should return `true`. + +```js +assert.isTrue(hasExoplanet("FGFFCFFGG")); +``` + +`hasExoplanet("MONOPLONOMONPLNOMPNOMP")` should return `false`. + +```js +assert.isFalse(hasExoplanet("MONOPLONOMONPLNOMPNOMP")); +``` + +`hasExoplanet("FREECODECAMP")` should return `true`. + +```js +assert.isTrue(hasExoplanet("FREECODECAMP")); +``` + +`hasExoplanet("9AB98AB9BC98A")` should return `false`. + +```js +assert.isFalse(hasExoplanet("9AB98AB9BC98A")); +``` + +`hasExoplanet("ZXXWYZXYWYXZEGZXWYZXYGEE")` should return `true`. + +```js +assert.isTrue(hasExoplanet("ZXXWYZXYWYXZEGZXWYZXYGEE")); +``` + +# --seed-- + +## --seed-contents-- + +```js +function hasExoplanet(readings) { + + return readings; +} +``` + +# --solutions-- + +```js +function hasExoplanet(readings) { + let total = 0; + const values = readings.split('').map(c => parseInt(c, 36)); + + total = values.reduce((sum, v) => sum + v, 0); + const average = total / values.length; + const threshold = average * 0.8; + + return values.some(v => v <= threshold); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68c1a929005bf54d342aa8d4.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68c1a929005bf54d342aa8d4.md new file mode 100644 index 0000000000000000000000000000000000000000..b84f86db8951f04aae330508eaafbc00e4c0a0da --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68c1a929005bf54d342aa8d4.md @@ -0,0 +1,79 @@ +--- +id: 68c1a929005bf54d342aa8d4 +title: "Challenge 57: Space Week Day 3: Phone Home" +challengeType: 28 +dashedName: challenge-57 +--- + +# --description-- + +For day three of Space Week, you are given an array of numbers representing distances (in kilometers) between yourself, satellites, and your home planet in a communication route. Determine how long it will take a message sent through the route to reach its destination planet using the following constraints: + +- The first value in the array is the distance from your location to the first satellite. +- Each subsequent value, except for the last, is the distance to the next satellite. +- The last value in the array is the distance from the previous satellite to your home planet. +- The message travels at 300,000 km/s. +- Each satellite the message **passes through** adds a 0.5 second transmission delay. +- Return a number rounded to 4 decimal places, with trailing zeros removed. + +# --hints-- + +`sendMessage([300000, 300000])` should return `2.5`. + +```js +assert.equal(sendMessage([300000, 300000]), 2.5); +``` + +`sendMessage([384400, 384400])` should return `3.0627`. + +```js +assert.equal(sendMessage([384400, 384400]), 3.0627); +``` + +`sendMessage([54600000, 54600000])` should return `364.5`. + +```js +assert.equal(sendMessage([54600000, 54600000]), 364.5); +``` + +`sendMessage([1000000, 500000000, 1000000])` should return `1674.3333`. + +```js +assert.equal(sendMessage([1000000, 500000000, 1000000]), 1674.3333); +``` + +`sendMessage([10000, 21339, 50000, 31243, 10000])` should return `2.4086`. + +```js +assert.equal(sendMessage([10000, 21339, 50000, 31243, 10000]), 2.4086); +``` + +`sendMessage([802101, 725994, 112808, 3625770, 481239])` should return `21.1597`. + +```js +assert.equal(sendMessage([802101, 725994, 112808, 3625770, 481239]), 21.1597); +``` + +# --seed-- + +## --seed-contents-- + +```js +function sendMessage(route) { + + return route; +} +``` + +# --solutions-- + +```js +function sendMessage(route) { + let totalDistance = route.reduce((a, d) => a += d, 0); + + const delay = (route.length - 1) * 0.5 + const time = totalDistance / 300000 + const total = time + delay; + return Number(total.toFixed(4)) +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68c1a929005bf54d342aa8d5.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68c1a929005bf54d342aa8d5.md new file mode 100644 index 0000000000000000000000000000000000000000..a1b6d1d631a559f7404b83860e10f0572ca692ec --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68c1a929005bf54d342aa8d5.md @@ -0,0 +1,95 @@ +--- +id: 68c1a929005bf54d342aa8d5 +title: "Challenge 58: Space Week Day 4: Landing Spot" +challengeType: 28 +dashedName: challenge-58 +--- + +# --description-- + +In day four of Space Week, you are given a matrix of numbers (an array of arrays), representing potential landing spots for your rover. Find the safest landing spot based on the following rules: + +- Each spot in the matrix will contain a number from `0-9`, inclusive. +- Any `0` represents a potential landing spot. +- Any number other than `0` is too dangerous to land. The higher the number, the more dangerous. +- The safest spot is defined as the `0` cell whose surrounding cells (up to 4 neighbors, ignore diagonals) have the lowest total danger. +- Ignore out-of-bounds neighbors (corners and edges just have fewer neighbors). +- Return the indices of the safest landing spot. There will always only be one safest spot. + +For instance, given: + +```js +[ + [1, 0], + [2, 0] +] +``` + +Return `[0, 1]`, the indices for the `0` in the first array. + +# --hints-- + +`findLandingSpot([[1, 0], [2, 0]])` should return `[0, 1]`. + +```js +assert.deepEqual(findLandingSpot([[1, 0], [2, 0]]), [0, 1]); +``` + +`findLandingSpot([[9, 0, 3], [7, 0, 4], [8, 0, 5]])` should return `[1, 1]`. + +```js +assert.deepEqual(findLandingSpot([[9, 0, 3], [7, 0, 4], [8, 0, 5]]), [1, 1]); +``` + +`findLandingSpot([[1, 2, 1], [0, 0, 2], [3, 0, 0]])` should return `[2, 2]`. + +```js +assert.deepEqual(findLandingSpot([[1, 2, 1], [0, 0, 2], [3, 0, 0]]), [2, 2]); +``` + +`findLandingSpot([[9, 6, 0, 8], [7, 1, 1, 0], [3, 0, 3, 9], [8, 6, 0, 9]])` should return `[2, 1]`. + +```js +assert.deepEqual(findLandingSpot([[9, 6, 0, 8], [7, 1, 1, 0], [3, 0, 3, 9], [8, 6, 0, 9]]), [2, 1]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function findLandingSpot(matrix) { + + return matrix; +} +``` + +# --solutions-- + +```js +function findLandingSpot(matrix) { + let bestSpot = null; + let lowestNeighborSum = Infinity; + + for (let i = 0; i < matrix.length; i++) { + for (let j = 0; j < matrix[i].length; j++) { + + if (matrix[i][j] === 0) { + let currentNeighborSum = 0; + + if (i > 0) currentNeighborSum += matrix[i - 1][j]; + if (j < matrix[i].length - 1) currentNeighborSum += matrix[i][j + 1]; + if (i < matrix.length - 1) currentNeighborSum += matrix[i + 1][j]; + if (j > 0) currentNeighborSum += matrix[i][j - 1]; + + if (currentNeighborSum < lowestNeighborSum) { + lowestNeighborSum = currentNeighborSum; + bestSpot = [i, j]; + } + } + } + } + + return bestSpot; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68c1a929005bf54d342aa8d6.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68c1a929005bf54d342aa8d6.md new file mode 100644 index 0000000000000000000000000000000000000000..8d16a5bb54dba4991641925bfca7b28a258d7159 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68c1a929005bf54d342aa8d6.md @@ -0,0 +1,76 @@ +--- +id: 68c1a929005bf54d342aa8d6 +title: "Challenge 59: Space Week Day 5: Goldilocks Zone" +challengeType: 28 +dashedName: challenge-59 +--- + +# --description-- + +For the fifth day of Space Week, you will calculate the "Goldilocks zone" of a star - the region around a star where conditions are "just right" for liquid water to exist. + +Given the mass of a star, return an array with the start and end distances of its Goldilocks Zone in Astronomical Units. + +To calculate the Goldilocks Zone: + +1. Find the luminosity of the star by raising its mass to the power of 3.5. +2. The start of the zone is 0.95 times the square root of its luminosity. +3. The end of the zone is 1.37 times the square root of its luminosity. + +- Return the distances rounded to two decimal places. + +For example, given `1` as a mass, return `[0.95, 1.37]`. + +# --hints-- + +`goldilocksZone(1)` should return `[0.95, 1.37]`. + +```js +assert.deepEqual(goldilocksZone(1), [0.95, 1.37]); +``` + +`goldilocksZone(0.5)` should return `[0.28, 0.41]`. + +```js +assert.deepEqual(goldilocksZone(0.5), [0.28, 0.41]); +``` + +`goldilocksZone(6)` should return `[21.85, 31.51]`. + +```js +assert.deepEqual(goldilocksZone(6), [21.85, 31.51]); +``` + +`goldilocksZone(3.7)` should return `[9.38, 13.52]`. + +```js +assert.deepEqual(goldilocksZone(3.7), [9.38, 13.52]); +``` + +`goldilocksZone(20)` should return `[179.69, 259.13]`. + +```js +assert.deepEqual(goldilocksZone(20), [179.69, 259.13]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function goldilocksZone(mass) { + + return mass; +} +``` + +# --solutions-- + +```js +function goldilocksZone(mass) { + const luminosity = Math.pow(mass, 3.5); + const start = 0.95 * Math.sqrt(luminosity); + const end = 1.37 * Math.sqrt(luminosity); + return [Number(start.toFixed(2)), Number(end.toFixed(2))]; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68c497f3aaefc9fd9f1b0e24.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68c497f3aaefc9fd9f1b0e24.md new file mode 100644 index 0000000000000000000000000000000000000000..dd1234113f546aabc0ca69ef88875e6c871acd89 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68c497f3aaefc9fd9f1b0e24.md @@ -0,0 +1,92 @@ +--- +id: 68c497f3aaefc9fd9f1b0e24 +title: "Challenge 60: Space Week Day 6: Moon Phase" +challengeType: 28 +dashedName: challenge-60 +--- + +# --description-- + +For day six of Space Week, you will be given a date in the format `"YYYY-MM-DD"` and need to determine the phase of the moon for that day using the following rules: + +Use a simplified lunar cycle of 28 days, divided into four equal phases: + +- `"New"`: days 1 - 7 +- `"Waxing"`: days 8 - 14 +- `"Full"`: days 15 - 21 +- `"Waning"`: days 22 - 28 + +After day 28, the cycle repeats with day 1, a new moon. + +- Use `"2000-01-06"` as a reference new moon (day 1 of the cycle) to determine the phase of the given day. +- You will not be given any dates before the reference date. +- Return the correct phase as a string. + +**Note:** Day 1 represents the day of the new moon, meaning 0 days have passed since the last new moon. + +# --hints-- + +`moonPhase("2000-01-12")` should return `"New"`. + +```js +assert.equal(moonPhase("2000-01-12"), "New"); +``` + +`moonPhase("2000-01-13")` should return `"Waxing"`. + +```js +assert.equal(moonPhase("2000-01-13"), "Waxing"); +``` + +`moonPhase("2014-10-15")` should return `"Full"`. + +```js +assert.equal(moonPhase("2014-10-15"), "Full"); +``` + +`moonPhase("2012-10-21")` should return `"Waning"`. + +```js +assert.equal(moonPhase("2012-10-21"), "Waning"); +``` + +`moonPhase("2022-12-14")` should return `"New"`. + +```js +assert.equal(moonPhase("2022-12-14"), "New"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function moonPhase(dateString) { + + return dateString; +} +``` + +# --solutions-- + +```js +function moonPhase(dateString) { + const ONE_DAY_IN_MS = 1000 * 60 * 60 * 24; + const refDate = new Date("2000-01-06"); + const targetDate = new Date(dateString); + const diffMs = targetDate - refDate; + const diffDays = diffMs / ONE_DAY_IN_MS; + const phaseDay = (diffDays % 28 + 1); + + if (phaseDay <= 7) { + return "New"; + } else if (phaseDay <= 14) { + return "Waxing"; + } else if (phaseDay <= 21) { + return "Full" + } else { + return "Waning"; + } +} + +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68c497f3aaefc9fd9f1b0e25.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68c497f3aaefc9fd9f1b0e25.md new file mode 100644 index 0000000000000000000000000000000000000000..3e17a6389ba87170d1ce7235076f94fd9b50c061 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68c497f3aaefc9fd9f1b0e25.md @@ -0,0 +1,80 @@ +--- +id: 68c497f3aaefc9fd9f1b0e25 +title: "Challenge 61: Space Week Day 7: Launch Fuel" +challengeType: 28 +dashedName: challenge-61 +--- + +# --description-- + +For the final day of Space Week, you will be given the mass in kilograms (kg) of a payload you want to send to orbit. Determine the amount of fuel needed to send your payload to orbit using the following rules: + +- Rockets require 1 kg of fuel per 5 kg of mass they must lift. +- Fuel itself has mass. So when you add fuel, the mass to lift goes up, which requires more fuel, which increases the mass, and so on. +- To calculate the total fuel needed: start with the payload mass, calculate the fuel needed for that, add that fuel to the total mass, and calculate again. Repeat this process until the additional fuel required is less than 1 kg, then stop. +- Ignore the mass of the rocket itself. Only compute fuel needed to lift the payload and its own fuel. + +For example, given a payload mass of 50 kg, you would need 10 kg of fuel to lift it (payload / 5), which increases the total mass to 60 kg, which needs 12 kg to lift (2 additional kg), which increases the total mass to 62 kg, which needs 12.4 kg to lift - 0.4 additional kg - which is less 1 additional kg, so we stop here. The total mass to lift is 62.4 kg, 50 of which is the initial payload and 12.4 of fuel. + +- Return the amount of fuel needed rounded to one decimal place. + +# --hints-- + +`launchFuel(50)` should return `12.4`. + +```js +assert.equal(launchFuel(50), 12.4); +``` + +`launchFuel(500)` should return `124.8`. + +```js +assert.equal(launchFuel(500), 124.8); +``` + +`launchFuel(243)` should return `60.7`. + +```js +assert.equal(launchFuel(243), 60.7); +``` + +`launchFuel(11000)` should return `2749.8`. + +```js +assert.equal(launchFuel(11000), 2749.8); +``` + +`launchFuel(6214)` should return `1553.4`. + +```js +assert.equal(launchFuel(6214), 1553.4); +``` + +# --seed-- + +## --seed-contents-- + +```js +function launchFuel(payload) { + + return payload; +} +``` + +# --solutions-- + +```js +function launchFuel(payload) { + let totalMass = payload; + let additionalFuel = totalMass / 5; + let totalFuel = additionalFuel; + + while (additionalFuel >= 1) { + totalMass += additionalFuel; + additionalFuel = (totalMass / 5) - totalFuel; + totalFuel += additionalFuel; + } + + return Number(totalFuel.toFixed(1)); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68c497f3aaefc9fd9f1b0e26.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68c497f3aaefc9fd9f1b0e26.md new file mode 100644 index 0000000000000000000000000000000000000000..f1f74a635d74ea214aa4e5413904973eacae5ba8 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68c497f3aaefc9fd9f1b0e26.md @@ -0,0 +1,88 @@ +--- +id: 68c497f3aaefc9fd9f1b0e26 +title: "Challenge 62: Hex to Decimal" +challengeType: 28 +dashedName: challenge-62 +--- + +# --description-- + +Given a string representing a hexadecimal number (base 16), return its decimal (base 10) value as an integer. + +Hexadecimal is a number system that uses 16 digits: + +- `0-9` represent values `0` through `9`. +- `A-F` represent values `10` through `15`. + +Here's a partial conversion table: + +| Hexadecimal | Decimal | +|:-----------:|:-------:| +| 0 | 0 | +| 1 | 1 | +| ... | ... | +| 9 | 9 | +| A | 10 | +| ... | ... | +| F | 15 | +| 10 | 16 | +| ... | ... | +| 9F | 159 | +| A0 | 160 | +| ... | ... | +| FF | 255 | +| 100 | 256 | + +- The string will only contain characters `0–9` and `A–F`. + +# --hints-- + +`hexToDecimal("A")` should return `10`. + +```js +assert.equal(hexToDecimal("A"), 10); +``` + +`hexToDecimal("15")` should return `21`. + +```js +assert.equal(hexToDecimal("15"), 21); +``` + +`hexToDecimal("2E")` should return `46`. + +```js +assert.equal(hexToDecimal("2E"), 46); +``` + +`hexToDecimal("FF")` should return `255`. + +```js +assert.equal(hexToDecimal("FF"), 255); +``` + +`hexToDecimal("A3F")` should return `2623`. + +```js +assert.equal(hexToDecimal("A3F"), 2623); +``` + +# --seed-- + +## --seed-contents-- + +```js +function hexToDecimal(hex) { + + return hex; +} +``` + +# --solutions-- + +```js +function hexToDecimal(hex) { + + return parseInt(hex, 16); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da001.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da001.md new file mode 100644 index 0000000000000000000000000000000000000000..68725157d99219dca640f4468f708c5f12ab36d7 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da001.md @@ -0,0 +1,113 @@ +--- +id: 68cae5b538ff798bbd4da001 +title: "Challenge 63: Battle of Words" +challengeType: 28 +dashedName: challenge-63 +--- + +# --description-- + +Given two sentences representing your team and an opposing team, where each word from your team battles the corresponding word from the opposing team, determine which team wins using the following rules: + +- The given sentences will always contain the same number of words. +- Words are separated by a single space and will only contain letters. +- The value of each word is the sum of its letters. +- Letters `a` to `z` correspond to the values `1` through `26`. For example, `a` is `1`, and `z` is `26`. +- A capital letter doubles the value of the letter. For example, `A` is `2`, and `Z` is `52`. +- Words battle in order: the first word of your team battles the first word of the opposing team, and so on. +- A word wins if its value is greater than the opposing word's value. +- The team with more winning words is the winner. + +Return `"We win"` if your team is the winner, `"We lose"` if your team loses, and `"Draw"` if both teams have the same number of wins. + +# --hints-- + +`battle("hello world", "hello word")` should return `"We win"`. + +```js +assert.equal(battle("hello world", "hello word"), "We win"); +``` + +`battle("Hello world", "hello world")` should return `"We win"`. + +```js +assert.equal(battle("Hello world", "hello world"), "We win"); +``` + +`battle("lorem ipsum", "kitty ipsum")` should return `"We lose"`. + +```js +assert.equal(battle("lorem ipsum", "kitty ipsum"), "We lose"); +``` + +`battle("hello world", "world hello")` should return `"Draw"`. + +```js +assert.equal(battle("hello world", "world hello"), "Draw"); +``` + +`battle("git checkout", "git switch")` should return `"We win"`. + +```js +assert.equal(battle("git checkout", "git switch"), "We win"); +``` + +`battle("Cheeseburger with fries", "Cheeseburger with Fries")` should return `"We lose"`. + +```js +assert.equal(battle("Cheeseburger with fries", "Cheeseburger with Fries"), "We lose"); +``` + +`battle("We must never surrender", "Our team must win")` should return `"Draw"`. + +```js +assert.equal(battle("We must never surrender", "Our team must win"), "Draw"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function battle(ourTeam, opponent) { + + return ourTeam; +} +``` + +# --solutions-- + +```js +function getCharacterValue(char) { + const lowerCaseValue = char.toLowerCase().charCodeAt(0) - 96; + return char >= 'A' && char <= 'Z' ? lowerCaseValue * 2 : lowerCaseValue; +} + +function getWordValue(word) { + let wordValue = 0; + for (let i=0; i opponentWordValue) myWins++; + if (opponentWordValue > myWordValue) opponentWins++; + } + + if (myWins > opponentWins) return 'We win'; + if (opponentWins > myWins) return 'We lose'; + return 'Draw'; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da002.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da002.md new file mode 100644 index 0000000000000000000000000000000000000000..c94466b1ce2a569250cab8aa168a18283619c9e7 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da002.md @@ -0,0 +1,73 @@ +--- +id: 68cae5b538ff798bbd4da002 +title: "Challenge 64: 24 to 12" +challengeType: 28 +dashedName: challenge-64 +--- + +# --description-- + +Given a string representing a time of the day in the 24-hour format of `"HHMM"`, return the time in its equivalent 12-hour format of `"H:MM AM"` or `"H:MM PM"`. + +- The given input will always be a four-digit string in 24-hour time format, from `"0000"` to `"2359"`. + +# --hints-- + +`to12("1124")` should return `"11:24 AM"`. + +```js +assert.equal(to12("1124"), "11:24 AM"); +``` + +`to12("0900")` should return `"9:00 AM"`. + +```js +assert.equal(to12("0900"), "9:00 AM"); +``` + +`to12("1455")` should return `"2:55 PM"`. + +```js +assert.equal(to12("1455"), "2:55 PM"); +``` + +`to12("2346")` should return `"11:46 PM"`. + +```js +assert.equal(to12("2346"), "11:46 PM"); +``` + +`to12("0030")` should return `"12:30 AM"`. + +```js +assert.equal(to12("0030"), "12:30 AM"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function to12(time) { + + return time; +} +``` + +# --solutions-- + +```js +function convertHours(hours) { + if (hours === 0) return 12; + if (hours > 12) return hours - 12; + return hours; +} + +function to12(time) { + const hours = parseInt(time.slice(0, 2), 10); + const minutes = time.slice(2); + const period = hours < 12 ? 'AM' : 'PM'; + + return `${convertHours(hours)}:${minutes} ${period}`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da003.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da003.md new file mode 100644 index 0000000000000000000000000000000000000000..5ecbf3d67f34103dca84c1267aca8d952d5a11e2 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da003.md @@ -0,0 +1,71 @@ +--- +id: 68cae5b538ff798bbd4da003 +title: "Challenge 65: String Count" +challengeType: 28 +dashedName: challenge-65 +--- + +# --description-- + +Given two strings, determine how many times the second string appears in the first. + +- The pattern string can overlap in the first string. For example, `"aaa"` contains `"aa"` twice. The first two `a`'s and the second two. + +# --hints-- + +`count('abcdefg', 'def')` should return `1`. + +```js +assert.equal(count('abcdefg', 'def'), 1); +``` + +`count('hello', 'world')` should return `0`. + +```js +assert.equal(count('hello', 'world'), 0); +``` + +`count('mississippi', 'iss')` should return `2`. + +```js +assert.equal(count('mississippi', 'iss'), 2); +``` + +`count('she sells seashells by the seashore', 'sh')` should return `3`. + +```js +assert.equal(count('she sells seashells by the seashore', 'sh'), 3); +``` + +`count('101010101010101010101', '101')` should return `10`. + +```js +assert.equal(count('101010101010101010101', '101'), 10); +``` + +# --seed-- + +## --seed-contents-- + +```js +function count(text, pattern) { + + return text; +} +``` + +# --solutions-- + +```js +function count(text, pattern) { + let occurrences = 0; + + for (let i = 0; i <= text.length - pattern.length; i++) { + if (text.slice(i, i + pattern.length) === pattern) { + occurrences++; + } + } + + return occurrences; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da004.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da004.md new file mode 100644 index 0000000000000000000000000000000000000000..5314868f5531c8f3eeae92be91e71f09bbdfd43e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da004.md @@ -0,0 +1,61 @@ +--- +id: 68cae5b538ff798bbd4da004 +title: "Challenge 66: HTML Tag Stripper" +challengeType: 28 +dashedName: challenge-66 +--- + +# --description-- + +Given a string of HTML code, remove the tags and return the plain text content. + +- The input string will contain only valid HTML. +- HTML tags may be nested. +- Remove the tags and any attributes. + +For example, `'Click here'` should return `"Click here"`. + +# --hints-- + +`stripTags('Click here')` should return `"Click here"`. + +```js +assert.equal(stripTags('Click here'), "Click here"); +``` + +`stripTags('

Hello World!

')` should return `"Hello World!"`. + +```js +assert.equal(stripTags('

Hello World!

'), "Hello World!"); +``` + +`stripTags('Cat')` should return an empty string (`""`). + +```js +assert.equal(stripTags('Cat'), ""); +``` + +`stripTags('
section
section
')` should return `sectionsection`. + +```js +assert.equal(stripTags('
section
section
'), "sectionsection"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function stripTags(html) { + + return html; +} +``` + +# --solutions-- + +```js +function stripTags(html) { + return html.replace(/<[^>]*>/g, ''); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da005.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da005.md new file mode 100644 index 0000000000000000000000000000000000000000..2a2edbd356211edb9efaec49db7da07d2431fc3b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da005.md @@ -0,0 +1,114 @@ +--- +id: 68cae5b538ff798bbd4da005 +title: "Challenge 67: Email Validator" +challengeType: 28 +dashedName: challenge-67 +--- + +# --description-- + +Given a string, determine if it is a valid email address using the following constraints: + +- It must contain exactly one `@` symbol. +- The local part (before the `@`): + - Can only contain letters (`a-z`, `A-Z`), digits (`0-9`), dots (`.`), underscores (`_`), or hyphens (`-`). + - Cannot start or end with a dot. +- The domain part (after the `@`): + - Must contain at least one dot. + - Must end with a dot followed by at least two letters. +- Neither the local or domain part can have two dots in a row. + +# --hints-- + +`validate("a@b.cd")` should return `true`. + +```js +assert.isTrue(validate("a@b.cd")); +``` + +`validate("hell.-w.rld@example.com")` should return `true`. + +```js +assert.isTrue(validate("hell.-w.rld@example.com")); +``` + +`validate(".b@sh.rc")` should return `false`. + +```js +assert.isFalse(validate(".b@sh.rc")); +``` + +`validate("example@test.c0")` should return `false`. + +```js +assert.isFalse(validate("example@test.c0")); +``` + +`validate("freecodecamp.org")` should return `false`. + +```js +assert.isFalse(validate("freecodecamp.org")); +``` + +`validate("develop.ment_user@c0D!NG.R.CKS")` should return `true`. + +```js +assert.isTrue(validate("develop.ment_user@c0D!NG.R.CKS")); +``` + +`validate("hello.@wo.rld")` should return `false`. + +```js +assert.isFalse(validate("hello.@wo.rld")); +``` + +`validate("hello@world..com")` should return `false`. + +```js +assert.isFalse(validate("hello@world..com")); +``` + +`validate("develop..ment_user@c0D!NG.R.CKS")` should return `false`. + +```js +assert.isFalse(validate("develop..ment_user@c0D!NG.R.CKS")); +``` + +`validate("git@commit@push.io")` should return `false`. + +```js +assert.isFalse(validate("git@commit@push.io")); +``` + +# --seed-- + +## --seed-contents-- + +```js +function validate(email) { + + return email; +} +``` + +# --solutions-- + +```js +function validate(email) { + if (email.includes('..')) return false; + + const parts = email.split('@'); + if (parts.length !== 2) return false; + + const [local, domain] = parts; + + if (local.startsWith('.') || local.endsWith('.')) return false; + if (!/^[a-zA-Z0-9._-]+$/.test(local)) return false; + if (!domain.includes('.')) return false; + + const tld = domain.split('.').pop(); + if (tld.length < 2 || !/^[a-zA-Z]+$/.test(tld)) return false; + + return true; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da006.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da006.md new file mode 100644 index 0000000000000000000000000000000000000000..da235c014175ef26b56d9e16976b6e2b73dea152 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da006.md @@ -0,0 +1,65 @@ +--- +id: 68cae5b538ff798bbd4da006 +title: "Challenge 68: Credit Card Masker" +challengeType: 28 +dashedName: challenge-68 +--- + +# --description-- + +Given a string of credit card numbers, return a masked version of it using the following constraints: + +- The string will contain four sets of four digits (`0-9`), with all sets being separated by a single space, or a single hyphen (`-`). +- Replace all numbers, except the last four, with an asterisk (`*`). +- Leave the remaining characters unchanged. + +For example, given `"4012-8888-8888-1881"` return `"****-****-****-1881"`. + +# --hints-- + +`mask("4012-8888-8888-1881")` should return `"****-****-****-1881"`. + +```js +assert.equal(mask("4012-8888-8888-1881"), "****-****-****-1881"); +``` + +`mask("5105 1051 0510 5100")` should return `"**** **** **** 5100"`. + +```js +assert.equal(mask("5105 1051 0510 5100"), "**** **** **** 5100"); +``` + +`mask("6011 1111 1111 1117")` should return `"**** **** **** 1117"`. + +```js +assert.equal(mask("6011 1111 1111 1117"), "**** **** **** 1117"); +``` + +`mask("2223-0000-4845-0010")` should return `"****-****-****-0010"`. + +```js +assert.equal(mask("2223-0000-4845-0010"), "****-****-****-0010"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function mask(card) { + + return card; +} +``` + +# --solutions-- + +```js +function mask(card) { + const split = card.split(card.includes('-') ? '-' : ' '); + + return card.includes('-') ? + `****-****-****-${split[3]}` : + `**** **** **** ${split[3]}`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da007.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da007.md new file mode 100644 index 0000000000000000000000000000000000000000..1c77aec28377691a8f341b437190655529a2bad2 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da007.md @@ -0,0 +1,80 @@ +--- +id: 68cae5b538ff798bbd4da007 +title: "Challenge 69: Missing Socks" +challengeType: 28 +dashedName: challenge-69 +--- + +# --description-- + +Given an integer representing the number of pairs of socks you started with, and another integer representing how many wash cycles you have gone through, return the number of complete pairs of socks you currently have using the following constraints: + +- Every 2 wash cycles, you lose a single sock. +- Every 3 wash cycles, you find a single missing sock. +- Every 5 wash cycles, a single sock is worn out and must be thrown away. +- Every 10 wash cycles, you buy a pair of socks. +- You can never have less than zero total socks. +- Rules can overlap. For example, on wash cycle 10, you will lose a single sock, throw away a single sock, and buy a new pair of socks. +- Return the number of complete pairs of socks. + +# --hints-- + +`sockPairs(2, 5)` should return `1`. + +```js +assert.equal(sockPairs(2, 5), 1); +``` + +`sockPairs(1, 2)` should return `0`. + +```js +assert.equal(sockPairs(1, 2), 0); +``` + +`sockPairs(5, 11)` should return `4`. + +```js +assert.equal(sockPairs(5, 11), 4); +``` + +`sockPairs(6, 25)` should return `3`. + +```js +assert.equal(sockPairs(6, 25), 3); +``` + +`sockPairs(1, 8)` should return `0`. + +```js +assert.equal(sockPairs(1, 8), 0); +``` + +# --seed-- + +## --seed-contents-- + +```js +function sockPairs(pairs, cycles) { + + return pairs; +} +``` + +# --solutions-- + +```js +function sockPairs(pairs, cycles) { + let socks = pairs * 2; + + for (let i = 1; i <= cycles; i++) { + if (i % 2 === 0) socks -= 1; + if (i % 3 === 0) socks += 1; + if (i % 5 === 0) socks -= 1; + if (i % 10 === 0) socks += 2; + + if (socks < 0) socks = 0; + } + + return Math.floor(socks / 2); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da008.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da008.md new file mode 100644 index 0000000000000000000000000000000000000000..e6d3c83a7f6105c9dd359b50b7b4293ae5753750 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da008.md @@ -0,0 +1,77 @@ +--- +id: 68cae5b538ff798bbd4da008 +title: "Challenge 70: HTML Attribute Extractor" +challengeType: 28 +dashedName: challenge-70 +--- + +# --description-- + +Given a string of a valid HTML element, return the attributes of the element using the following criteria: + +- You will only be given one element. +- Attributes will be in the format: `attribute="value"`. +- Return an array of strings with each attribute property and value, separated by a comma, in this format: `["attribute1, value1", "attribute2, value2"]`. +- Return attributes in the order they are given. +- If no attributes are found, return an empty array. + +# --hints-- + +`extractAttributes('')` should return `["class, red"]`. + +```js +assert.deepEqual(extractAttributes(''), ["class, red"]); +``` + +`extractAttributes('')` should return `["charset, UTF-8"]`. + +```js +assert.deepEqual(extractAttributes(''), ["charset, UTF-8"]); +``` + +`extractAttributes("

Lorem ipsum dolor sit amet

")` should return `[]`. + +```js +assert.deepEqual(extractAttributes("

Lorem ipsum dolor sit amet

"), []); +``` + +`extractAttributes('')` should return `["name, email", "type, email", "required, true"]`. + +```js +assert.deepEqual(extractAttributes(''), ["name, email", "type, email", "required, true"]); +``` + +`extractAttributes('')` should return `["id, submit", "class, btn btn-primary"]`. + +```js +assert.deepEqual(extractAttributes(''), ["id, submit", "class, btn btn-primary"]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function extractAttributes(element) { + + return element; +} +``` + +# --solutions-- + +```js +function extractAttributes(element) { + const regex = /(\w[\w-]*)="([^"]*)"/g; + const result = []; + let match; + + while ((match = regex.exec(element)) !== null) { + const attr = match[1]; + const val = match[2]; + result.push(`${attr}, ${val}`); + } + + return result; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da009.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da009.md new file mode 100644 index 0000000000000000000000000000000000000000..ea38ce65b7e6a6ac68cf35dad2c439ba40c6c467 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da009.md @@ -0,0 +1,62 @@ +--- +id: 68cae5b538ff798bbd4da009 +title: "Challenge 71: Tip Calculator" +challengeType: 28 +dashedName: challenge-71 +--- + +# --description-- + +Given the price of your meal and a custom tip percent, return an array with three tip values; 15%, 20%, and the custom amount. + +- Prices will be given in the format: `"$N.NN"`. +- Custom tip percents will be given in this format: `"25%"`. +- Return amounts in the same `"$N.NN"` format, rounded to two decimal places. + +For example, given a `"$10.00"` meal price, and a `"25%"` custom tip value, return `["$1.50", "$2.00", "$2.50"]`. + +# --hints-- + +`calculateTips("$10.00", "25%")` should return `["$1.50", "$2.00", "$2.50"]`. + +```js +assert.deepEqual(calculateTips("$10.00", "25%"), ["$1.50", "$2.00", "$2.50"]); +``` + +`calculateTips("$89.67", "26%")` should return `["$13.45", "$17.93", "$23.31"]`. + +```js +assert.deepEqual(calculateTips("$89.67", "26%"), ["$13.45", "$17.93", "$23.31"]); +``` + +`calculateTips("$19.85", "9%")` should return `["$2.98", "$3.97", "$1.79"]`. + +```js +assert.deepEqual(calculateTips("$19.85", "9%"), ["$2.98", "$3.97", "$1.79"]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function calculateTips(mealPrice, customTip) { + + return mealPrice; +} +``` + +# --solutions-- + +```js +function calculateTips(mealPrice, customTip) { + const meal = parseFloat(mealPrice.slice(1)); + const customPercent = parseFloat(customTip.slice(0, -1)); + const tips = [15, 20, customPercent]; + + return tips.map(percent => { + const amount = (meal * percent / 100).toFixed(2); + return `$${amount}`; + }); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da00a.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da00a.md new file mode 100644 index 0000000000000000000000000000000000000000..b1d3b8aa00c1e0856e865e58c8097dd0eff374c3 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68cae5b538ff798bbd4da00a.md @@ -0,0 +1,76 @@ +--- +id: 68cae5b538ff798bbd4da00a +title: "Challenge 72: Thermostat Adjuster 2" +challengeType: 28 +dashedName: challenge-72 +--- + +# --description-- + +Given the current temperature of a room in Fahrenheit and a target temperature in Celsius, return a string indicating how to adjust the room temperature based on these constraints: + +- Return `"Heat: X degrees Fahrenheit"` if the current temperature is below the target. With `X` being the number of degrees in Fahrenheit to heat the room to reach the target, rounded to 1 decimal place. +- Return `"Cool: X degrees Fahrenheit"` if the current temperature is above the target. With `X` being the number of degrees in Fahrenheit to cool the room to reach the target, rounded to 1 decimal place. +- Return `"Hold"` if the current temperature is equal to the target. + +To convert Celsius to Fahrenheit, multiply the Celsius temperature by 1.8 and add 32 to the result (`F = (C * 1.8) + 32`). + +# --hints-- + +`adjustThermostat(32, 0)` should return `"Hold"`. + +```js +assert.equal(adjustThermostat(32, 0), "Hold"); +``` + +`adjustThermostat(70, 25)` should return `"Heat: 7.0 degrees Fahrenheit"`. + +```js +assert.equal(adjustThermostat(70, 25), "Heat: 7.0 degrees Fahrenheit"); +``` + +`adjustThermostat(72, 18)` should return `"Cool: 7.6 degrees Fahrenheit"`. + +```js +assert.equal(adjustThermostat(72, 18), "Cool: 7.6 degrees Fahrenheit"); +``` + +`adjustThermostat(212, 100)` should return `"Hold"`. + +```js +assert.equal(adjustThermostat(212, 100), "Hold"); +``` + +`adjustThermostat(59, 22)` should return `"Heat: 12.6 degrees Fahrenheit"`. + +```js +assert.equal(adjustThermostat(59, 22), "Heat: 12.6 degrees Fahrenheit"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function adjustThermostat(currentF, targetC) { + + return currentF; +} +``` + +# --solutions-- + +```js +function adjustThermostat(currentF, targetC) { + const targetF = targetC * 1.8 + 32; + const diff = Math.abs(targetF - currentF).toFixed(1); + + if (currentF < targetF) { + return `Heat: ${diff} degrees Fahrenheit`; + } else if (currentF > targetF) { + return `Cool: ${diff} degrees Fahrenheit`; + } else { + return "Hold" + } +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68d2ba1468508398389487ce.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68d2ba1468508398389487ce.md new file mode 100644 index 0000000000000000000000000000000000000000..abf19ea9b55dca597341032f77083b9d120ec81d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68d2ba1468508398389487ce.md @@ -0,0 +1,87 @@ +--- +id: 68d2ba1468508398389487ce +title: "Challenge 73: Speak Wisely, You Must" +challengeType: 28 +dashedName: challenge-73 +--- + +# --description-- + +Given a sentence, return a version of it that sounds like advice from a wise teacher using the following rules: + +- Words are separated by a single space. +- Find the first occurrence of one of the following words in the sentence: `"have"`, `"must"`, `"are"`, `"will"`, `"can"`. +- Move all words before and including that word to the end of the sentence and: + - Preserve the order of the words when you move them. + - Make them all lowercase. + - And add a comma and space before them. +- Capitalize the first letter of the new first word of the sentence. +- All given sentences will end with a single punctuation mark. Keep the original punctuation of the sentence and move it to the end of the new sentence. +- Return the new sentence, make sure there's a single space between each word and no spaces at the beginning or end of the sentence. + +For example, given `"You must speak wisely."` return `"Speak wisely, you must."` + +# --hints-- + +`wiseSpeak("You must speak wisely.")` should return `"Speak wisely, you must."` + +```js +assert.equal(wiseSpeak("You must speak wisely."), "Speak wisely, you must."); +``` + +`wiseSpeak("You can do it!")` should return `"Do it, you can!"` + +```js +assert.equal(wiseSpeak("You can do it!"), "Do it, you can!"); +``` + +`wiseSpeak("Do you think you will complete this?")` should return `"Complete this, do you think you will?"` + +```js +assert.equal(wiseSpeak("Do you think you will complete this?"), "Complete this, do you think you will?"); +``` + +`wiseSpeak("All your base are belong to us.")` should return `"Belong to us, all your base are."` + +```js +assert.equal(wiseSpeak("All your base are belong to us."), "Belong to us, all your base are."); +``` + +`wiseSpeak("You have much to learn.")` should return `"Much to learn, you have."` + +```js +assert.equal(wiseSpeak("You have much to learn."), "Much to learn, you have."); +``` + +# --seed-- + +## --seed-contents-- + +```js +function wiseSpeak(sentence) { + + return sentence; +} +``` + +# --solutions-- + +```js +function wiseSpeak(sentence) { + const triggers = ["have", "must", "are", "will", "can"]; + const punctuation = sentence[sentence.length - 1]; + const words = sentence.split(" "); + + const triggerIndex = words.findIndex(w => triggers.includes(w)); + + const toMove = words.slice(0, triggerIndex + 1).map(w => w.toLowerCase()); + const remaining = words.slice(triggerIndex + 1); + + const newStart = remaining.map((w, i) => { + return i === 0 ? w[0].toUpperCase() + w.slice(1) : + i === remaining.length - 1 ? w.slice(0, w.length - 1) : w; + }) + + return newStart.join(" ") + ", " + toMove.join(" ") + punctuation; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68d2ba1468508398389487cf.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68d2ba1468508398389487cf.md new file mode 100644 index 0000000000000000000000000000000000000000..df5b23882c12ff7bad090de9998e642bc27b7b23 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68d2ba1468508398389487cf.md @@ -0,0 +1,54 @@ +--- +id: 68d2ba1468508398389487cf +title: "Challenge 74: Favorite Songs" +challengeType: 28 +dashedName: challenge-74 +--- + +# --description-- + +Remember iPods? The first model came out 24 years ago today, on Oct. 23, 2001. + +Given an array of song objects representing your iPod playlist, return an array with the titles of the two most played songs, with the most played song first. + +- Each object will have a `"title"` property (string), and a `"plays"` property (integer). + +# --hints-- + +`favoriteSongs([{"title": "Sync or Swim", "plays": 3}, {"title": "Byte Me", "plays": 1}, {"title": "Earbud Blues", "plays": 2} ])` should return `["Sync or Swim", "Earbud Blues"]`. + +```js +assert.deepEqual(favoriteSongs([{"title": "Sync or Swim", "plays": 3}, {"title": "Byte Me", "plays": 1}, {"title": "Earbud Blues", "plays": 2} ]), ["Sync or Swim", "Earbud Blues"]); +``` + +`favoriteSongs([{"title": "Skip Track", "plays": 98}, {"title": "99 Downloads", "plays": 99}, {"title": "Clickwheel Love", "plays": 100} ])` should return `["Clickwheel Love", "99 Downloads"]`. + +```js +assert.deepEqual(favoriteSongs([{"title": "Skip Track", "plays": 98}, {"title": "99 Downloads", "plays": 99}, {"title": "Clickwheel Love", "plays": 100} ]), ["Clickwheel Love", "99 Downloads"]); +``` + +`favoriteSongs([{"title": "Song A", "plays": 42}, {"title": "Song B", "plays": 99}, {"title": "Song C", "plays": 75} ])` should return `["Song B", "Song C"]`. + +```js +assert.deepEqual(favoriteSongs([{"title": "Song A", "plays": 42}, {"title": "Song B", "plays": 99}, {"title": "Song C", "plays": 75} ]), ["Song B", "Song C"]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function favoriteSongs(playlist) { + + return playlist; +} +``` + +# --solutions-- + +```js +function favoriteSongs(playlist) { + const sorted = [...playlist].sort((a, b) => b.plays - a.plays); + return sorted.slice(0, 2).map(song => song.title); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68d2ba1468508398389487d0.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68d2ba1468508398389487d0.md new file mode 100644 index 0000000000000000000000000000000000000000..8ec869f3f46981244d9fc49588ae16c0d6864999 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68d2ba1468508398389487d0.md @@ -0,0 +1,107 @@ +--- +id: 68d2ba1468508398389487d0 +title: "Challenge 75: Hidden Treasure" +challengeType: 28 +dashedName: challenge-75 +--- + +# --description-- + +Given a 2D array representing a map of the ocean floor that includes a hidden treasure, and an array with the coordinates (`[row, column]`) for the next dive of your treasure search, return `"Empty"`, `"Found"`, or `"Recovered"` using the following rules: + +- The given 2D array will contain exactly one unrecovered treasure, which will occupy multiple cells. +- Each cell in the 2D array will contain one of the following values: + - `"-"`: No treasure. + - `"O"`: A part of the treasure that has not been found. + - `"X"`: A part of the treasure that has already been found. + +- If the dive location has no treasure, return `"Empty"`. +- If the dive location finds treasure, but at least one other part of the treasure remains unfound, return `"Found"`. +- If the dive location finds the last unfound part of the treasure, return `"Recovered"`. + +For example, given: + +```json +[ + [ "-", "X"], + [ "-", "X"], + [ "-", "O"] +] +``` + +And `[2, 1]` for the coordinates of the dive location, return `"Recovered"` because the dive found the last unfound part of the treasure. + +# --hints-- + +`dive([[ "-", "X"], [ "-", "X"], [ "-", "O"]], [2, 1])` should return `"Recovered"`. + +```js +assert.equal(dive([[ "-", "X"], [ "-", "X"], [ "-", "O"]], [2, 1]), "Recovered"); +``` + +`dive([[ "-", "X"], [ "-", "X"], [ "-", "O"]], [2, 0])` should return `"Empty"`. + +```js +assert.equal(dive([[ "-", "X"], [ "-", "X"], [ "-", "O"]], [2, 0]), "Empty"); +``` + +`dive([[ "-", "X"], [ "-", "O"], [ "-", "O"]], [1, 1])` should return `"Found"`. + +```js +assert.equal(dive([[ "-", "X"], [ "-", "O"], [ "-", "O"]], [1, 1]), "Found"); +``` + +`dive([[ "-", "-", "-"], [ "X", "O", "X"], [ "-", "-", "-"]], [1, 2])` should return `"Found"`. + +```js +assert.equal(dive([[ "-", "-", "-"], [ "X", "O", "X"], [ "-", "-", "-"]], [1, 2]), "Found"); +``` + +`dive([[ "-", "-", "-"], [ "-", "-", "-"], [ "O", "X", "X"]], [2, 0])` should return `"Recovered"`. + +```js +assert.equal(dive([[ "-", "-", "-"], [ "-", "-", "-"], [ "O", "X", "X"]], [2, 0]), "Recovered"); +``` + +`dive([[ "-", "-", "-"], [ "-", "-", "-"], [ "O", "X", "X"]], [1, 2])` should return `"Empty"`. + +```js +assert.equal(dive([[ "-", "-", "-"], [ "-", "-", "-"], [ "O", "X", "X"]], [1, 2]), "Empty"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function dive(map, coordinates) { + + return map; +} +``` + +# --solutions-- + +```js +function dive(map, coordinates) { + const [row, col] = coordinates; + const target = map[row][col]; + + if (target === "-") { + return "Empty"; + } + + if (target === "O") { + for (let r = 0; r < map.length; r++) { + for (let c = 0; c < map[r].length; c++) { + if ((r !== row || c !== col) && map[r][c] === "O") { + return "Found"; + } + } + } + return "Recovered"; + } + + return "Found"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68d30845cc08266018fc46bc.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68d30845cc08266018fc46bc.md new file mode 100644 index 0000000000000000000000000000000000000000..5b06c823fe38db08d8216a6f1ce81ba42331ee12 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68d30845cc08266018fc46bc.md @@ -0,0 +1,65 @@ +--- +id: 68d30845cc08266018fc46bc +title: "Challenge 76: Complementary DNA" +challengeType: 28 +dashedName: challenge-76 +--- + +# --description-- + +Given a string representing a DNA sequence, return its complementary strand using the following rules: + +- DNA consists of the letters `"A"`, `"C"`, `"G"`, and `"T"`. +- The letters `"A"` and `"T"` complement each other. +- The letters `"C"` and `"G"` complement each other. + +For example, given `"ACGT"`, return `"TGCA"`. + +# --hints-- + +`complementaryDNA("ACGT")` should return `"TGCA"`. + +```js +assert.equal(complementaryDNA("ACGT"), "TGCA"); +``` + +`complementaryDNA("ATGCGTACGTTAGC")` should return `"TACGCATGCAATCG"`. + +```js +assert.equal(complementaryDNA("ATGCGTACGTTAGC"), "TACGCATGCAATCG"); +``` + +`complementaryDNA("GGCTTACGATCGAAG")` should return `"CCGAATGCTAGCTTC"`. + +```js +assert.equal(complementaryDNA("GGCTTACGATCGAAG"), "CCGAATGCTAGCTTC"); +``` + +`complementaryDNA("GATCTAGCTAGGCTAGCTAG")` should return `"CTAGATCGATCCGATCGATC"`. + +```js +assert.equal(complementaryDNA("GATCTAGCTAGGCTAGCTAG"), "CTAGATCGATCCGATCGATC"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function complementaryDNA(strand) { + + return strand; +} +``` + +# --solutions-- + +```js +function complementaryDNA(strand) { + const complements = { A: "T", T: "A", C: "G", G: "C" }; + return strand + .split("") + .map(c => complements[c]) + .join(""); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68d30845cc08266018fc46bd.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68d30845cc08266018fc46bd.md new file mode 100644 index 0000000000000000000000000000000000000000..42dff80b37171ad860994efd91c5269e93a88660 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68d30845cc08266018fc46bd.md @@ -0,0 +1,77 @@ +--- +id: 68d30845cc08266018fc46bd +title: "Challenge 77: Duration Formatter" +challengeType: 28 +dashedName: challenge-77 +--- + +# --description-- + +Given an integer number of seconds, return a string representing the same duration in the format `"H:MM:SS"`, where `"H"` is the number of hours, `"MM"` is the number of minutes, and `"SS"` is the number of seconds. Return the time using the following rules: + +- Seconds: Should always be two digits. +- Minutes: Should omit leading zeros when they aren't needed. Use `"0"` if the duration is less than one minute. +- Hours: Should be included only if they're greater than zero. + +# --hints-- + +`format(500)` should return `"8:20"`. + +```js +assert.equal(format(500), "8:20"); +``` + +`format(4000)` should return `"1:06:40"`. + +```js +assert.equal(format(4000), "1:06:40"); +``` + +`format(1)` should return `"0:01"`. + +```js +assert.equal(format(1), "0:01"); +``` + +`format(5555)` should return `"1:32:35"`. + +```js +assert.equal(format(5555), "1:32:35"); +``` + +`format(99999)` should return `"27:46:39"`. + +```js +assert.equal(format(99999), "27:46:39"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function format(seconds) { + + return seconds; +} +``` + +# --solutions-- + +```js +function format(seconds) { + const h = Math.floor(seconds / 3600); + const m = Math.floor((seconds % 3600) / 60); + const s = seconds % 60; + + const secondsStr = s.toString().padStart(2, "0"); + const minutesStr = m.toString(); + + if (h > 0) { + const hoursStr = h.toString(); + return `${hoursStr}:${minutesStr.padStart(2, "0")}:${secondsStr}`; + } else { + return `${minutesStr}:${secondsStr}`; + } +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68d30845cc08266018fc46be.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68d30845cc08266018fc46be.md new file mode 100644 index 0000000000000000000000000000000000000000..b0e9bd9844adf9dd17f88521807abf375daf7a01 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68d30845cc08266018fc46be.md @@ -0,0 +1,61 @@ +--- +id: 68d30845cc08266018fc46be +title: "Challenge 78: Integer Sequence" +challengeType: 28 +dashedName: challenge-78 +--- + +# --description-- + +Given a positive integer, return a string with all of the integers from `1` up to, and including, the given number, in numerical order. + +For example, given `5`, return `"12345"`. + +# --hints-- + +`sequence(5)` should return `"12345"`. + +```js +assert.equal(sequence(5), "12345"); +``` + +`sequence(10)` should return `"12345678910"`. + +```js +assert.equal(sequence(10), "12345678910"); +``` + +`sequence(1)` should return `"1"`. + +```js +assert.strictEqual(sequence(1), "1"); +``` + +`sequence(27)` should return `"123456789101112131415161718192021222324252627"`. + +```js +assert.equal(sequence(27), "123456789101112131415161718192021222324252627"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function sequence(n) { + + return n; +} +``` + +# --solutions-- + +```js +function sequence(n) { + let result = ""; + for (let i = 1; i <= n; i++) { + result += i; + } + return result; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68d30fc57588d97fd3027b30.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68d30fc57588d97fd3027b30.md new file mode 100644 index 0000000000000000000000000000000000000000..62bdae70f3fb5284a56d93668611f4c491b29154 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68d30fc57588d97fd3027b30.md @@ -0,0 +1,98 @@ +--- +id: 68d30fc57588d97fd3027b30 +title: "Challenge 79: Navigator" +challengeType: 28 +dashedName: challenge-79 +--- + +# --description-- + +On October 28, 1994, Netscape Navigator was released, helping millions explore the early web. + +Given an array of browser commands you executed on Netscape Navigator, return the current page you are on after executing all the commands using the following rules: + +- You always start on the `"Home"` page, which will not be included in the commands array. +- Valid commands are: + - `"Visit Page"`: Where `"Page"` is the name of the page you are visiting. For example, `"Visit About"` takes you to the `"About"` page. When you visit a new page, make sure to discard any forward history you have. + - `"Back"`: Takes you to the previous page in your history or stays on the current page if there isn't one. + - `"Forward"`: Takes you forward in the history to the page you came from or stays on the current page if there isn't one. + +For example, given `["Visit About Us", "Back", "Forward"]`, return `"About Us"`. + +# --hints-- + +`navigate(["Visit About Us", "Back", "Forward"])` should return `"About Us"`. + +```js +assert.equal(navigate(["Visit About Us", "Back", "Forward"]), "About Us"); +``` + +`navigate(["Forward"])` should return `"Home"`. + +```js +assert.equal(navigate(["Forward"]), "Home"); +``` + +`navigate(["Back"])` should return `"Home"`. + +```js +assert.equal(navigate(["Back"]), "Home"); +``` + +`navigate(["Visit About Us", "Visit Gallery"])` should return `"Gallery"`. + +```js +assert.equal(navigate(["Visit About Us", "Visit Gallery"]), "Gallery"); +``` + +`navigate(["Visit About Us", "Visit Gallery", "Back", "Back"])` should return `"Home"`. + +```js +assert.equal(navigate(["Visit About Us", "Visit Gallery", "Back", "Back"]), "Home"); +``` + +`navigate(["Visit About", "Visit Gallery", "Back", "Visit Contact", "Forward"])` should return `"Contact"`. + +```js +assert.equal(navigate(["Visit About", "Visit Gallery", "Back", "Visit Contact", "Forward"]), "Contact"); +``` + +`navigate(["Visit About Us", "Visit Visit Us", "Forward", "Visit Contact Us", "Back"])` should return `"Visit Us"`. + +```js +assert.equal(navigate(["Visit About Us", "Visit Visit Us", "Forward", "Visit Contact Us", "Back"]), "Visit Us"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function navigate(commands) { + + return commands; +} +``` + +# --solutions-- + +```js +function navigate(commands) { + const history = ["Home"]; + let currentPageIndex = 0; + + for (const command of commands) { + if (command.startsWith("Visit")) { + history.splice(currentPageIndex + 1); + history.push(command.slice(6)); + currentPageIndex++; + } else if(command === "Back" && currentPageIndex > 0) { + currentPageIndex--; + } else if (command === "Forward" && currentPageIndex < history.length - 1) { + currentPageIndex++; + } + } + + return history[currentPageIndex]; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68e39ed6106dac2f0a98fd62.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68e39ed6106dac2f0a98fd62.md new file mode 100644 index 0000000000000000000000000000000000000000..ea20633ddb3f2e97154bc29ed33aeef83d79b333 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68e39ed6106dac2f0a98fd62.md @@ -0,0 +1,78 @@ +--- +id: 68e39ed6106dac2f0a98fd62 +title: "Challenge 80: Email Sorter" +challengeType: 28 +dashedName: challenge-80 +--- + +# --description-- + +On October 29, 1971, the first email ever was sent, introducing the `username@domain` format we still use. Now, there are billions of email addresses. + +In this challenge, you are given a list of email addresses and need to sort them alphabetically by domain name first (the part after the `@`), and username second (the part before the `@`). + +- Sorting should be case-insensitive. +- If more than one email has the same domain, sort them by their username. +- Return an array of the sorted addresses. +- Returned addresses should retain their original case. + +For example, given `["jill@mail.com", "john@example.com", "jane@example.com"]`, return `["jane@example.com", "john@example.com", "jill@mail.com"]`. + +# --hints-- + +`sort(["jill@mail.com", "john@example.com", "jane@example.com"])` should return `["jane@example.com", "john@example.com", "jill@mail.com"]`. + +```js +assert.deepEqual(sort(["jill@mail.com", "john@example.com", "jane@example.com"]), ["jane@example.com", "john@example.com", "jill@mail.com"]); +``` + +`sort(["bob@mail.com", "alice@zoo.com", "carol@mail.com"])` should return `["bob@mail.com", "carol@mail.com", "alice@zoo.com"]`. + +```js +assert.deepEqual(sort(["bob@mail.com", "alice@zoo.com", "carol@mail.com"]), ["bob@mail.com", "carol@mail.com", "alice@zoo.com"]); +``` + +`sort(["user@z.com", "user@y.com", "user@x.com"])` should return `["user@x.com", "user@y.com", "user@z.com"]`. + +```js +assert.deepEqual(sort(["user@z.com", "user@y.com", "user@x.com"]), ["user@x.com", "user@y.com", "user@z.com"]); +``` + +`sort(["sam@MAIL.com", "amy@mail.COM", "bob@Mail.com"])` should return `["amy@mail.COM", "bob@Mail.com", "sam@MAIL.com"]`. + +```js +assert.deepEqual(sort(["sam@MAIL.com", "amy@mail.COM", "bob@Mail.com"]), ["amy@mail.COM", "bob@Mail.com", "sam@MAIL.com"]); +``` + +`sort(["simon@beta.com", "sammy@alpha.com", "Sarah@Alpha.com", "SAM@ALPHA.com", "Simone@Beta.com", "sara@alpha.com"])` should return `["SAM@ALPHA.com", "sammy@alpha.com", "sara@alpha.com", "Sarah@Alpha.com", "simon@beta.com", "Simone@Beta.com"]`. + +```js +assert.deepEqual(sort(["simon@beta.com", "sammy@alpha.com", "Sarah@Alpha.com", "SAM@ALPHA.com", "Simone@Beta.com", "sara@alpha.com"]), ["SAM@ALPHA.com", "sammy@alpha.com", "sara@alpha.com", "Sarah@Alpha.com", "simon@beta.com", "Simone@Beta.com"]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function sort(emails) { + + return emails; +} +``` + +# --solutions-- + +```js +function sort(emails) { + return emails.slice().sort((a, b) => { + const [userA, domainA] = a.split('@'); + const [userB, domainB] = b.split('@'); + + const domainCompare = domainA.toLowerCase().localeCompare(domainB.toLowerCase()); + if (domainCompare !== 0) return domainCompare; + + return userA.toLowerCase().localeCompare(userB.toLowerCase()); + }); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68e39ed6106dac2f0a98fd63.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68e39ed6106dac2f0a98fd63.md new file mode 100644 index 0000000000000000000000000000000000000000..a12f40914f4a09dac9e93b9934b709ae74091ddc --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68e39ed6106dac2f0a98fd63.md @@ -0,0 +1,78 @@ +--- +id: 68e39ed6106dac2f0a98fd63 +title: "Challenge 81: Nth Prime" +challengeType: 28 +dashedName: challenge-81 +--- + +# --description-- + +A prime number is a positive integer greater than 1 that is divisible only by 1 and itself. The first five prime numbers are `2`, `3`, `5`, `7`, and `11`. + +Given a positive integer `n`, return the `n`th prime number. For example, given `5` return the 5th prime number: `11`. + +# --hints-- + +`nthPrime(5)` should return `11`. + +```js +assert.equal(nthPrime(5), 11); +``` + +`nthPrime(10)` should return `29`. + +```js +assert.equal(nthPrime(10), 29); +``` + +`nthPrime(16)` should return `53`. + +```js +assert.equal(nthPrime(16), 53); +``` + +`nthPrime(99)` should return `523`. + +```js +assert.equal(nthPrime(99), 523); +``` + +`nthPrime(1000)` should return `7919`. + +```js +assert.equal(nthPrime(1000), 7919); +``` + +# --seed-- + +## --seed-contents-- + +```js +function nthPrime(n) { + + return n; +} +``` + +# --solutions-- + +```js +function nthPrime(n) { + const primes = []; + let num = 2; + + while (primes.length < n) { + let isPrime = true; + for (let i = 2; i * i <= num; i++) { + if (num % i === 0) { + isPrime = false; + break; + } + } + if (isPrime) primes.push(num); + num++; + } + + return primes[n - 1]; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68e39ed6106dac2f0a98fd64.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68e39ed6106dac2f0a98fd64.md new file mode 100644 index 0000000000000000000000000000000000000000..5c5f05e22ae28effdf90ffd1d14cd991a95e2c3d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68e39ed6106dac2f0a98fd64.md @@ -0,0 +1,80 @@ +--- +id: 68e39ed6106dac2f0a98fd64 +title: "Challenge 82: SpOoKy~CaSe" +challengeType: 28 +dashedName: challenge-82 +--- + +# --description-- + +Given a string representing a variable name, convert it to "spooky case" using the following constraints: + +- Replace all underscores (`_`), and hyphens (`-`) with a tilde (`~`). +- Capitalize the first letter of the string, and every other letter after that. Ignore the tilde character when counting. Make all other letters lowercase. + +For example, given `hello_world`, return `HeLlO~wOrLd`. + +# --hints-- + +`spookify("hello_world")` should return `"HeLlO~wOrLd"`. + +```js +assert.equal(spookify("hello_world"), "HeLlO~wOrLd"); +``` + +`spookify("Spooky_Case")` should return `"SpOoKy~CaSe"`. + +```js +assert.equal(spookify("Spooky_Case"), "SpOoKy~CaSe"); +``` + +`spookify("TRICK-or-TREAT")` should return `"TrIcK~oR~tReAt"`. + +```js +assert.equal(spookify("TRICK-or-TREAT"), "TrIcK~oR~tReAt"); +``` + +`spookify("c_a-n_d-y_-b-o_w_l")` should return `"C~a~N~d~Y~~b~O~w~L"`. + +```js +assert.equal(spookify("c_a-n_d-y_-b-o_w_l"), "C~a~N~d~Y~~b~O~w~L"); +``` + +`spookify("thE_hAUntEd-hOUsE-Is-fUll_Of_ghOsts")` should return `"ThE~hAuNtEd~HoUsE~iS~fUlL~oF~gHoStS"`. + +```js +assert.equal(spookify("thE_hAUntEd-hOUsE-Is-fUll_Of_ghOsts"), "ThE~hAuNtEd~HoUsE~iS~fUlL~oF~gHoStS"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function spookify(boo) { + + return boo; +} +``` + +# --solutions-- + +```js +function spookify(boo) { + const replaced = boo.replace(/[_-]/g, "~"); + + let result = ""; + let capitalize = true; + + for (let char of replaced) { + if (char === "~") { + result += char; + } else { + result += capitalize ? char.toUpperCase() : char.toLowerCase(); + capitalize = !capitalize; + } + } + + return result; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68e39ed6106dac2f0a98fd65.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68e39ed6106dac2f0a98fd65.md new file mode 100644 index 0000000000000000000000000000000000000000..9e5b452716b0e997baa16c4e5dbf6424ab8637a6 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68e39ed6106dac2f0a98fd65.md @@ -0,0 +1,98 @@ +--- +id: 68e39ed6106dac2f0a98fd65 +title: "Challenge 83: Signature Validation" +challengeType: 28 +dashedName: challenge-83 +--- + +# --description-- + +Given a message string, a secret key string, and a signature number, determine if the signature is valid using this encoding method: + +- Letters in the message and secret key have these values: + - `a` to `z` have values `1` to `26` respectively. + - `A` to `Z` have values `27` to `52` respectively. +- All other characters have no value. +- Compute the signature by taking the sum of the message plus the sum of the secret key. + +For example, given the message `"foo"` and the secret key `"bar"`, the signature would be `57`: + +```md +f (6) + o (15) + o (15) = 36 +b (2) + a (1) + r (18) = 21 +36 + 21 = 57 +``` + +Check if the computed signature matches the provided signature. + +# --hints-- + +`verify("foo", "bar", 57)` should return `true`. + +```js +assert.isTrue(verify("foo", "bar", 57)); +``` + +`verify("foo", "bar", 54)` should return `false`. + +```js +assert.isFalse(verify("foo", "bar", 54)); +``` + +`verify("freeCodeCamp", "Rocks", 238)` should return `true`. + +```js +assert.isTrue(verify("freeCodeCamp", "Rocks", 238)); +``` + +`verify("Is this valid?", "No", 210)` should return `false`. + +```js +assert.isFalse(verify("Is this valid?", "No", 210)); +``` + +`verify("Is this valid?", "Yes", 233)` should return `true`. + +```js +assert.isTrue(verify("Is this valid?", "Yes", 233)); +``` + +`verify("Check out the freeCodeCamp podcast,", "in the mobile app", 514)` should return `true`. + +```js +assert.isTrue(verify("Check out the freeCodeCamp podcast,", "in the mobile app", 514)); +``` + +# --seed-- + +## --seed-contents-- + +```js +function verify(message, key, signature) { + + return message; +} +``` + +# --solutions-- + +```js +function verify(message, key, signature) { + function charValue(ch) { + if (ch >= 'a' && ch <= 'z') return ch.charCodeAt(0) - 'a'.charCodeAt(0) + 1; + if (ch >= 'A' && ch <= 'Z') return ch.charCodeAt(0) - 'A'.charCodeAt(0) + 27; + return 0; + } + + function computeSum(str) { + let sum = 0; + for (let ch of str) { + sum += charValue(ch); + } + return sum; + } + + const total = computeSum(message) + computeSum(key); + return total === signature; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68e39ed6106dac2f0a98fd66.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68e39ed6106dac2f0a98fd66.md new file mode 100644 index 0000000000000000000000000000000000000000..bd685f84bfd2ed8cebf780169ba5c5d191a5e0e2 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68e39ed6106dac2f0a98fd66.md @@ -0,0 +1,87 @@ +--- +id: 68e39ed6106dac2f0a98fd66 +title: "Challenge 84: Infected" +challengeType: 28 +dashedName: challenge-84 +--- + +# --description-- + +On November 2nd, 1988, the first major internet worm was released, infecting about 10% of computers connected to the internet after only a day. + +In this challenge, you are given a number of days that have passed since an internet worm was released, and you need to determine how many computers are infected using the following rules: + +- On day 0, the first computer is infected. +- Each subsequent day, the number of infected computers doubles. +- Every 3rd day, a patch is applied after the virus spreads and reduces the number of infected computers by 20%. Round the number of patched computers up to the nearest whole number. + +For example, on: + +- Day 0: 1 total computer is infected. +- Day 1: 2 total computers are infected. +- Day 2: 4 total computers are infected. +- Day 3: 8 total computers are infected. Then, apply the patch: 8 infected * 20% = 1.6 patched. Round 1.6 up to 2. 8 computers infected - 2 patched = 6 total computers infected after day 3. + +Return the number of total infected computers after the given amount of days have passed. + +# --hints-- + +`infected(1)` should return `2`. + +```js +assert.equal(infected(1), 2); +``` + +`infected(3)` should return `6`. + +```js +assert.equal(infected(3), 6); +``` + +`infected(8)` should return `152`. + +```js +assert.equal(infected(8), 152); +``` + +`infected(17)` should return `39808`. + +```js +assert.equal(infected(17), 39808); +``` + +`infected(25)` should return `5217638`. + +```js +assert.equal(infected(25), 5217638); +``` + +# --seed-- + +## --seed-contents-- + +```js +function infected(days) { + + return days; +} +``` + +# --solutions-- + +```js +function infected(days) { + let infected = 1; + + for (let day = 1; day <= days; day++) { + infected *= 2; + + if (day % 3 === 0) { + let patched = Math.ceil(infected * 0.2); + infected -= patched; + } + } + + return infected; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ee9e3066cfd4eb2328e8a4.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ee9e3066cfd4eb2328e8a4.md new file mode 100644 index 0000000000000000000000000000000000000000..8835cef3d648d976d02cad8ad4af254edca13eb8 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ee9e3066cfd4eb2328e8a4.md @@ -0,0 +1,64 @@ +--- +id: 68ee9e3066cfd4eb2328e8a4 +title: "Challenge 85: Word Counter" +challengeType: 28 +dashedName: challenge-85 +--- + +# --description-- + +Given a sentence string, return the number of words that are in the sentence. + +- Words are any sequence of non-space characters and are separated by a single space. + +# --hints-- + +`countWords("Hello world")` should return `2`. + +```js +assert.equal(countWords("Hello world"), 2); +``` + +`countWords("The quick brown fox jumps over the lazy dog.")` should return `9`. + +```js +assert.equal(countWords("The quick brown fox jumps over the lazy dog."), 9); +``` + +`countWords("I like coding challenges!")` should return `4`. + +```js +assert.equal(countWords("I like coding challenges!"), 4); +``` + +`countWords("Complete the challenge in JavaScript and Python.")` should return `7`. + +```js +assert.equal(countWords("Complete the challenge in JavaScript and Python."), 7); +``` + +`countWords("The missing semi-colon crashed the entire internet.")` should return `7`. + +```js +assert.equal(countWords("The missing semi-colon crashed the entire internet."), 7); +``` + +# --seed-- + +## --seed-contents-- + +```js +function countWords(sentence) { + + return sentence; +} +``` + +# --solutions-- + +```js +function countWords(sentence) { + + return sentence.split(' ').length; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ee9e3066cfd4eb2328e8a5.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ee9e3066cfd4eb2328e8a5.md new file mode 100644 index 0000000000000000000000000000000000000000..077b9f02da55c80742edfbfe688986bbe853a769 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ee9e3066cfd4eb2328e8a5.md @@ -0,0 +1,61 @@ +--- +id: 68ee9e3066cfd4eb2328e8a5 +title: "Challenge 86: Image Search" +challengeType: 28 +dashedName: challenge-86 +--- + +# --description-- + +On November 4th, 2001, Google launched its image search, allowing people to find images using search terms. In this challenge, you will imitate the image search. + +Given an array of image names and a search term, return an array of image names containing the search term. + +- Ignore the case when matching the search terms. +- Return the images in the same order they appear in the input array. + +# --hints-- + +`imageSearch(["dog.png", "cat.jpg", "parrot.jpeg"], "dog")` should return `["dog.png"]`. + +```js +assert.deepEqual(imageSearch(["dog.png", "cat.jpg", "parrot.jpeg"], "dog"), ["dog.png"]); +``` + +`imageSearch(["Sunset.jpg", "Beach.png", "sunflower.jpeg"], "sun")` should return `["Sunset.jpg", "sunflower.jpeg"]`. + +```js +assert.deepEqual(imageSearch(["Sunset.jpg", "Beach.png", "sunflower.jpeg"], "sun"), ["Sunset.jpg", "sunflower.jpeg"]); +``` + +`imageSearch(["Moon.png", "sun.jpeg", "stars.png"], "PNG")` should return `["Moon.png", "stars.png"]`. + +```js +assert.deepEqual(imageSearch(["Moon.png", "sun.jpeg", "stars.png"], "PNG"), ["Moon.png", "stars.png"]); +``` + +`imageSearch(["cat.jpg", "dogToy.jpeg", "kitty-cat.png", "catNip.jpeg", "franken_cat.gif"], "Cat")` should return `["cat.jpg", "kitty-cat.png", "catNip.jpeg", "franken_cat.gif"]`. + +```js +assert.deepEqual(imageSearch(["cat.jpg", "dogToy.jpeg", "kitty-cat.png", "catNip.jpeg", "franken_cat.gif"], "Cat"), ["cat.jpg", "kitty-cat.png", "catNip.jpeg", "franken_cat.gif"]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function imageSearch(images, term) { + + return images; +} +``` + +# --solutions-- + +```js +function imageSearch(images, term) { + const lowerTerm = term.toLowerCase(); + return images.filter(img => img.toLowerCase().includes(lowerTerm)); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ee9e3066cfd4eb2328e8a6.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ee9e3066cfd4eb2328e8a6.md new file mode 100644 index 0000000000000000000000000000000000000000..f0948b9eb2a058b5960ac1e41d018b652ae590de --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ee9e3066cfd4eb2328e8a6.md @@ -0,0 +1,69 @@ +--- +id: 68ee9e3066cfd4eb2328e8a6 +title: "Challenge 87: Matrix Builder" +challengeType: 28 +dashedName: challenge-87 +--- + +# --description-- + +Given two integers (a number of rows and a number of columns), return a matrix (an array of arrays) filled with zeros (`0`) of the given size. + +For example, given `2` and `3`, return: + +```json +[ + [0, 0, 0], + [0, 0, 0] +] +``` + +# --hints-- + +`buildMatrix(2, 3)` should return `[[0, 0, 0], [0, 0, 0]]`. + +```js +assert.deepEqual(buildMatrix(2, 3), [[0, 0, 0], [0, 0, 0]]); +``` + +`buildMatrix(3, 2)` should return `[[0, 0], [0, 0], [0, 0]]`. + +```js +assert.deepEqual(buildMatrix(3, 2), [[0, 0], [0, 0], [0, 0]]); +``` + +`buildMatrix(4, 3)` should return `[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]`. + +```js +assert.deepEqual(buildMatrix(4, 3), [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]); +``` + +`buildMatrix(9, 1)` should return `[[0], [0], [0], [0], [0], [0], [0], [0], [0]]`. + +```js +assert.deepEqual(buildMatrix(9, 1), [[0], [0], [0], [0], [0], [0], [0], [0], [0]]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function buildMatrix(rows, cols) { + + return rows; +} +``` + +# --solutions-- + +```js +function buildMatrix(rows, cols) { + const matrix = []; + for (let i = 0; i < rows; i++) { + const row = new Array(cols).fill(0); + matrix.push(row); + } + return matrix; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ee9e3066cfd4eb2328e8a7.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ee9e3066cfd4eb2328e8a7.md new file mode 100644 index 0000000000000000000000000000000000000000..4552b934640215ec7a1f6c053803f91a48f80d69 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ee9e3066cfd4eb2328e8a7.md @@ -0,0 +1,77 @@ +--- +id: 68ee9e3066cfd4eb2328e8a7 +title: "Challenge 88: Weekday Finder" +challengeType: 28 +dashedName: challenge-88 +--- + +# --description-- + +Given a string date in the format `YYYY-MM-DD`, return the day of the week. + +Valid return days are: + +- `"Sunday"` +- `"Monday"` +- `"Tuesday"` +- `"Wednesday"` +- `"Thursday"` +- `"Friday"` +- `"Saturday"` + +Be sure to ignore time zones. + +# --hints-- + +`getWeekday("2025-11-06")` should return `Thursday`. + +```js +assert.equal(getWeekday("2025-11-06"), "Thursday"); +``` + +`getWeekday("1999-12-31")` should return `Friday`. + +```js +assert.equal(getWeekday("1999-12-31"), "Friday"); +``` + +`getWeekday("1111-11-11")` should return `Saturday`. + +```js +assert.equal(getWeekday("1111-11-11"), "Saturday"); +``` + +`getWeekday("2112-12-21")` should return `Wednesday`. + +```js +assert.equal(getWeekday("2112-12-21"), "Wednesday"); +``` + +`getWeekday("2345-10-01")` should return `Monday`. + +```js +assert.equal(getWeekday("2345-10-01"), "Monday"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getWeekday(dateString) { + + return dateString; +} +``` + +# --solutions-- + +```js +function getWeekday(dateString) { + const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; + const [year, month, day] = dateString.split("-").map(Number); + const date = new Date(Date.UTC(year, month - 1, day)); + + return days[date.getUTCDay()]; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ee9e3066cfd4eb2328e8a8.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ee9e3066cfd4eb2328e8a8.md new file mode 100644 index 0000000000000000000000000000000000000000..0ea141181dc59c1ac9e14028558513c0b8a56c36 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ee9e3066cfd4eb2328e8a8.md @@ -0,0 +1,81 @@ +--- +id: 68ee9e3066cfd4eb2328e8a8 +title: "Challenge 89: Counting Cards" +challengeType: 28 +dashedName: challenge-89 +--- + +# --description-- + +A standard deck of playing cards has 13 unique cards in each suit. Given an integer representing the number of cards to pick from the deck, return the number of unique combinations of cards you can pick. + +- Order does not matter. Picking card A then card B is the same as picking card B then card A. + +For example, given `52`, return `1`. There's only one combination of 52 cards to pick from a 52 card deck. And given `2`, return `1326`, There's 1326 card combinations you can end up with when picking 2 cards from the deck. + +# --hints-- + +`combinations(52)` should return `1`. + +```js +assert.equal(combinations(52), 1); +``` + +`combinations(1)` should return `52`. + +```js +assert.equal(combinations(1), 52); +``` + +`combinations(2)` should return `1326`. + +```js +assert.equal(combinations(2), 1326); +``` + +`combinations(5)` should return `2598960`. + +```js +assert.equal(combinations(5), 2598960); +``` + +`combinations(10)` should return `15820024220`. + +```js +assert.equal(combinations(10), 15820024220); +``` + +`combinations(50)` should return `1326`. + +```js +assert.equal(combinations(50), 1326); +``` + +# --seed-- + +## --seed-contents-- + +```js +function combinations(cards) { + + return cards; +} +``` + +# --solutions-- + +```js +function combinations(cards) { + const n = 52; + + function factorial(x) { + let result = 1; + for (let i = 2; i <= x; i++) { + result *= i; + } + return result; + } + + return factorial(n) / (factorial(cards) * factorial(n - cards)); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c7c.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c7c.md new file mode 100644 index 0000000000000000000000000000000000000000..ffd586b09bbd4971e430d78a6aae33959a500fbb --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c7c.md @@ -0,0 +1,59 @@ +--- +id: 68f6587287ad1f4ad39b0c7c +title: "Challenge 90: Character Limit" +challengeType: 28 +dashedName: challenge-90 +--- + +# --description-- + +In this challenge, you are given a string and need to determine if it fits in a social media post. Return the following strings based on the rules given: + +- `"short post"` if it fits within a 40-character limit. +- `"long post"` if it's greater than 40 characters and fits within an 80-character limit. +- `"invalid post"` if it's too long to fit within either limit. + +# --hints-- + +`canPost("Hello world")` should return `"short post"`. + +```js +assert.equal(canPost("Hello world"), "short post"); +``` + +`canPost("This is a longer message but still under eighty characters.")` should return `"long post"`. + +```js +assert.equal(canPost("This is a longer message but still under eighty characters."), "long post"); +``` + +`canPost("This message is too long to fit into either of the character limits for a social media post.")` should return `"invalid post"`. + +```js +assert.equal(canPost("This message is too long to fit into either of the character limits for a social media post."), "invalid post"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function canPost(message) { + + return message; +} +``` + +# --solutions-- + +```js +function canPost(message) { + if (message.length <= 40) { + return "short post" + } else if (message.length <= 80) { + return "long post" + } else { + return "invalid post" + } +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c7d.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c7d.md new file mode 100644 index 0000000000000000000000000000000000000000..b3da195001ed6bf181fc7a5562c06c83f42beeae --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c7d.md @@ -0,0 +1,112 @@ +--- +id: 68f6587287ad1f4ad39b0c7d +title: "Challenge 91: Word Search" +challengeType: 28 +dashedName: challenge-91 +--- + +# --description-- + +Given a matrix (an array of arrays) of single letters and a word to find, return the start and end indices of the word in the matrix. + +- The given matrix will be filled with all lowercase letters (`a-z`). +- The word to find will always be in the matrix exactly once. +- The word to find will always be in a straight line in one of these directions: + - left to right + - right to left + - top to bottom + - bottom to top + +For example, given the matrix: + +```md +[ + ["a", "c", "t"], + ["t", "a", "t"], + ["c", "t", "c"] +] +``` + +And the word `"cat"`, return: + +```md +[[0, 1], [2, 1]] +``` + +Where `[0, 1]` are the indices for the `"c"` (start of the word), and `[2, 1]` are the indices for the `"t"` (end of the word). + +# --hints-- + +`findWord([["a", "c", "t"], ["t", "a", "t"], ["c", "t", "c"]], "cat")` should return `[[0, 1], [2, 1]]`. + +```js +assert.deepEqual(findWord([["a", "c", "t"], ["t", "a", "t"], ["c", "t", "c"]], "cat"), [[0, 1], [2, 1]]); +``` + +`findWord([["d", "o", "g"], ["o", "g", "d"], ["d", "g", "o"]], "dog")` should return `[[0, 0], [0, 2]]`. + +```js +assert.deepEqual(findWord([["d", "o", "g"], ["o", "g", "d"], ["d", "g", "o"]], "dog"), [[0, 0], [0, 2]]); +``` + +`findWord([["h", "i", "s", "h"], ["i", "s", "f", "s"], ["f", "s", "i", "i"], ["s", "h", "i", "f"]], "fish")` should return `[[3, 3], [0, 3]]`. + +```js +assert.deepEqual(findWord([["h", "i", "s", "h"], ["i", "s", "f", "s"], ["f", "s", "i", "i"], ["s", "h", "i", "f"]], "fish"), [[3, 3], [0, 3]]); +``` + +`findWord([["f", "x", "o", "x"], ["o", "x", "o", "f"], ["f", "o", "f", "x"], ["f", "x", "x", "o"]], "fox")` should return `[[1, 3], [1, 1]]`. + +```js +assert.deepEqual(findWord([["f", "x", "o", "x"], ["o", "x", "o", "f"], ["f", "o", "f", "x"], ["f", "x", "x", "o"]], "fox"), [[1, 3], [1, 1]]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function findWord(matrix, word) { + + return matrix; +} +``` + +# --solutions-- + +```js +function findWord(matrix, word) { + const rows = matrix.length; + const cols = matrix[0].length; + const len = word.length; + + const directions = [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0] + ]; + + for (let r = 0; r < rows; r++) { + for (let c = 0; c < cols; c++) { + for (let [dr, dc] of directions) { + let match = true; + for (let i = 0; i < len; i++) { + const nr = r + dr * i; + const nc = c + dc * i; + if (nr < 0 || nr >= rows || nc < 0 || nc >= cols || matrix[nr][nc] !== word[i]) { + match = false; + break; + } + } + if (match) { + return [ + [r, c], + [r + dr * (len - 1), c + dc * (len - 1)] + ]; + } + } + } + } +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c7e.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c7e.md new file mode 100644 index 0000000000000000000000000000000000000000..2a9110044fbd84e2cd91a1f1e600a752823bc2b3 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c7e.md @@ -0,0 +1,77 @@ +--- +id: 68f6587287ad1f4ad39b0c7e +title: "Challenge 92: Extension Extractor" +challengeType: 28 +dashedName: challenge-92 +--- + +# --description-- + +Given a string representing a filename, return the extension of the file. + +- The extension is the part of the filename that comes after the last period (`.`). +- If the filename does not contain a period or ends with a period, return `"none"`. +- The extension should be returned as-is, preserving case. + +# --hints-- + +`getExtension("document.txt")` should return `"txt"`. + +```js +assert.equal(getExtension("document.txt"), "txt"); +``` + +`getExtension("README")` should return `"none"`. + +```js +assert.equal(getExtension("README"), "none"); +``` + +`getExtension("image.PNG")` should return `"PNG"`. + +```js +assert.equal(getExtension("image.PNG"), "PNG"); +``` + +`getExtension(".gitignore")` should return `"gitignore"`. + +```js +assert.equal(getExtension(".gitignore"), "gitignore"); +``` + +`getExtension("archive.tar.gz")` should return `"gz"`. + +```js +assert.equal(getExtension("archive.tar.gz"), "gz"); +``` + +`getExtension("final.draft.")` should return `"none"`. + +```js +assert.equal(getExtension("final.draft."), "none"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getExtension(filename) { + + return filename; +} +``` + +# --solutions-- + +```js +function getExtension(filename) { + const lastDot = filename.lastIndexOf('.'); + + if (lastDot === -1 || lastDot === filename.length - 1) { + return "none"; + } + + return filename.slice(lastDot + 1); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c7f.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c7f.md new file mode 100644 index 0000000000000000000000000000000000000000..ea2adc679e8f4495a6f1ba788b6065b191424fa3 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c7f.md @@ -0,0 +1,86 @@ +--- +id: 68f6587287ad1f4ad39b0c7f +title: "Challenge 93: Vowels and Consonants" +challengeType: 28 +dashedName: challenge-93 +--- + +# --description-- + +Given a string, return an array with the number of vowels and number of consonants in the string. + +- Vowels consist of `a`, `e`, `i`, `o`, `u` in any case. +- Consonants consist of all other letters in any case. +- Ignore any non-letter characters. + +For example, given `"Hello World"`, return `[3, 7]`. + +# --hints-- + +`count("Hello World")` should return `[3, 7]`. + +```js +assert.deepEqual(count("Hello World"), [3, 7]); +``` + +`count("JavaScript")` should return `[3, 7]`. + +```js +assert.deepEqual(count("JavaScript"), [3, 7]); +``` + +`count("Python")` should return `[1, 5]`. + +```js +assert.deepEqual(count("Python"), [1, 5]); +``` + +`count("freeCodeCamp")` should return `[5, 7]`. + +```js +assert.deepEqual(count("freeCodeCamp"), [5, 7]); +``` + +`count("Hello, World!")` should return `[3, 7]`. + +```js +assert.deepEqual(count("Hello, World!"), [3, 7]); +``` + +`count("The quick brown fox jumps over the lazy dog.")` should return `[11, 24]`. + +```js +assert.deepEqual(count("The quick brown fox jumps over the lazy dog."), [11, 24]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function count(str) { + + return str; +} +``` + +# --solutions-- + +```js +function count(str) { + const vowels = 'aeiou'; + const consonants = 'bcdfghjklmnpqrstvwxyz'; + let v = 0, c = 0; + + for (let i=0; i>` as the prefix. + - `J-R`: Use `--` as the prefix. + - `S-Z`: Use `::` as the prefix. +- A comma and space (`, `) should follow the name. +- The title and company should follow the comma and space, separated by `" at "` (with spaces around it). + +For example, given `"Quinn Waverly"`, `"Founder and CEO"`, and `"TechCo"` return `"--Quinn Waverly, Founder and CEO at TechCo"`. + +# --hints-- + +`generateSignature("Quinn Waverly", "Founder and CEO", "TechCo")` should return `"--Quinn Waverly, Founder and CEO at TechCo"`. + +```js +assert.equal(generateSignature("Quinn Waverly", "Founder and CEO", "TechCo"), "--Quinn Waverly, Founder and CEO at TechCo"); +``` + +`generateSignature("Alice Reed", "Engineer", "TechCo")` should return `">>Alice Reed, Engineer at TechCo"`. + +```js +assert.equal(generateSignature("Alice Reed", "Engineer", "TechCo"), ">>Alice Reed, Engineer at TechCo"); +``` + +`generateSignature("Tina Vaughn", "Developer", "example.com")` should return `"::Tina Vaughn, Developer at example.com"`. + +```js +assert.equal(generateSignature("Tina Vaughn", "Developer", "example.com"), "::Tina Vaughn, Developer at example.com"); +``` + +`generateSignature("B. B.", "Product Tester", "AcmeCorp")` should return `">>B. B., Product Tester at AcmeCorp"`. + +```js +assert.equal(generateSignature("B. B.", "Product Tester", "AcmeCorp"), ">>B. B., Product Tester at AcmeCorp"); +``` + +`generateSignature("windstorm", "Cloud Architect", "Atmospheronics")` should return `"::windstorm, Cloud Architect at Atmospheronics"`. + +```js +assert.equal(generateSignature("windstorm", "Cloud Architect", "Atmospheronics"), "::windstorm, Cloud Architect at Atmospheronics"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function generateSignature(name, title, company) { + + return name; +} +``` + +# --solutions-- + +```js +function generateSignature(name, title, company) { + const firstLetter = name[0].toUpperCase(); + let prefix; + if ("ABCDEFGHI".includes(firstLetter)) { + prefix = ">>"; + } else if ("JKLMNOPQR".includes(firstLetter)) { + prefix = "--"; + } else { + prefix = "::"; + } + + return `${prefix}${name}, ${title} at ${company}`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c81.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c81.md new file mode 100644 index 0000000000000000000000000000000000000000..d7ea7a5e457b2f5e4d0022f09617027e5ba87f05 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c81.md @@ -0,0 +1,71 @@ +--- +id: 68f6587287ad1f4ad39b0c81 +title: "Challenge 95: Array Shift" +challengeType: 28 +dashedName: challenge-95 +--- + +# --description-- + +Given an array and an integer representing how many positions to shift the array, return the shifted array. + +- A positive integer shifts the array to the left. +- A negative integer shifts the array to the right. +- The shift wraps around the array. + +For example, given `[1, 2, 3]` and `1`, shift the array 1 to the left, returning `[2, 3, 1]`. + +# --hints-- + +`shiftArray([1, 2, 3], 1)` should return `[2, 3, 1]`. + +```js +assert.deepEqual(shiftArray([1, 2, 3], 1), [2, 3, 1]); +``` + +`shiftArray([1, 2, 3], -1)` should return `[3, 1, 2]`. + +```js +assert.deepEqual(shiftArray([1, 2, 3], -1), [3, 1, 2]); +``` + +`shiftArray(["alpha", "bravo", "charlie"], 5)` should return `["charlie", "alpha", "bravo"]`. + +```js +assert.deepEqual(shiftArray(["alpha", "bravo", "charlie"], 5), ["charlie", "alpha", "bravo"]); +``` + +`shiftArray(["alpha", "bravo", "charlie"], -11)` should return `["bravo", "charlie", "alpha"]`. + +```js +assert.deepEqual(shiftArray(["alpha", "bravo", "charlie"], -11), ["bravo", "charlie", "alpha"]); +``` + +`shiftArray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 15)` should return `[5, 6, 7, 8, 9, 0, 1, 2, 3, 4]`. + +```js +assert.deepEqual(shiftArray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 15), [5, 6, 7, 8, 9, 0, 1, 2, 3, 4]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function shiftArray(arr, n) { + + return arr; +} +``` + +# --solutions-- + +```js +function shiftArray(arr, n) { + const len = arr.length; + n = n % len; + if (n < 0) n += len; + + return arr.slice(n).concat(arr.slice(0, n)); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c82.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c82.md new file mode 100644 index 0000000000000000000000000000000000000000..a17078130659440932c49aed53f2894576e254d9 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c82.md @@ -0,0 +1,83 @@ +--- +id: 68f6587287ad1f4ad39b0c82 +title: "Challenge 96: Is It the Weekend?" +challengeType: 28 +dashedName: challenge-96 +--- + +# --description-- + +Given a date in the format `"YYYY-MM-DD"`, return the number of days left until the weekend. + +- The weekend starts on Saturday. +- If the given date is Saturday or Sunday, return `"It's the weekend!"`. +- Otherwise, return `"X days until the weekend."`, where `X` is the number of days until Saturday. +- If `X` is `1`, use `"day"` (singular) instead of `"days"` (plural). +- Make sure the calculation ignores your local timezone. + +# --hints-- + +`daysUntilWeekend("2025-11-14")` should return `"1 day until the weekend."`. + +```js +assert.equal(daysUntilWeekend("2025-11-14"), "1 day until the weekend."); +``` + +`daysUntilWeekend("2025-01-01")` should return `"3 days until the weekend."`. + +```js +assert.equal(daysUntilWeekend("2025-01-01"), "3 days until the weekend."); +``` + +`daysUntilWeekend("2025-12-06")` should return `"It's the weekend!"`. + +```js +assert.equal(daysUntilWeekend("2025-12-06"), "It's the weekend!"); +``` + +`daysUntilWeekend("2026-01-27")` should return `"4 days until the weekend."`. + +```js +assert.equal(daysUntilWeekend("2026-01-27"), "4 days until the weekend."); +``` + +`daysUntilWeekend("2026-09-07")` should return `"5 days until the weekend."`. + +```js +assert.equal(daysUntilWeekend("2026-09-07"), "5 days until the weekend."); +``` + +`daysUntilWeekend("2026-11-29")` should return `"It's the weekend!"`. + +```js +assert.equal(daysUntilWeekend("2026-11-29"), "It's the weekend!"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function daysUntilWeekend(dateString) { + + return dateString; +} +``` + +# --solutions-- + +```js +function daysUntilWeekend(dateString) { + const [year, month, day] = dateString.split("-").map(Number); + const date = new Date(Date.UTC(year, month - 1, day)); + + const dayOfWeek = date.getUTCDay(); + + if (dayOfWeek === 6 || dayOfWeek === 0) { + return "It's the weekend!"; + } + + const daysUntilSaturday = (6 - dayOfWeek); + return `${daysUntilSaturday} day${daysUntilSaturday === 1 ? "" : "s"} until the weekend.`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c83.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c83.md new file mode 100644 index 0000000000000000000000000000000000000000..9e46e536bb4ea718ab3fcd7c8961430da74e666c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c83.md @@ -0,0 +1,70 @@ +--- +id: 68f6587287ad1f4ad39b0c83 +title: "Challenge 97: GCD" +challengeType: 28 +dashedName: challenge-97 +--- + +# --description-- + +Given two positive integers, return their greatest common divisor (GCD). + +- The GCD of two integers is the largest number that divides evenly into both numbers without leaving a remainder. + +For example, the divisors of `4` are `1`, `2`, and `4`. The divisors of `6` are `1`, `2`, `3`, and `6`. So given `4` and `6`, return `2`, the largest number that appears in both sets of divisors. + +# --hints-- + +`gcd(4, 6)` should return `2`. + +```js +assert.equal(gcd(4, 6), 2); +``` + +`gcd(20, 15)` should return `5`. + +```js +assert.equal(gcd(20, 15), 5); +``` + +`gcd(13, 17)` should return `1`. + +```js +assert.equal(gcd(13, 17), 1); +``` + +`gcd(654, 456)` should return `6`. + +```js +assert.equal(gcd(654, 456), 6); +``` + +`gcd(3456, 4320)` should return `864`. + +```js +assert.equal(gcd(3456, 4320), 864); +``` + +# --seed-- + +## --seed-contents-- + +```js +function gcd(x, y) { + + return x; +} +``` + +# --solutions-- + +```js +function gcd(x, y) { + while (y !== 0) { + const temp = y; + y = x % y; + x = temp; + } + return x; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c84.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c84.md new file mode 100644 index 0000000000000000000000000000000000000000..4d6d7839c12031f15a13e976d18b898d5d30d4aa --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c84.md @@ -0,0 +1,73 @@ +--- +id: 68f6587287ad1f4ad39b0c84 +title: "Challenge 98: Rectangle Count" +challengeType: 28 +dashedName: challenge-98 +--- + +# --description-- + +Given two positive integers representing the width and height of a rectangle, determine how many rectangles can fit in the given one. + +- Only count rectangles with integer width and height. + +For example, given `1` and `3`, return `6`. Three 1x1 rectangles, two 1x2 rectangles, and one 1x3 rectangle. + +# --hints-- + +`countRectangles(1, 3)` should return `6`. + +```js +assert.equal(countRectangles(1, 3), 6); +``` + +`countRectangles(3, 2)` should return `18`. + +```js +assert.equal(countRectangles(3, 2), 18); +``` + +`countRectangles(1, 2)` should return `3`. + +```js +assert.equal(countRectangles(1, 2), 3); +``` + +`countRectangles(5, 4)` should return `150`. + +```js +assert.equal(countRectangles(5, 4), 150); +``` + +`countRectangles(11, 19)` should return `12540`. + +```js +assert.equal(countRectangles(11, 19), 12540); +``` + +# --seed-- + +## --seed-contents-- + +```js +function countRectangles(width, height) { + + return width; +} +``` + +# --solutions-- + +```js +function countRectangles(width, height) { + let count = 0; + + for (let w = 1; w <= width; w++) { + for (let h = 1; h <= height; h++) { + count += (width - w + 1) * (height - h + 1); + } + } + + return count; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c85.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c85.md new file mode 100644 index 0000000000000000000000000000000000000000..c9a44467cebf0f70a0ce70c7d27d0e7716cc3921 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c85.md @@ -0,0 +1,84 @@ +--- +id: 68f6587287ad1f4ad39b0c85 +title: "Challenge 99: Fingerprint Test" +challengeType: 28 +dashedName: challenge-99 +--- + +# --description-- + +Given two strings representing fingerprints, determine if they are a match using the following rules: + +- Each fingerprint will consist only of lowercase letters (`a-z`). +- Two fingerprints are considered a match if: + - They are the same length. + - The number of differing characters does not exceed 10% of the fingerprint length. + +# --hints-- + +`isMatch("helloworld", "helloworld")` should return `true`. + +```js +assert.isTrue(isMatch("helloworld", "helloworld")); +``` + +`isMatch("helloworld", "helloworlds")` should return `false`. + +```js +assert.isFalse(isMatch("helloworld", "helloworlds")); +``` + +`isMatch("helloworld", "jelloworld")` should return `true`. + +```js +assert.isTrue(isMatch("helloworld", "jelloworld")); +``` + +`isMatch("thequickbrownfoxjumpsoverthelazydog", "thequickbrownfoxjumpsoverthelazydog")` should return `true`. + +```js +assert.isTrue(isMatch("thequickbrownfoxjumpsoverthelazydog", "thequickbrownfoxjumpsoverthelazydog")); +``` + +`isMatch("theslickbrownfoxjumpsoverthelazydog", "thequickbrownfoxjumpsoverthehazydog")` should return `true`. + +```js +assert.isTrue(isMatch("theslickbrownfoxjumpsoverthelazydog", "thequickbrownfoxjumpsoverthehazydog")); +``` + +`isMatch("thequickbrownfoxjumpsoverthelazydog", "thequickbrownfoxjumpsoverthehazycat")` should return `false`. + +```js +assert.isFalse(isMatch("thequickbrownfoxjumpsoverthelazydog", "thequickbrownfoxjumpsoverthehazycat")); +``` + +# --seed-- + +## --seed-contents-- + +```js +function isMatch(fingerprintA, fingerprintB) { + + return fingerprintA; +} +``` + +# --solutions-- + +```js +function isMatch(fingerprintA, fingerprintB) { + if (fingerprintA.length !== fingerprintB.length) return false; + + const length = fingerprintA.length; + let mismatches = 0; + + for (let i = 0; i < length; i++) { + if (fingerprintA[i] !== fingerprintB[i]) { + mismatches++; + if (mismatches > length * 0.1) return false; + } + } + + return true; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328c3.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328c3.md new file mode 100644 index 0000000000000000000000000000000000000000..027458d96c1602c19a618d20235dc6f84fd12142 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328c3.md @@ -0,0 +1,65 @@ +--- +id: 68ffb91507a5b645769328c3 +title: "Challenge 100: 100 Characters" +challengeType: 28 +dashedName: challenge-100 +--- + +# --description-- + +Welcome to the 100th Daily Coding Challenge! + +Given a string, repeat its characters until the result is exactly 100 characters long. If your repetitions go over 100 characters, trim the extra so it's exactly 100. + +# --hints-- + +`oneHundred("One hundred ")` should return `"One hundred One hundred One hundred One hundred One hundred One hundred One hundred One hundred One "`. + +```js +assert.equal(oneHundred("One hundred "), "One hundred One hundred One hundred One hundred One hundred One hundred One hundred One hundred One "); +``` + +`oneHundred("freeCodeCamp ")` should return `"freeCodeCamp freeCodeCamp freeCodeCamp freeCodeCamp freeCodeCamp freeCodeCamp freeCodeCamp freeCodeC"`. + +```js +assert.equal(oneHundred("freeCodeCamp "), "freeCodeCamp freeCodeCamp freeCodeCamp freeCodeCamp freeCodeCamp freeCodeCamp freeCodeCamp freeCodeC"); +``` + +`oneHundred("daily challenges ")` should return `"daily challenges daily challenges daily challenges daily challenges daily challenges daily challenge"`. + +```js +assert.equal(oneHundred("daily challenges "), "daily challenges daily challenges daily challenges daily challenges daily challenges daily challenge"); +``` + +`oneHundred("!")` should return `"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"`. + +```js +assert.equal(oneHundred("!"), "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function oneHundred(chars) { + + return chars; +} +``` + +# --solutions-- + +```js +function oneHundred(chars) { + let result = ""; + let i = 0; + + while (result.length < 100) { + result += chars[i % chars.length]; + i++; + } + + return result.slice(0, 100); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328c4.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328c4.md new file mode 100644 index 0000000000000000000000000000000000000000..9e8b1a1a9d9f016cc3232761fdb2ea7d12766729 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328c4.md @@ -0,0 +1,95 @@ +--- +id: 68ffb91507a5b645769328c4 +title: "Challenge 101: Markdown Heading Converter" +challengeType: 28 +dashedName: challenge-101 +--- + +# --description-- + +Given a string representing a Markdown heading, return the equivalent HTML heading. + +A valid Markdown heading must: + +- Start with zero or more spaces, followed by +- 1 to 6 hash characters (`#`) in a row, then +- At least one space. And finally, +- The heading text. + +The number of hash symbols determines the heading level. For example, one hash symbol corresponds to an `h1` tag, and six hash symbols correspond to an `h6` tag. + +If the given string doesn't have the exact format above, return `"Invalid format"`. + +For example, given `"# My level 1 heading"`, return `"

My level 1 heading

"`. + +Note: The console may not display HTML tags in strings when logging messages. Check the browser console to see logs with tags included. + +# --hints-- + +`convert("# My level 1 heading")` should return `"

My level 1 heading

"`. + +```js +assert.equal(convert("# My level 1 heading"), "

My level 1 heading

"); +``` + +`convert("My heading")` should return `"Invalid format"`. + +```js +assert.equal(convert("My heading"), "Invalid format"); +``` + +`convert("##### My level 5 heading")` should return `"
My level 5 heading
"`. + +```js +assert.equal(convert("##### My level 5 heading"), "
My level 5 heading
"); +``` + +`convert("#My heading")` should return `"Invalid format"`. + +```js +assert.equal(convert("#My heading"), "Invalid format"); +``` + +`convert(" ### My level 3 heading")` should return `"

My level 3 heading

"`. + +```js +assert.equal(convert(" ### My level 3 heading"), "

My level 3 heading

"); +``` + +`convert("####### My level 7 heading")` should return `"Invalid format"`. + +```js +assert.equal(convert("####### My level 7 heading"), "Invalid format"); +``` + +`convert("## My #2 heading")` should return `"

My #2 heading

"`. + +```js +assert.equal(convert("## My #2 heading"), "

My #2 heading

"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function convert(heading) { + + return heading; +} +``` + +# --solutions-- + +```js +function convert(heading) { + const trimmed = heading.trim() + + if (!/^#{1,6}\s+\S+/.test(trimmed)) return "Invalid format" + + const hashCount = trimmed.indexOf(' '); + const text = trimmed.slice(hashCount).trimStart(); + + return `${text}`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328c5.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328c5.md new file mode 100644 index 0000000000000000000000000000000000000000..d84c708c242ed6b1d89532979e32effe48eeed59 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328c5.md @@ -0,0 +1,82 @@ +--- +id: 68ffb91507a5b645769328c5 +title: "Challenge 102: Longest Word" +challengeType: 28 +dashedName: challenge-102 +--- + +# --description-- + +Given a sentence string, return the longest word in the sentence. + +- Words are separated by a single space. +- Only letters (`a-z`, case-insensitive) count toward the word's length. +- If there are multiple words with the same length, return the first one that appears. +- Return the word as it appears in the given string, with punctuation removed. + +# --hints-- + +`longestWord("The quick red fox")` should return `"quick"`. + +```js +assert.equal(longestWord("The quick red fox"), "quick"); +``` + +`longestWord("Hello coding challenge.")` should return `"challenge"`. + +```js +assert.equal(longestWord("Hello coding challenge."), "challenge"); +``` + +`longestWord("Do Try This At Home.")` should return `"This"`. + +```js +assert.equal(longestWord("Do Try This At Home."), "This"); +``` + +`longestWord("This sentence... has commas, ellipses, and an exclamation point!")` should return `"exclamation"`. + +```js +assert.equal(longestWord("This sentence... has commas, ellipses, and an exclamation point!"), "exclamation"); +``` + +`longestWord("A tie? No way!")` should return `"tie"`. + +```js +assert.equal(longestWord("A tie? No way!"), "tie"); +``` + +`longestWord("Wouldn't you like to know.")` should return `"Wouldnt"`. + +```js +assert.equal(longestWord("Wouldn't you like to know."), "Wouldnt"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function longestWord(sentence) { + + return sentence; +} +``` + +# --solutions-- + +```js +function longestWord(sentence) { + const words = sentence.split(" "); + let longest = ""; + + for (let word of words) { + const cleaned = word.replace(/[^a-z]/gi, ""); + if (cleaned.length > longest.length) { + longest = cleaned; + } + } + + return longest; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328c6.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328c6.md new file mode 100644 index 0000000000000000000000000000000000000000..ff823a4a7f87e873fe23b1411fe925cfd11990aa --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328c6.md @@ -0,0 +1,71 @@ +--- +id: 68ffb91507a5b645769328c6 +title: "Challenge 103: LCM" +challengeType: 28 +dashedName: challenge-103 +--- + +# --description-- + +Given two integers, return the least common multiple (LCM) of the two numbers. + +The LCM of two numbers is the smallest positive integer that is a multiple of both numbers. For example, given `4` and `6`, return `12` because: + +- Multiples of `4` are `4`, `8`, `12` and so on. +- Multiples of `6` are `6`, `12`, `18` and so on. +- `12` is the smallest number that is a multiple of both. + +# --hints-- + +`lcm(4, 6)` should return `12`. + +```js +assert.equal(lcm(4, 6), 12); +``` + +`lcm(9, 6)` should return `18`. + +```js +assert.equal(lcm(9, 6), 18); +``` + +`lcm(10, 100)` should return `100`. + +```js +assert.equal(lcm(10, 100), 100); +``` + +`lcm(13, 17)` should return `221`. + +```js +assert.equal(lcm(13, 17), 221); +``` + +`lcm(45, 70)` should return `630`. + +```js +assert.equal(lcm(45, 70), 630); +``` + +# --seed-- + +## --seed-contents-- + +```js +function lcm(a, b) { + + return a; +} +``` + +# --solutions-- + +```js +function lcm(a, b) { + function gcd(x, y) { + return y === 0 ? x : gcd(y, x % y); + } + + return Math.abs(a * b) / gcd(a, b); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328c7.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328c7.md new file mode 100644 index 0000000000000000000000000000000000000000..e48b62a74fd991aae9a19979aad427ef8ae73938 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328c7.md @@ -0,0 +1,66 @@ +--- +id: 68ffb91507a5b645769328c7 +title: "Challenge 104: Recipe Scaler" +challengeType: 28 +dashedName: challenge-104 +--- + +# --description-- + +Given an array of recipe ingredients and a number to scale the recipe, return an array with the quantities scaled accordingly. + +- Each item in the given array will be a string in the format: `"quantity unit ingredient"`. For example `"2 C Flour"`. +- Scale the quantity by the given number. Do not include any trailing zeros and do not convert any units. +- Return the scaled items in the same order they are given. + +# --hints-- + +`scaleRecipe(["2 C Flour", "1.5 T Sugar"], 2)` should return `["4 C Flour", "3 T Sugar"]`. + +```js +assert.deepEqual(scaleRecipe(["2 C Flour", "1.5 T Sugar"], 2), ["4 C Flour", "3 T Sugar"]); +``` + +`scaleRecipe(["4 T Flour", "1 C Milk", "2 T Oil"], 1.5)` should return `["6 T Flour", "1.5 C Milk", "3 T Oil"]`. + +```js +assert.deepEqual(scaleRecipe(["4 T Flour", "1 C Milk", "2 T Oil"], 1.5), ["6 T Flour", "1.5 C Milk", "3 T Oil"]); +``` + +`scaleRecipe(["3 C Milk", "2 C Oats"], 0.5)` should return `["1.5 C Milk", "1 C Oats"]`. + +```js +assert.deepEqual(scaleRecipe(["3 C Milk", "2 C Oats"], 0.5), ["1.5 C Milk", "1 C Oats"]); +``` + +`scaleRecipe(["2 C All-purpose Flour", "1 t Baking Soda", "1 t Salt", "1 C Butter", "0.5 C Sugar", "0.5 C Brown Sugar", "1 t Vanilla Extract", "2 C Chocolate Chips"], 2.5)` should return `["5 C All-purpose Flour", "2.5 t Baking Soda", "2.5 t Salt", "2.5 C Butter", "1.25 C Sugar", "1.25 C Brown Sugar", "2.5 t Vanilla Extract", "5 C Chocolate Chips"]`. + +```js +assert.deepEqual(scaleRecipe(["2 C All-purpose Flour", "1 t Baking Soda", "1 t Salt", "1 C Butter", "0.5 C Sugar", "0.5 C Brown Sugar", "1 t Vanilla Extract", "2 C Chocolate Chips"], 2.5), ["5 C All-purpose Flour", "2.5 t Baking Soda", "2.5 t Salt", "2.5 C Butter", "1.25 C Sugar", "1.25 C Brown Sugar", "2.5 t Vanilla Extract", "5 C Chocolate Chips"]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function scaleRecipe(ingredients, scale) { + + return ingredients; +} +``` + +# --solutions-- + +```js +function scaleRecipe(ingredients, scale) { + return ingredients.map(item => { + const [quantityStr, unit, ...rest] = item.split(" "); + const ingredientName = rest.join(" "); + + const quantity = parseFloat(quantityStr) * scale; + + return `${quantity} ${unit} ${ingredientName}`; + }); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328c8.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328c8.md new file mode 100644 index 0000000000000000000000000000000000000000..7be5b9dc7db138d1824c0f14f55e4c58fa321bcd --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328c8.md @@ -0,0 +1,65 @@ +--- +id: 68ffb91507a5b645769328c8 +title: "Challenge 105: Character Count" +challengeType: 28 +dashedName: challenge-105 +--- + +# --description-- + +Given a sentence string, return an array with a count of each character in alphabetical order. + +- Treat upper and lowercase letters as the same letter when counting. +- Ignore numbers, spaces, punctuation, etc. +- Return the count and letter in the format `"letter count"`. For instance, `"a 3"`. +- All returned letters should be lowercase. +- Do not return a count of letters that are not in the given string. + +# --hints-- + +`countCharacters("hello world")` should return `["d 1", "e 1", "h 1", "l 3", "o 2", "r 1", "w 1"]`. + +```js +assert.deepEqual(countCharacters("hello world"), ["d 1", "e 1", "h 1", "l 3", "o 2", "r 1", "w 1"]); +``` + +`countCharacters("I love coding challenges!")` should return `["a 1", "c 2", "d 1", "e 3", "g 2", "h 1", "i 2", "l 3", "n 2", "o 2", "s 1", "v 1"]`. + +```js +assert.deepEqual(countCharacters("I love coding challenges!"), ["a 1", "c 2", "d 1", "e 3", "g 2", "h 1", "i 2", "l 3", "n 2", "o 2", "s 1", "v 1"]); +``` + +`countCharacters("// TODO: Complete this challenge ASAP!")` should return `["a 3", "c 2", "d 1", "e 4", "g 1", "h 2", "i 1", "l 3", "m 1", "n 1", "o 3", "p 2", "s 2", "t 3"]`. + +```js +assert.deepEqual(countCharacters("// TODO: Complete this challenge ASAP!"), ["a 3", "c 2", "d 1", "e 4", "g 1", "h 2", "i 1", "l 3", "m 1", "n 1", "o 3", "p 2", "s 2", "t 3"]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function countCharacters(sentence) { + + return sentence; +} +``` + +# --solutions-- + +```js +function countCharacters(sentence) { + const counts = {}; + + for (let char of sentence.toLowerCase()) { + if (char >= "a" && char <= "z") { + counts[char] = (counts[char] || 0) + 1; + } + } + + return Object.keys(counts) + .sort() + .map(letter => `${letter} ${counts[letter]}`); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328c9.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328c9.md new file mode 100644 index 0000000000000000000000000000000000000000..f8624f824332aa79f7bec65a99b6a127ed2bb7d7 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328c9.md @@ -0,0 +1,75 @@ +--- +id: 68ffb91507a5b645769328c9 +title: "Challenge 106: Message Validator" +challengeType: 28 +dashedName: challenge-106 +--- + +# --description-- + +Given a message string and a validation string, determine if the message is valid. + +- A message is valid if each word in the message starts with the corresponding letter in the validation string, in order. +- Letters are case-insensitive. +- Words in the message are separated by single spaces. + +# --hints-- + +`isValidMessage("hello world", "hw")` should return `true`. + +```js +assert.isTrue(isValidMessage("hello world", "hw")); +``` + +`isValidMessage("ALL CAPITAL LETTERS", "acl")` should return `true`. + +```js +assert.isTrue(isValidMessage("ALL CAPITAL LETTERS", "acl")); +``` + +`isValidMessage("Coding challenge are boring.", "cca")` should return `false`. + +```js +assert.isFalse(isValidMessage("Coding challenge are boring.", "cca")); +``` + +`isValidMessage("The quick brown fox jumps over the lazy dog.", "TQBFJOTLD")` should return `true`. + +```js +assert.isTrue(isValidMessage("The quick brown fox jumps over the lazy dog.", "TQBFJOTLD")); +``` + +`isValidMessage("The quick brown fox jumps over the lazy dog.", "TQBFJOTLDT")` should return `false`. + +```js +assert.isFalse(isValidMessage("The quick brown fox jumps over the lazy dog.", "TQBFJOTLDT")); +``` + +# --seed-- + +## --seed-contents-- + +```js +function isValidMessage(message, validator) { + + return message; +} +``` + +# --solutions-- + +```js +function isValidMessage(message, validation) { + const words = message.split(" "); + + if (words.length !== validation.length) return false; + + for (let i = 0; i < words.length; i++) { + if (words[i][0].toLowerCase() !== validation[i].toLowerCase()) { + return false; + } + } + + return true; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328ca.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328ca.md new file mode 100644 index 0000000000000000000000000000000000000000..784aba8e268a82717b7ad4069de2e138b571cd7d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328ca.md @@ -0,0 +1,77 @@ +--- +id: 68ffb91507a5b645769328ca +title: "Challenge 107: FizzBuzz" +challengeType: 28 +dashedName: challenge-107 +--- + +# --description-- + +Given an integer (`n`), return an array of integers from `1` to `n` (inclusive), replacing numbers that are multiple of: + +- 3 with `"Fizz"`. +- 5 with `"Buzz"`. +- 3 and 5 with `"FizzBuzz"`. + +# --hints-- + +`fizzBuzz(2)` should return `[1, 2]`. + +```js +assert.deepEqual(fizzBuzz(2), [1, 2]); +``` + +`fizzBuzz(4)` should return `[1, 2, "Fizz", 4]`. + +```js +assert.deepEqual(fizzBuzz(4), [1, 2, "Fizz", 4]); +``` + +`fizzBuzz(8)` should return `[1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8]`. + +```js +assert.deepEqual(fizzBuzz(8), [1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8]); +``` + +`fizzBuzz(20)` should return `[1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz", 16, 17, "Fizz", 19, "Buzz"]`. + +```js +assert.deepEqual(fizzBuzz(20), [1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz", 16, 17, "Fizz", 19, "Buzz"]); +``` + +`fizzBuzz(50)` should return `[1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz", 16, 17, "Fizz", 19, "Buzz", "Fizz", 22, 23, "Fizz", "Buzz", 26, "Fizz", 28, 29, "FizzBuzz", 31, 32, "Fizz", 34, "Buzz", "Fizz", 37, 38, "Fizz", "Buzz", 41, "Fizz", 43, 44, "FizzBuzz", 46, 47, "Fizz", 49, "Buzz"]`. + +```js +assert.deepEqual(fizzBuzz(50), [1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz", 16, 17, "Fizz", 19, "Buzz", "Fizz", 22, 23, "Fizz", "Buzz", 26, "Fizz", 28, 29, "FizzBuzz", 31, 32, "Fizz", 34, "Buzz", "Fizz", 37, 38, "Fizz", "Buzz", 41, "Fizz", 43, 44, "FizzBuzz", 46, 47, "Fizz", 49, "Buzz"]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function fizzBuzz(n) { + + return n; +} +``` + +# --solutions-- + +```js +function fizzBuzz(n) { + const result = []; + for (let i = 1; i <= n; i++) { + if (i % 15 === 0) { + result.push("FizzBuzz"); + } else if (i % 3 === 0) { + result.push("Fizz"); + } else if (i % 5 === 0) { + result.push("Buzz"); + } else { + result.push(i); + } + } + return result; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328cb.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328cb.md new file mode 100644 index 0000000000000000000000000000000000000000..c6baf34a80c4284b506146754a785d8fa573f2d6 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328cb.md @@ -0,0 +1,86 @@ +--- +id: 68ffb91507a5b645769328cb +title: "Challenge 108: BuzzFizz" +challengeType: 28 +dashedName: challenge-108 +--- + +# --description-- + +Given an array, determine if it is a correct FizzBuzz sequence from 1 to the last item in the array. A sequence is correct if: + +- Numbers that are multiples of 3 are replaced with "Fizz" +- Numbers that are multiples of 5 are replaced with "Buzz" +- Numbers that are multiples of both 3 and 5 are replaced with "FizzBuzz" +- All other numbers remain as integers in ascending order, starting from 1. +- The array must start at 1 and have no missing or extra elements. + +# --hints-- + +`isFizzBuzz([1, 2, "Fizz", 4])` should return `true`. + +```js +assert.isTrue(isFizzBuzz([1, 2, "Fizz", 4])); +``` + +`isFizzBuzz([1, 2, 3, 4])` should return `false`. + +```js +assert.isFalse(isFizzBuzz([1, 2, 3, 4])); +``` + +`isFizzBuzz([1, 2, "Fizz", 4, "Buzz", 7])` should return `false`. + +```js +assert.isFalse(isFizzBuzz([1, 2, "Fizz", 4, "Buzz", 7])); +``` + +`isFizzBuzz([1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, "FizzBuzz"])` should return `false`. + +```js +assert.isFalse(isFizzBuzz([1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, "FizzBuzz"])); +``` + +`isFizzBuzz([1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, "Fizz"])` should return `false`. + +```js +assert.isFalse(isFizzBuzz([1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, "Fizz"])); +``` + +`isFizzBuzz([1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, "Buzz"])` should return `false`. + +```js +assert.isFalse(isFizzBuzz([1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, "Buzz"])); +``` + +`isFizzBuzz([1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz", 16, 17, "Fizz", 19, "Buzz", "Fizz", 22, 23, "Fizz", "Buzz", 26, "Fizz", 28, 29, "FizzBuzz", 31, 32, "Fizz", 34, "Buzz", "Fizz", 37, 38, "Fizz", "Buzz", 41, "Fizz", 43, 44, "FizzBuzz", 46, 47, "Fizz", 49, "Buzz"])` should return `true`. + +```js +assert.isTrue(isFizzBuzz([1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz", 16, 17, "Fizz", 19, "Buzz", "Fizz", 22, 23, "Fizz", "Buzz", 26, "Fizz", 28, 29, "FizzBuzz", 31, 32, "Fizz", 34, "Buzz", "Fizz", 37, 38, "Fizz", "Buzz", 41, "Fizz", 43, 44, "FizzBuzz", 46, 47, "Fizz", 49, "Buzz"])); +``` + +# --seed-- + +## --seed-contents-- + +```js +function isFizzBuzz(sequence) { + + return sequence; +} +``` + +# --solutions-- + +```js +function isFizzBuzz(sequence) { + for (let i = 0; i < sequence.length; i++) { + const n = i + 1; + if (n % 15 === 0 && sequence[i] !== "FizzBuzz") return false; + if (n % 3 === 0 && n % 5 !== 0 && sequence[i] !== "Fizz") return false; + if (n % 5 === 0 && n % 3 !== 0 && sequence[i] !== "Buzz") return false; + if (n % 3 !== 0 && n % 5 !== 0 && sequence[i] !== n) return false; + } + return true; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328cc.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328cc.md new file mode 100644 index 0000000000000000000000000000000000000000..cfcb725527ada46b3b978fd4b6cd0cc78b0306eb --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68ffb91507a5b645769328cc.md @@ -0,0 +1,78 @@ +--- +id: 68ffb91507a5b645769328cc +title: "Challenge 109: What's My Age Again?" +challengeType: 28 +dashedName: challenge-109 +--- + +# --description-- + +Given the date of someone's birthday in the format `YYYY-MM-DD`, return the person's age as of November 27th, 2025. + +- Assume all birthdays are valid dates before November 27th, 2025. +- Return the age as an integer. +- Be sure to account for whether the person has already had their birthday in 2025. + +# --hints-- + +`calculateAge("2000-11-20")` should return `25`. + +```js +assert.equal(calculateAge("2000-11-20"), 25); +``` + +`calculateAge("2000-12-01")` should return `24`. + +```js +assert.equal(calculateAge("2000-12-01"), 24); +``` + +`calculateAge("2014-10-25")` should return `11`. + +```js +assert.equal(calculateAge("2014-10-25"), 11); +``` + +`calculateAge("1994-01-06")` should return `31`. + +```js +assert.equal(calculateAge("1994-01-06"), 31); +``` + +`calculateAge("1994-12-14")` should return `30`. + +```js +assert.equal(calculateAge("1994-12-14"), 30); +``` + +# --seed-- + +## --seed-contents-- + +```js +function calculateAge(birthday) { + + return birthday; +} +``` + +# --solutions-- + +```js +function calculateAge(birthday) { + const today = new Date("2025-11-27"); + const [year, month, day] = birthday.split("-").map(Number); + const birthDate = new Date(year, month - 1, day); + + let age = today.getFullYear() - birthDate.getFullYear(); + + if ( + today.getMonth() < birthDate.getMonth() || + (today.getMonth() === birthDate.getMonth() && today.getDate() < birthDate.getDate()) + ) { + age--; + } + + return age; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629efb.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629efb.md new file mode 100644 index 0000000000000000000000000000000000000000..0e196dea7e725365a469cd46d6a861cdd68744b6 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629efb.md @@ -0,0 +1,103 @@ +--- +id: 69162d64f96574d9bb629efb +title: "Challenge 110: Word Guesser" +challengeType: 28 +dashedName: challenge-110 +--- + +# --description-- + +Given two strings of the same length, a secret word and a guess, compare the guess to the secret word using the following rules: + +- The secret word and guess will only consist of uppercase letters (`"A"` to `"Z"`); +- For each letter in the guess, replace it with a number according to how it matches the secret word: + - `"2"` if the letter is in the secret word and in the correct position. + - `"1"` if the letter is in the secret word but in the wrong position. + - `"0"` if the letter is not in the secret word. +- Each letter in the secret word can be used at most once. +- Exact matches (`"2"`) are assigned first, then partial matches (`"1"`) are assigned from left to right for remaining letters. +- If a letter occurs multiple times in the guess, it can only match as many times as it appears in the secret word. + +For example, given a secret word of `"APPLE"` and a guess of `"POPPA"`, return `"10201"`: + +The first `"P"` is not in the correct location (`"1"`), the `"O"` isn't in the secret word (`"0"`), the second `"P"` is in the correct location (`"2"`), the third `"P"` is a zero (`"0"`) because the two `"P"`'s in the secret word have been used, and the `"A"` is not in the correct location (`"1"`). + +# --hints-- + +`compare("APPLE", "POPPA")` should return `"10201"`. + +```js +assert.equal(compare("APPLE", "POPPA"), "10201"); +``` + +`compare("REACT", "TRACE")` should return `"11221"`. + +```js +assert.equal(compare("REACT", "TRACE"), "11221"); +``` + +`compare("DEBUGS", "PYTHON")` should return `"000000"`. + +```js +assert.equal(compare("DEBUGS", "PYTHON"), "000000"); +``` + +`compare("JAVASCRIPT", "TYPESCRIPT")` should return `"0000222222"`. + +```js +assert.equal(compare("JAVASCRIPT", "TYPESCRIPT"), "0000222222"); +``` + +`compare("ORANGE", "ROUNDS")` should return `"110200"`. + +```js +assert.equal(compare("ORANGE", "ROUNDS"), "110200"); +``` + +`compare("WIRELESS", "ETHERNET")` should return `"10021000"`. + +```js +assert.equal(compare("WIRELESS", "ETHERNET"), "10021000"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function compare(word, guess) { + + return word; +} +``` + +# --solutions-- + +```js +function compare(word, guess) { + const n = word.length; + let result = Array(n).fill("0"); + let used = Array(n).fill(false); + + for (let i = 0; i < n; i++) { + if (guess[i] === word[i]) { + result[i] = "2"; + used[i] = true; + } + } + + for (let i = 0; i < n; i++) { + if (result[i] === "0") { + for (let j = 0; j < n; j++) { + if (!used[j] && guess[i] === word[j]) { + result[i] = "1"; + used[j] = true; + break; + } + } + } + } + + return result.join(""); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629efc.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629efc.md new file mode 100644 index 0000000000000000000000000000000000000000..997036cbe5e0d30db0ca3ab3c05f328c60da13d2 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629efc.md @@ -0,0 +1,99 @@ +--- +id: 69162d64f96574d9bb629efc +title: "Challenge 111: Ball Trajectory" +challengeType: 28 +dashedName: challenge-111 +--- + +# --description-- + +Today's challenge is inspired by the video game Pong, which was released November 29, 1972. + +Given a matrix (array of arrays) that includes the location of the ball (`2`), and the previous location of the ball (`1`), return the matrix indices for the next location of the ball. + +- The ball always moves in a straight line. +- The movement direction is determined by how the ball moved from `1` to `2`. +- The edges of the matrix are considered walls. If the ball hits a: + - top or bottom wall, it bounces by reversing its vertical direction. + - left or right wall, it bounces by reversing its horizontal direction. + - corner, it bounces by reversing both directions. + +# --hints-- + +`getNextLocation([[0,0,0,0], [0,0,0,0], [0,1,2,0], [0,0,0,0]])` should return `[2, 3]`. + +```js +assert.deepEqual(getNextLocation([[0,0,0,0], [0,0,0,0], [0,1,2,0], [0,0,0,0]]), [2, 3]); +``` + +`getNextLocation([[0,0,0,0], [0,0,1,0], [0,2,0,0], [0,0,0,0]])` should return `[3, 0]`. + +```js +assert.deepEqual(getNextLocation([[0,0,0,0], [0,0,1,0], [0,2,0,0], [0,0,0,0]]), [3, 0]); +``` + +`getNextLocation([[0,2,0,0], [1,0,0,0], [0,0,0,0], [0,0,0,0]])` should return `[1, 2]`. + +```js +assert.deepEqual(getNextLocation([[0,2,0,0], [1,0,0,0], [0,0,0,0], [0,0,0,0]]), [1, 2]); +``` + +`getNextLocation([[0,0,0,0], [0,0,0,0], [2,0,0,0], [0,1,0,0]])` should return `[1, 1]`. + +```js +assert.deepEqual(getNextLocation([[0,0,0,0], [0,0,0,0], [2,0,0,0], [0,1,0,0]]), [1, 1]); +``` + +`getNextLocation([[0,0,0,0], [0,0,0,0], [0,0,1,0], [0,0,0,2]])` should return `[2, 2]`. + +```js +assert.deepEqual(getNextLocation([[0,0,0,0], [0,0,0,0], [0,0,1,0], [0,0,0,2]]), [2, 2]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getNextLocation(matrix) { + + return matrix; +} +``` + +# --solutions-- + +```js +function getNextLocation(matrix) { + let prev = null; + let curr = null; + + for (let row = 0; row < matrix.length; row++) { + for (let col = 0; col < matrix[0].length; col++) { + if (matrix[row][col] === 1) prev = [row, col]; + if (matrix[row][col] === 2) curr = [row, col]; + } + } + + const [prevRow, prevCol] = prev; + const [currRow, currCol] = curr; + + let dirX = currCol - prevCol; + let dirY = currRow - prevRow; + + let nextRow = currRow + dirY; + let nextCol = currCol + dirX; + + const maxRow = matrix.length - 1; + const maxCol = matrix[0].length - 1; + + + if (nextCol < 0 || nextCol > maxCol) dirX *= -1; + if (nextRow < 0 || nextRow > maxRow) dirY *= -1; + + nextRow = currRow + dirY; + nextCol = currCol + dirX; + + return [nextRow, nextCol]; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629efd.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629efd.md new file mode 100644 index 0000000000000000000000000000000000000000..dc6f158abbe897309b12d646d8e79cd8f08d090a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629efd.md @@ -0,0 +1,81 @@ +--- +id: 69162d64f96574d9bb629efd +title: "Challenge 112: AI Detector" +challengeType: 28 +dashedName: challenge-112 +--- + +# --description-- + +Today's challenge is inspired by the release of ChatGPT on November 30, 2022. + +Given a string of one or more sentences, determine if it was likely generated by AI using the following rules: + +- It contains two or more dashes (`-`). +- It contains two or more sets of parenthesis (`()`). Text can be within the parenthesis. +- It contains three or more words with 7 or more letters. + +- Words are separated by a single space and only consist of letters (`A-Z`). Don't include punctuation or other non-letters as part of a word. + +If the given sentence meets any of the rules above, return `"AI"`, otherwise, return `"Human"`. + +# --hints-- + +`detectAI("The quick brown fox jumped over the lazy dog.")` should return `"Human"`. + +```js +assert.equal(detectAI("The quick brown fox jumped over the lazy dog."), "Human"); +``` + +`detectAI("The hypersonic brown fox - jumped (over) the lazy dog.")` should return `"Human"`. + +```js +assert.equal(detectAI("The hypersonic brown fox - jumped (over) the lazy dog."), "Human"); +``` + +`detectAI("Yes - you're right! I made a mistake there - let me try again.")` should return `"AI"`. + +```js +assert.equal(detectAI("Yes - you're right! I made a mistake there - let me try again."), "AI"); +``` + +`detectAI("The extraordinary students were studying vivaciously.")` should return `"AI"`. + +```js +assert.equal(detectAI("The extraordinary students were studying vivaciously."), "AI"); +``` + +`detectAI("The (excited) student was (coding) in the library.")` should return `"AI"`. + +```js +assert.equal(detectAI("The (excited) student was (coding) in the library."), "AI"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function detectAI(text) { + + return text; +} +``` + +# --solutions-- + +```js +function detectAI(text) { + const dashCount = (text.match(/-/g) || []).length; + if (dashCount >= 2) return "AI"; + + const parenCount = (text.match(/\([^)]*\)/g) || []).length; + if (parenCount >= 2) return "AI"; + + const words = text.split(" "); + const longWordCount = words.filter(w => w.replace(/[^A-Za-z]/g, "").length >= 7).length; + if (longWordCount >= 3) return "AI"; + + return "Human"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629efe.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629efe.md new file mode 100644 index 0000000000000000000000000000000000000000..b972b66ae036f4605b1e53c289b06af1dac780d0 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629efe.md @@ -0,0 +1,67 @@ +--- +id: 69162d64f96574d9bb629efe +title: "Challenge 113: Miles to Kilometers" +challengeType: 28 +dashedName: challenge-113 +--- + +# --description-- + +Given a distance in miles as a number, return the equivalent distance in kilometers. + +- The input will always be a non-negative number. +- 1 mile equals 1.60934 kilometers. +- Round the result to two decimal places. +- Remove unnecessary trailing zeros from the rounded result. + +# --hints-- + +`convertToKm(1)` should return `1.61`. + +```js +assert.equal(convertToKm(1), 1.61); +``` + +`convertToKm(21)` should return `33.8`. + +```js +assert.equal(convertToKm(21), 33.8); +``` + +`convertToKm(3.5)` should return `5.63`. + +```js +assert.equal(convertToKm(3.5), 5.63); +``` + +`convertToKm(0)` should return `0`. + +```js +assert.equal(convertToKm(0), 0); +``` + +`convertToKm(0.621371)` should return `1`. + +```js +assert.equal(convertToKm(0.621371), 1); +``` + +# --seed-- + +## --seed-contents-- + +```js +function convertToKm(miles) { + + return miles; +} +``` + +# --solutions-- + +```js +function convertToKm(miles) { + const km = miles * 1.60934; + return Math.round(km * 100) / 100; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629eff.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629eff.md new file mode 100644 index 0000000000000000000000000000000000000000..b5e57e94b37741a5f6059c821df074070d1c0a94 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629eff.md @@ -0,0 +1,56 @@ +--- +id: 69162d64f96574d9bb629eff +title: "Challenge 114: Camel to Snake" +challengeType: 28 +dashedName: challenge-114 +--- + +# --description-- + +Given a string in camel case, return the snake case version of the string using the following rules: + +- The input string will contain only letters (`A-Z` and `a-z`) and will always start with a lowercase letter. +- Every uppercase letter in the camel case string starts a new word. +- Convert all letters to lowercase. +- Separate words with an underscore (`_`). + +# --hints-- + +`toSnake("helloWorld")` should return `"hello_world"`. + +```js +assert.equal(toSnake("helloWorld"), "hello_world"); +``` + +`toSnake("myVariableName")` should return `"my_variable_name"`. + +```js +assert.equal(toSnake("myVariableName"), "my_variable_name"); +``` + +`toSnake("freecodecampDailyChallenges")` should return `"freecodecamp_daily_challenges"`. + +```js +assert.equal(toSnake("freecodecampDailyChallenges"), "freecodecamp_daily_challenges"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function toSnake(camel) { + + return camel; +} +``` + +# --solutions-- + +```js +function toSnake(camel) { + return camel + .replace(/([A-Z])/g, "_$1") + .toLowerCase(); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629f00.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629f00.md new file mode 100644 index 0000000000000000000000000000000000000000..c0829c4a038455e152785025f2e32aa6e44aa1b5 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629f00.md @@ -0,0 +1,84 @@ +--- +id: 69162d64f96574d9bb629f00 +title: "Challenge 115: Markdown Ordered List Item Converter" +challengeType: 28 +dashedName: challenge-115 +--- + +# --description-- + +Given a string representing an ordered list item in Markdown, return the equivalent HTML string. + +A valid ordered list item in Markdown must: + +- Start with zero or more spaces, followed by +- A number (1 or greater) and a period (`.`), followed by +- At least one space, and then +- The list item text. + +If the string doesn't have the exact format above, return `"Invalid format"`. Otherwise, wrap the list item text in `li` tags and return the string. + +For example, given `"1. My item"`, return `"
  • My item
  • "`. + +Note: The console may not display HTML tags in strings when logging messages. Check the browser console to see logs with tags included. + +# --hints-- + +`convertListItem("1. My item")` should return `"
  • My item
  • "`. + +```js +assert.equal(convertListItem("1. My item"), "
  • My item
  • "); +``` + +`convertListItem(" 1. Another item")` should return `"
  • Another item
  • "`. + +```js +assert.equal(convertListItem(" 1. Another item"), "
  • Another item
  • "); +``` + +`convertListItem("1 . invalid item")` should return `"Invalid format"`. + +```js +assert.equal(convertListItem("1 . invalid item"), "Invalid format"); +``` + +`convertListItem("2. list item text")` should return `"
  • list item text
  • "`. + +```js +assert.equal(convertListItem("2. list item text"), "
  • list item text
  • "); +``` + +`convertListItem(". invalid again")` should return `"Invalid format"`. + +```js +assert.equal(convertListItem(". invalid again"), "Invalid format"); +``` + +`convertListItem("A. last invalid")` should return `"Invalid format"`. + +```js +assert.equal(convertListItem("A. last invalid"), "Invalid format"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function convertListItem(markdown) { + + return markdown; +} +``` + +# --solutions-- + +```js +function convertListItem(markdown) { + const match = markdown.match(/^\s*(\d+)\.\s+(.+)$/); + if (!match) return "Invalid format"; + + const text = match[2]; + return `
  • ${text}
  • `; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629f01.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629f01.md new file mode 100644 index 0000000000000000000000000000000000000000..2d26ed138ef4b2285687159a95ee6259ed2c7656 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629f01.md @@ -0,0 +1,80 @@ +--- +id: 69162d64f96574d9bb629f01 +title: "Challenge 116: Permutation Count" +challengeType: 28 +dashedName: challenge-116 +--- + +# --description-- + +Given a string, return the number of distinct permutations that can be formed from its characters. + +- A permutation is any reordering of the characters in the string. +- Do not count duplicate permutations. +- If the string contains repeated characters, repeated arrangements should only be counted once. +- The string will contain only letters (`A-Z`, `a-z`). + +For example, given `"abb"`, return `3` because there's three unique ways to arrange the letters: `"abb"`, `"bab"`, and `"bba"`. + +# --hints-- + +`countPermutations("abb")` should return `3`. + +```js +assert.equal(countPermutations("abb"), 3); +``` + +`countPermutations("abc")` should return `6`. + +```js +assert.equal(countPermutations("abc"), 6); +``` + +`countPermutations("racecar")` should return `630`. + +```js +assert.equal(countPermutations("racecar"), 630); +``` + +`countPermutations("freecodecamp")` should return `39916800`. + +```js +assert.equal(countPermutations("freecodecamp"), 39916800); +``` + +# --seed-- + +## --seed-contents-- + +```js +function countPermutations(str) { + + return str; +} +``` + +# --solutions-- + +```js +function countPermutations(str) { + const freq = {}; + for (const ch of str) { + freq[ch] = (freq[ch] || 0) + 1; + } + + function factorial(n) { + let result = 1; + for (let i = 2; i <= n; i++) result *= i; + return result; + } + + const n = str.length; + let result = factorial(n); + + for (const ch in freq) { + result /= factorial(freq[ch]); + } + + return result; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629f02.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629f02.md new file mode 100644 index 0000000000000000000000000000000000000000..e91f8704481be2e109f253fa5693d39e0570a00f --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629f02.md @@ -0,0 +1,69 @@ +--- +id: 69162d64f96574d9bb629f02 +title: "Challenge 117: Symmetric Difference" +challengeType: 28 +dashedName: challenge-117 +--- + +# --description-- + +Given two arrays, return a new array containing the symmetric difference of them. + +- The symmetric difference between two sets is the set of values that appear in either set, but not both. +- Return the values in the order they first appear in the input arrays. + +# --hints-- + +`difference([1, 2, 3], [3, 4, 5])` should return `[1, 2, 4, 5]`. + +```js +assert.deepEqual(difference([1, 2, 3], [3, 4, 5]), [1, 2, 4, 5]); +``` + +`difference(["a", "b"], ["c", "b"])` should return `["a", "c"]`. + +```js +assert.deepEqual(difference(["a", "b"], ["c", "b"]), ["a", "c"]); +``` + +`difference([1, "a", 2], [2, "b", "a"])` should return `[1, "b"]`. + +```js +assert.deepEqual(difference([1, "a", 2], [2, "b", "a"]), [1, "b"]); +``` + +`difference([1, 3, 5, 7, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9])` should return `[2, 4, 6, 8]`. + +```js +assert.deepEqual(difference([1, 3, 5, 7, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9]), [2, 4, 6, 8]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function difference(arr1, arr2) { + + return arr1; +} +``` + +# --solutions-- + +```js +function difference(arr1, arr2) { + const diff = []; + + for (const v of arr1) { + + if (!diff.includes(v) && !arr2.includes(v)) diff.push(v) + } + + for (const v of arr2) { + if (!diff.includes(v) && !arr1.includes(v)) diff.push(v) + } + + return diff; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629f03.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629f03.md new file mode 100644 index 0000000000000000000000000000000000000000..e2a9e3bdf5dcf308c94472d62fa4169566132ea4 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629f03.md @@ -0,0 +1,89 @@ +--- +id: 69162d64f96574d9bb629f03 +title: "Challenge 118: Date Formatter" +challengeType: 28 +dashedName: challenge-118 +--- + +# --description-- + +Given a date in the format `"Month day, year"`, return the date in the format `"YYYY-MM-DD"`. + +- The given month will be the full English month name. For example: `"January"`, `"February"`, etc. +- In the return value, pad the month and day with leading zeros if necessary to ensure two digits. + +For example, given `"December 6, 2025"`, return `"2025-12-06"`. + +# --hints-- + +`formatDate("December 6, 2025")` should return `"2025-12-06"`. + +```js +assert.equal(formatDate("December 6, 2025"), "2025-12-06"); +``` + +`formatDate("January 1, 2000")` should return `"2000-01-01"`. + +```js +assert.equal(formatDate("January 1, 2000"), "2000-01-01"); +``` + +`formatDate("November 11, 1111")` should return `"1111-11-11"`. + +```js +assert.equal(formatDate("November 11, 1111"), "1111-11-11"); +``` + +`formatDate("September 7, 512")` should return `"512-09-07"`. + +```js +assert.equal(formatDate("September 7, 512"), "512-09-07"); +``` + +`formatDate("May 4, 1950")` should return `"1950-05-04"`. + +```js +assert.equal(formatDate("May 4, 1950"), "1950-05-04"); +``` + +`formatDate("February 29, 1992")` should return `"1992-02-29"`. + +```js +assert.equal(formatDate("February 29, 1992"), "1992-02-29"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function formatDate(dateString) { + + return dateString; +} +``` + +# --solutions-- + +```js +function formatDate(dateString) { + const months = { + January: "01", + February: "02", + March: "03", + April: "04", + May: "05", + June: "06", + July: "07", + August: "08", + September: "09", + October: "10", + November: "11", + December: "12" + }; + + const [month, day, year] = dateString.replace(",", "").split(" "); + + return `${year}-${months[month]}-${day.padStart(2, "0")}`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629f04.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629f04.md new file mode 100644 index 0000000000000000000000000000000000000000..b858b30a8bbbb5d0841a2de5b042bc0075d87e4a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629f04.md @@ -0,0 +1,77 @@ +--- +id: 69162d64f96574d9bb629f04 +title: "Challenge 119: String Compression" +challengeType: 28 +dashedName: challenge-119 +--- + +# --description-- + +Given a string sentence, return a compressed version of the sentence where consecutive duplicate words are replaced by the word followed with the number of times it repeats in parentheses. + +- Only consecutive duplicates are compressed. +- Words are separated by single spaces. + +For example, given `"yes yes yes please"`, return `"yes(3) please"`. + +# --hints-- + +`compressString("yes yes yes please")` should return `"yes(3) please"`. + +```js +assert.equal(compressString("yes yes yes please"), "yes(3) please"); +``` + +`compressString("I have have have apples")` should return `"I have(3) apples"`. + +```js +assert.equal(compressString("I have have have apples"), "I have(3) apples"); +``` + +`compressString("one one three and to the the the the")` should return `"one(2) three and to the(4)"`. + +```js +assert.equal(compressString("one one three and to the the the the"), "one(2) three and to the(4)"); +``` + +`compressString("route route route route route route tee tee tee tee tee tee")` should return `"route(6) tee(6)"`. + +```js +assert.equal(compressString("route route route route route route tee tee tee tee tee tee"), "route(6) tee(6)"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function compressString(sentence) { + + return sentence; +} +``` + +# --solutions-- + +```js +function compressString(sentence) { + const words = sentence.split(" "); + const result = []; + let count = 1; + + for (let i = 0; i < words.length; i++) { + if (words[i] === words[i + 1]) { + count++; + } else { + if (count > 1) { + result.push(`${words[i]}(${count})`); + } else { + result.push(words[i]); + } + count = 1; + } + } + + return result.join(" "); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b480.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b480.md new file mode 100644 index 0000000000000000000000000000000000000000..3616c5e967f06d2b4d72399a90a45f636e759720 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b480.md @@ -0,0 +1,72 @@ +--- +id: 691b559495c5cb5a37b9b480 +title: "Challenge 120: Pounds to Kilograms" +challengeType: 28 +dashedName: challenge-120 +--- + +# --description-- + +Given a weight in pounds as a number, return the string `"(lbs) pounds equals (kgs) kilograms."`. + +- Replace `"(lbs)"` with the input number. +- Replace `"(kgs)"` with the input converted to kilograms, rounded to two decimals and always include two decimal places in the value. +- 1 pound equals 0.453592 kilograms. +- If the input is `1`, use `"pound"` instead of `"pounds"`. +- If the converted value is `1`, use `"kilogram"` instead of `"kilograms"`. + +# --hints-- + +`convertToKgs(1)` should return `"1 pound equals 0.45 kilograms."`. + +```js +assert.equal(convertToKgs(1), "1 pound equals 0.45 kilograms."); +``` + +`convertToKgs(0)` should return `"0 pounds equals 0.00 kilograms."`. + +```js +assert.equal(convertToKgs(0), "0 pounds equals 0.00 kilograms."); +``` + +`convertToKgs(100)` should return `"100 pounds equals 45.36 kilograms."`. + +```js +assert.equal(convertToKgs(100), "100 pounds equals 45.36 kilograms."); +``` + +`convertToKgs(2.5)` should return `"2.5 pounds equals 1.13 kilograms."`. + +```js +assert.equal(convertToKgs(2.5), "2.5 pounds equals 1.13 kilograms."); +``` + +`convertToKgs(2.20462)` should return `"2.20462 pounds equals 1.00 kilogram."`. + +```js +assert.equal(convertToKgs(2.20462), "2.20462 pounds equals 1.00 kilogram."); +``` + +# --seed-- + +## --seed-contents-- + +```js +function convertToKgs(lbs) { + return lbs; +} +``` + +# --solutions-- + +```js +function convertToKgs(lbs) { + const KG_PER_POUND = 0.453592; + const kgs = (lbs * KG_PER_POUND).toFixed(2); + + const poundWord = lbs === 1 ? "pound" : "pounds"; + const kilogramWord = kgs === "1.00" ? "kilogram" : "kilograms"; + + return `${lbs} ${poundWord} equals ${kgs} ${kilogramWord}.`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b481.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b481.md new file mode 100644 index 0000000000000000000000000000000000000000..0992da304b22ee043abc6e117b5457c4278df9a7 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b481.md @@ -0,0 +1,68 @@ +--- +id: 691b559495c5cb5a37b9b481 +title: "Challenge 121: Most Frequent" +challengeType: 28 +dashedName: challenge-121 +--- + +# --description-- + +Given an array of elements, return the element that appears most frequently. + +- There will always be a single most frequent element. + +# --hints-- + +`mostFrequent(["a", "b", "a", "c"])` should return `"a"`. + +```js +assert.equal(mostFrequent(["a", "b", "a", "c"]), "a"); +``` + +`mostFrequent([2, 3, 5, 2, 6, 3, 2, 7, 2, 9])` should return `2`. + +```js +assert.equal(mostFrequent([2, 3, 5, 2, 6, 3, 2, 7, 2, 9]), 2); +``` + +`mostFrequent([true, false, "false", "true", false])` should return `false`. + +```js +assert.isFalse(mostFrequent([true, false, "false", "true", false])); +``` + +`mostFrequent([40, 20, 70, 30, 10, 40, 10, 50, 40, 60])` should return `40`. + +```js +assert.equal(mostFrequent([40, 20, 70, 30, 10, 40, 10, 50, 40, 60]), 40); +``` + +# --seed-- + +## --seed-contents-- + +```js +function mostFrequent(arr) { + return arr; +} +``` + +# --solutions-- + +```js +function mostFrequent(arr) { + const freq = {}; + let maxCount = 0; + let mostElem = null; + + for (const el of arr) { + freq[el] = (freq[el] || 0) + 1; + if (freq[el] > maxCount) { + maxCount = freq[el]; + mostElem = el; + } + } + + return mostElem; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b482.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b482.md new file mode 100644 index 0000000000000000000000000000000000000000..2385fad17e4994b535508dc2226f5cbe9c9d4aff --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b482.md @@ -0,0 +1,72 @@ +--- +id: 691b559495c5cb5a37b9b482 +title: "Challenge 122: Markdown Bold Parser" +challengeType: 28 +dashedName: challenge-122 +--- + +# --description-- + +Given a string that may include some bold text in Markdown, return the equivalent HTML string. + +- Bold text in Markdown is any text that starts and ends with two asterisks (`**`) or two underscores (`__`). +- There cannot be any spaces between the text and the asterisks or underscores, but there can be + spaces in the text itself. +- Convert all bold occurrences to HTML `b` tags and return the string. + +For example, given `"**This is bold**"`, return `"This is bold"`. + +Note: The console may not display HTML tags in strings when logging messages. Check the browser console to see logs with tags included. + +# --hints-- + +`parseBold("**This is bold**")` should return `"This is bold"`. + +```js +assert.equal(parseBold("**This is bold**"), "This is bold"); +``` + +`parseBold("__This is also bold__")` should return `"This is also bold"`. + +```js +assert.equal(parseBold("__This is also bold__"), "This is also bold"); +``` + +`parseBold("**This is not bold **")` should return `"**This is not bold **"`. + +```js +assert.equal(parseBold("**This is not bold **"), "**This is not bold **"); +``` + +`parseBold("__ This is also not bold__")` should return `"__ This is also not bold__"`. + +```js +assert.equal(parseBold("__ This is also not bold__"), "__ This is also not bold__"); +``` + +`parseBold("The **quick** brown fox __jumps__ over the **lazy** dog.")` should return `"The quick brown fox jumps over the lazy dog."`. + +```js +assert.equal(parseBold("The **quick** brown fox __jumps__ over the **lazy** dog."), "The quick brown fox jumps over the lazy dog."); +``` + +# --seed-- + +## --seed-contents-- + +```js +function parseBold(markdown) { + return markdown; +} +``` + +# --solutions-- + +```js +function parseBold(markdown) { + markdown = markdown.replace(/\*\*(\S(?:.*?\S)?)\*\*/g, "$1"); + markdown = markdown.replace(/__(\S(?:.*?\S)?)__/g, "$1"); + + return markdown; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b483.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b483.md new file mode 100644 index 0000000000000000000000000000000000000000..53488b6d41c6857750feaadd19800846562767eb --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b483.md @@ -0,0 +1,103 @@ +--- +id: 691b559495c5cb5a37b9b483 +title: "Challenge 123: Roman Numeral Builder" +challengeType: 28 +dashedName: challenge-123 +--- + +# --description-- + +Given an integer, return its equivalent value in Roman numerals. + +Roman numerals use these symbols: + +| Symbol | Value | +| ------ | ----- | +| I | 1 | +| V | 5 | +| X | 10 | +| L | 50 | +| C | 100 | +| D | 500 | +| M | 1000 | + +Roman numerals are written from largest to smallest, left to right using the following rules: + +- Addition is used when a symbol is followed by one of equal or smaller value. For example, `18` is written as `XVIII` (10 + 5 + 1 + 1 + 1 = 18). +- Subtraction is used when a smaller symbol appears before a larger one, to represent 4 or 9 in any place value. For example, 19 is written as `XIX` (10 + (10 - 1)). +- No symbol may be repeated more than three times in a row. Subtraction is used when you would otherwise need to write a symbol more than three times in a row. So the largest number you can write is 3999. + +Here's one more example: given `1464`, return `"MCDLXIV"` (1000 + (500 - 100) + 50 + 10 + (5 - 1)). + +# --hints-- + +`toRoman(18)` should return `"XVIII"`. + +```js +assert.equal(toRoman(18), "XVIII"); +``` + +`toRoman(19)` should return `"XIX"`. + +```js +assert.equal(toRoman(19), "XIX"); +``` + +`toRoman(1464)` should return `"MCDLXIV"`. + +```js +assert.equal(toRoman(1464), "MCDLXIV"); +``` + +`toRoman(2025)` should return `"MMXXV"`. + +```js +assert.equal(toRoman(2025), "MMXXV"); +``` + +`toRoman(3999)` should return `"MMMCMXCIX"`. + +```js +assert.equal(toRoman(3999), "MMMCMXCIX"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function toRoman(num) { + return num; +} +``` + +# --solutions-- + +```js +function toRoman(num) { + const symbols = [ + ["M", 1000], + ["CM", 900], + ["D", 500], + ["CD", 400], + ["C", 100], + ["XC", 90], + ["L", 50], + ["XL", 40], + ["X", 10], + ["IX", 9], + ["V", 5], + ["IV", 4], + ["I", 1] + ]; + + let result = ""; + for (const [sym, val] of symbols) { + while (num >= val) { + result += sym; + num -= val; + } + } + return result; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b484.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b484.md new file mode 100644 index 0000000000000000000000000000000000000000..addbd3323bf4b16ce69e6ae52933a88f47b62098 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b484.md @@ -0,0 +1,76 @@ +--- +id: 691b559495c5cb5a37b9b484 +title: "Challenge 124: Inventory Update" +challengeType: 28 +dashedName: challenge-124 +--- + +# --description-- + +Given a 2D array representing the inventory of your store, and another 2D array representing a shipment you have received, return your updated inventory. + +- Each element in the arrays will have the format: `[quantity, "item"]`, where `quantity` is an integer and `"item"` is a string. +- Update items in the inventory by adding the quantity of any matching items from the shipment. +- If a received item does not exist in the current inventory, add it as a new entry to the end of the inventory. +- Return inventory in the order it was given with new items at the end in the order they appear in the shipment. + +For example, given an inventory of `[[2, "apples"], [5, "bananas"]]` and a shipment of `[[1, "apples"], [3, "bananas"]]`, return `[[3, "apples"], [8, "bananas"]]`. + +# --hints-- + +`updateInventory([[2, "apples"], [5, "bananas"]], [[1, "apples"], [3, "bananas"]])` should return `[[3, "apples"], [8, "bananas"]]`. + +```js +assert.deepEqual(updateInventory([[2, "apples"], [5, "bananas"]], [[1, "apples"], [3, "bananas"]]), [[3, "apples"], [8, "bananas"]]); +``` + +`updateInventory([[2, "apples"], [5, "bananas"]], [[1, "apples"], [3, "bananas"], [4, "oranges"]])` should return `[[3, "apples"], [8, "bananas"], [4, "oranges"]]`. + +```js +assert.deepEqual(updateInventory([[2, "apples"], [5, "bananas"]], [[1, "apples"], [3, "bananas"], [4, "oranges"]]), [[3, "apples"], [8, "bananas"], [4, "oranges"]]); +``` + +`updateInventory([], [[10, "apples"], [30, "bananas"], [20, "oranges"]])` should return `[[10, "apples"], [30, "bananas"], [20, "oranges"]]`. + +```js +assert.deepEqual(updateInventory([], [[10, "apples"], [30, "bananas"], [20, "oranges"]]), [[10, "apples"], [30, "bananas"], [20, "oranges"]]); +``` + +`updateInventory([[0, "Bowling Ball"], [0, "Dirty Socks"], [0, "Hair Pin"], [0, "Microphone"]], [[1, "Hair Pin"], [1, "Half-Eaten Apple"], [1, "Bowling Ball"], [1, "Toothpaste"]])` should return `[[1, "Bowling Ball"], [0, "Dirty Socks"], [1, "Hair Pin"], [0, "Microphone"], [1, "Half-Eaten Apple"], [1, "Toothpaste"]]`. + +```js +assert.deepEqual(updateInventory([[0, "Bowling Ball"], [0, "Dirty Socks"], [0, "Hair Pin"], [0, "Microphone"]], [[1, "Hair Pin"], [1, "Half-Eaten Apple"], [1, "Bowling Ball"], [1, "Toothpaste"]]), [[1, "Bowling Ball"], [0, "Dirty Socks"], [1, "Hair Pin"], [0, "Microphone"], [1, "Half-Eaten Apple"], [1, "Toothpaste"]]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function updateInventory(inventory, shipment) { + return inventory; +} +``` + +# --solutions-- + +```js +function updateInventory(inventory, shipment) { + const inventoryMap = new Map(); + inventory.forEach(([qty, item], index) => { + inventoryMap.set(item, index); + }); + + shipment.forEach(([qty, item]) => { + if (inventoryMap.has(item)) { + const index = inventoryMap.get(item); + inventory[index][0] += qty; + } else { + inventory.push([qty, item]); + inventoryMap.set(item, inventory.length - 1); + } + }); + + return inventory; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b485.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b485.md new file mode 100644 index 0000000000000000000000000000000000000000..b94b4291d3bdf02fd697e20342f0ba9904c89b87 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b485.md @@ -0,0 +1,123 @@ +--- +id: 691b559495c5cb5a37b9b485 +title: "Challenge 125: Game of Life" +challengeType: 28 +dashedName: challenge-125 +--- + +# --description-- + +Given a matrix (array of arrays) representing the current state in Conway's Game of Life, return the next state of the matrix using these rules: + +- Each cell is either `1` (alive) or `0` (dead). +- A cell's neighbors are the up to eight surrounding cells (vertically, horizontally, and diagonally). +- Cells on the edges have fewer than eight neighbors. + +Rules for updating each cell: + +- Any live cell with fewer than two live neighbors dies (underpopulation). +- Any live cell with two or three live neighbors lives on. +- Any live cell with more than three live neighbors dies (overpopulation). +- Any dead cell with exactly three live neighbors becomes alive (reproduction). + +For example, given: + +```json +[ + [0, 1, 0], + [0, 1, 1], + [1, 1, 0] +] +``` + +return: + +```json +[ + [0, 1, 1], + [0, 0, 1], + [1, 1, 1] +] +``` + +Each cell updates according to the number of live neighbors. For instance, `[0][0]` stays dead (2 live neighbors), `[0][1]` stays alive (2 live neighbors), `[0][2]` dies (3 live neighbors), and so on. + +# --hints-- + +`gameOfLife([[0, 1, 0], [0, 1, 1], [1, 1, 0]])` should return `[[0, 1, 1], [0, 0, 1], [1, 1, 1]]`. + +```js +assert.deepEqual(gameOfLife([[0, 1, 0], [0, 1, 1], [1, 1, 0]]), [[0, 1, 1], [0, 0, 1], [1, 1, 1]]); +``` + +`gameOfLife([[1, 1, 0, 0], [1, 0, 1, 0], [0, 1, 1, 1], [0, 0, 1, 0]])` should return `[[1, 1, 0, 0], [1, 0, 0, 1], [0, 0, 0, 1], [0, 1, 1, 1]]`. + +```js +assert.deepEqual(gameOfLife([[1, 1, 0, 0], [1, 0, 1, 0], [0, 1, 1, 1], [0, 0, 1, 0]]), [[1, 1, 0, 0], [1, 0, 0, 1], [0, 0, 0, 1], [0, 1, 1, 1]]); +``` + +`gameOfLife([[1, 0, 0], [0, 1, 0], [0, 0, 1]])` should return `[[0, 0, 0], [0, 1, 0], [0, 0, 0]]`. + +```js +assert.deepEqual(gameOfLife([[1, 0, 0], [0, 1, 0], [0, 0, 1]]), [[0, 0, 0], [0, 1, 0], [0, 0, 0]]); +``` + +`gameOfLife([[0, 1, 1, 0], [1, 1, 0, 1], [0, 1, 1, 0], [0, 0, 1, 0]])` should return `[[1, 1, 1, 0], [1, 0, 0, 1], [1, 0, 0, 1], [0, 1, 1, 0]]`. + +```js +assert.deepEqual(gameOfLife([[0, 1, 1, 0], [1, 1, 0, 1], [0, 1, 1, 0], [0, 0, 1, 0]]), [[1, 1, 1, 0], [1, 0, 0, 1], [1, 0, 0, 1], [0, 1, 1, 0]]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function gameOfLife(grid) { + return grid; +} +``` + +# --solutions-- + +```js +function gameOfLife(grid) { + const rows = grid.length; + const cols = grid[0].length; + + const countLiveNeighbors = (r, c) => { + let count = 0; + for (let i = r - 1; i <= r + 1; i++) { + for (let j = c - 1; j <= c + 1; j++) { + if ( + i >= 0 && + i < rows && + j >= 0 && + j < cols && + !(i === r && j === c) && + grid[i][j] === 1 + ) { + count++; + } + } + } + return count; + }; + + const next = grid.map(row => [...row]); + + for (let r = 0; r < rows; r++) { + for (let c = 0; c < cols; c++) { + const liveNeighbors = countLiveNeighbors(r, c); + + if (grid[r][c] === 1) { + if (liveNeighbors < 2 || liveNeighbors > 3) next[r][c] = 0; + } else { + if (liveNeighbors === 3) next[r][c] = 1; + } + } + } + + return next; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b486.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b486.md new file mode 100644 index 0000000000000000000000000000000000000000..4ff92162fbd2ab6e890cdb0232a64635b7fd679d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b486.md @@ -0,0 +1,61 @@ +--- +id: 691b559495c5cb5a37b9b486 +title: "Challenge 126: Capitalize It" +challengeType: 28 +dashedName: challenge-126 +--- + +# --description-- + +Given a string title, return a new string formatted in title case using the following rules: + +- Capitalize the first letter of each word. +- Make all other letters in each word lowercase. +- Words are always separated by a single space. + +# --hints-- + +`titleCase("hello world")` should return `"Hello World"`. + +```js +assert.equal(titleCase("hello world"), "Hello World"); +``` + +`titleCase("the quick brown fox")` should return `"The Quick Brown Fox"`. + +```js +assert.equal(titleCase("the quick brown fox"), "The Quick Brown Fox"); +``` + +`titleCase("JAVASCRIPT AND PYTHON")` should return `"Javascript And Python"`. + +```js +assert.equal(titleCase("JAVASCRIPT AND PYTHON"), "Javascript And Python"); +``` + +`titleCase("AvOcAdO tOAst fOr brEAkfAst")` should return `"Avocado Toast For Breakfast"`. + +```js +assert.equal(titleCase("AvOcAdO tOAst fOr brEAkfAst"), "Avocado Toast For Breakfast"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function titleCase(title) { + return title; +} +``` + +# --solutions-- + +```js +function titleCase(title) { + return title + .split(" ") + .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) + .join(" "); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b487.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b487.md new file mode 100644 index 0000000000000000000000000000000000000000..8a4e4e01e84e22e1e35b521020ddfbf9a37dcaf8 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b487.md @@ -0,0 +1,83 @@ +--- +id: 691b559495c5cb5a37b9b487 +title: "Challenge 127: Speed Check" +challengeType: 28 +dashedName: challenge-127 +--- + +# --description-- + +Given the speed you are traveling in miles per hour (MPH), and a speed limit in kilometers per hour (KPH), determine whether you are speeding and if you will get a warning or a ticket. + +- 1 mile equals 1.60934 kilometers. +- If you are traveling less than or equal to the speed limit, return `"Not Speeding"`. +- If you are traveling 5 KPH or less over the speed limit, return `"Warning"`. +- If you are traveling more than 5 KPH over the speed limit, return `"Ticket"`. + +# --hints-- + +`speedCheck(30, 70)` should return `"Not Speeding"`. + +```js +assert.equal(speedCheck(30, 70), "Not Speeding"); +``` + +`speedCheck(40, 60)` should return `"Warning"`. + +```js +assert.equal(speedCheck(40, 60), "Warning"); +``` + +`speedCheck(40, 65)` should return `"Not Speeding"`. + +```js +assert.equal(speedCheck(40, 65), "Not Speeding"); +``` + +`speedCheck(60, 90)` should return `"Ticket"`. + +```js +assert.equal(speedCheck(60, 90), "Ticket"); +``` + +`speedCheck(65, 100)` should return `"Warning"`. + +```js +assert.equal(speedCheck(65, 100), "Warning"); +``` + +`speedCheck(88, 40)` should return `"Ticket"`. + +```js +assert.equal(speedCheck(88, 40), "Ticket"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function speedCheck(speedMph, speedLimitKph) { + return speedMph; +} +``` + +# --solutions-- + +```js +function speedCheck(speedMph, speedLimitKph) { + const speedKph = speedMph * 1.60934; + + if (speedKph <= speedLimitKph) { + return "Not Speeding"; + } + + const over = speedKph - speedLimitKph; + + if (over <= 5) { + return "Warning"; + } + + return "Ticket"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b488.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b488.md new file mode 100644 index 0000000000000000000000000000000000000000..9e4fee43aeea0e64620937388a695b672f047fef --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b488.md @@ -0,0 +1,76 @@ +--- +id: 691b559495c5cb5a37b9b488 +title: "Challenge 128: Consonant Count" +challengeType: 28 +dashedName: challenge-128 +--- + +# --description-- + +Given a string and a target number, determine whether the string contains exactly the target number of consonants. + +- Consonants are all alphabetic characters except `"a"`, `"e"`, `"i"`, `"o"`, and `"u"` in any case. +- Ignore digits, punctuation, spaces, and other non-letter characters when counting. + +# --hints-- + +`hasConsonantCount("helloworld", 7)` should return `true`. + +```js +assert.isTrue(hasConsonantCount("helloworld", 7)); +``` + +`hasConsonantCount("eieio", 5)` should return `false`. + +```js +assert.isFalse(hasConsonantCount("eieio", 5)); +``` + +`hasConsonantCount("freeCodeCamp Rocks!", 11)` should return `true`. + +```js +assert.isTrue(hasConsonantCount("freeCodeCamp Rocks!", 11)); +``` + +`hasConsonantCount("Th3 Qu!ck Br0wn F0x Jump5 0ver Th3 L@zy D0g.", 24)` should return `false`. + +```js +assert.isFalse( + hasConsonantCount("Th3 Qu!ck Br0wn F0x Jump5 0ver Th3 L@zy D0g.", 24) +); +``` + +`hasConsonantCount("Th3 Qu!ck Br0wn F0x Jump5 0ver Th3 L@zy D0g.", 23)` should return `true`. + +```js +assert.isTrue( + hasConsonantCount("Th3 Qu!ck Br0wn F0x Jump5 0ver Th3 L@zy D0g.", 23) +); +``` + +# --seed-- + +## --seed-contents-- + +```js +function hasConsonantCount(text, target) { + return text; +} +``` + +# --solutions-- + +```js +function hasConsonantCount(text, target) { + const vowels = new Set(["a", "e", "i", "o", "u"]); + let count = 0; + + for (const char of text.toLowerCase()) { + if (/[a-z]/.test(char) && !vowels.has(char)) { + count++; + } + } + + return count === target; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b489.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b489.md new file mode 100644 index 0000000000000000000000000000000000000000..7e0695b5bde7ef221c833dfa594efe7d4f255808 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b489.md @@ -0,0 +1,65 @@ +--- +id: 691b559495c5cb5a37b9b489 +title: "Challenge 129: Markdown Blockquote Parser" +challengeType: 28 +dashedName: challenge-129 +--- + +# --description-- + +Given a string that includes a blockquote in Markdown, return the equivalent HTML string. + +A blockquote in Markdown is any line that: + +- Starts with zero or more spaces +- Followed by a greater-than sign (`>`) +- Then, one or more spaces +- And finally, the blockquote text. + +Return the blockquote text surrounded by opening and closing HTML `blockquote` tags. + +For example, given `"> This is a quote"`, return `
    This is a quote
    `. + +Note: The console may not display HTML tags in strings when logging messages. Check the browser console to see logs with tags included. + +# --hints-- + +`parseBlockquote("> This is a quote")` should return `"
    This is a quote
    "`. + +```js +assert.equal(parseBlockquote("> This is a quote"), "
    This is a quote
    "); +``` + +`parseBlockquote(" > This is also a quote")` should return `"
    This is also a quote
    "`. + +```js +assert.equal(parseBlockquote(" > This is also a quote"), "
    This is also a quote
    "); +``` + +`parseBlockquote(" > So Is This")` should return `"
    So Is This
    "`. + +```js +assert.equal(parseBlockquote(" > So Is This"), "
    So Is This
    "); +``` + +# --seed-- + +## --seed-contents-- + +```js +function parseBlockquote(markdown) { + return markdown; +} +``` + +# --solutions-- + +```js +function parseBlockquote(markdown) { + const blockquoteRegex = /^\s*>\s+(.+)$/; + const match = markdown.match(blockquoteRegex); + + const text = match[1]; + return `
    ${text}
    `; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b5597f0f3e85a588a5c94.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b5597f0f3e85a588a5c94.md new file mode 100644 index 0000000000000000000000000000000000000000..f3a8913f1956d41e61f748ebc027fc9caa177872 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b5597f0f3e85a588a5c94.md @@ -0,0 +1,78 @@ +--- +id: 691b5597f0f3e85a588a5c94 +title: "Challenge 130: Checkerboard" +challengeType: 28 +dashedName: challenge-130 +--- + +# --description-- + +Given an array with two numbers, the first being the number of rows and the second being the number of columns, return a matrix (an array of arrays) filled with `"X"` and `"O"` characters of the given size. + +- The characters should alternate like a checkerboard. +- The top-left cell must always be `"X"`. + +For example, given `[3, 3]`, return: + +```json +[ + ["X", "O", "X"], + ["O", "X", "O"], + ["X", "O", "X"] +] +``` + +# --hints-- + +`createBoard([3, 3])` should return `[["X", "O", "X"], ["O", "X", "O"], ["X", "O", "X"]]`. + +```js +assert.deepEqual(createBoard([3, 3]), [["X", "O", "X"], ["O", "X", "O"], ["X", "O", "X"]]); +``` + +`createBoard([6, 1])` should return `[["X"], ["O"], ["X"], ["O"], ["X"], ["O"]]`. + +```js +assert.deepEqual(createBoard([6, 1]), [["X"], ["O"], ["X"], ["O"], ["X"], ["O"]]); +``` + +`createBoard([2, 10])` should return `[["X", "O", "X", "O", "X", "O", "X", "O", "X", "O"], ["O", "X", "O", "X", "O", "X", "O", "X", "O", "X"]]`. + +```js +assert.deepEqual(createBoard([2, 10]), [["X", "O", "X", "O", "X", "O", "X", "O", "X", "O"], ["O", "X", "O", "X", "O", "X", "O", "X", "O", "X"]]); +``` + +`createBoard([5, 4])` should return `[["X", "O", "X", "O"], ["O", "X", "O", "X"], ["X", "O", "X", "O"], ["O", "X", "O", "X"], ["X", "O", "X", "O"]]`. + +```js +assert.deepEqual(createBoard([5, 4]), [["X", "O", "X", "O"], ["O", "X", "O", "X"], ["X", "O", "X", "O"], ["O", "X", "O", "X"], ["X", "O", "X", "O"]]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function createBoard(dimensions) { + return dimensions; +} +``` + +# --solutions-- + +```js +function createBoard(dimensions) { + const [rows, cols] = dimensions; + const board = []; + + for (let r = 0; r < rows; r++) { + const row = []; + for (let c = 0; c < cols; c++) { + row.push((r + c) % 2 === 0 ? "X" : "O"); + } + board.push(row); + } + + return board; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691f7773cddba1caf1bf5eca.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691f7773cddba1caf1bf5eca.md new file mode 100644 index 0000000000000000000000000000000000000000..8f3eedff9285f38eae8f1fdd67d3c3f9c71520bc --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691f7773cddba1caf1bf5eca.md @@ -0,0 +1,72 @@ +--- +id: 691f7773cddba1caf1bf5eca +title: "Challenge 131: Pairwise" +challengeType: 28 +dashedName: challenge-131 +--- + +# --description-- + +Given an array of integers and a target number, find all pairs of elements in the array whose values add up to the target and return the sum of their indices. + +For example, given `[2, 3, 4, 6, 8]` and `10`, you will find two valid pairs: + +- `2` and `8` (2 + 8 = 10), whose indices are `0` and `4` +- `4` and `6` (4 + 6 = 10), whose indices are `2` and `3` + +Add all the indices together to get a return value of `9`. + +# --hints-- + +`pairwise([2, 3, 4, 6, 8], 10)` should return `9`. + +```js +assert.equal(pairwise([2, 3, 4, 6, 8], 10), 9); +``` + +`pairwise([4, 1, 5, 2, 6, 3], 7)` should return `15`. + +```js +assert.equal(pairwise([4, 1, 5, 2, 6, 3], 7), 15); +``` + +`pairwise([-30, -15, 5, 10, 15, -5, 20, -40], -20)` should return `22`. + +```js +assert.equal(pairwise([-30, -15, 5, 10, 15, -5, 20, -40], -20), 22); +``` + +`pairwise([7, 9, 13, 19, 21, 6, 3, 1, 4, 8, 12, 22], 24)` should return `10`. + +```js +assert.equal(pairwise([7, 9, 13, 19, 21, 6, 3, 1, 4, 8, 12, 22], 24), 10); +``` + +# --seed-- + +## --seed-contents-- + +```js +function pairwise(arr, target) { + + return arr; +} +``` + +# --solutions-- + +```js +function pairwise(arr, target) { + let total = 0; + + for (let i = 0; i < arr.length; i++) { + for (let j = i + 1; j < arr.length; j++) { + if (arr[i] + arr[j] === target) { + total += i + j; + } + } + } + + return total; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691f7773cddba1caf1bf5ecb.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691f7773cddba1caf1bf5ecb.md new file mode 100644 index 0000000000000000000000000000000000000000..a9f3cd2f58bbcb2b844ce830762275a10b6bb895 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691f7773cddba1caf1bf5ecb.md @@ -0,0 +1,75 @@ +--- +id: 691f7773cddba1caf1bf5ecb +title: "Challenge 132: Purge Most Frequent" +challengeType: 28 +dashedName: challenge-132 +--- + +# --description-- + +Given an array of values, remove all occurrences of the most frequently occurring element and return the resulting array. + +- If multiple values are tied for most frequent, remove all of them. +- Do not change any of the other elements or their order. + +# --hints-- + +`purgeMostFrequent([1, 2, 2, 3])` should return `[1, 3]`. + +```js +assert.deepEqual(purgeMostFrequent([1, 2, 2, 3]), [1, 3]); +``` + +`purgeMostFrequent(["a", "b", "d", "b", "c", "d", "c", "d", "c", "d"])` should return `["a", "b", "b", "c", "c", "c"]`. + +```js +assert.deepEqual(purgeMostFrequent(["a", "b", "d", "b", "c", "d", "c", "d", "c", "d"]), ["a", "b", "b", "c", "c", "c"]); +``` + +`purgeMostFrequent(["red", "blue", "green", "red", "blue", "green", "blue"])` should return `["red", "green", "red", "green"]`. + +```js +assert.deepEqual(purgeMostFrequent(["red", "blue", "green", "red", "blue", "green", "blue"]), ["red", "green", "red", "green"]); +``` + +`purgeMostFrequent([5, 5, 5, 5])` should return `[]`. + +```js +assert.deepEqual(purgeMostFrequent([5, 5, 5, 5]), []); +``` + +`purgeMostFrequent([10, 12, 7, 3, 7, 7, 12, 12])` should return `[10, 3]`. + +```js +assert.deepEqual(purgeMostFrequent([10, 12, 7, 3, 7, 7, 12, 12]), [10, 3]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function purgeMostFrequent(arr) { + + return arr; +} +``` + +# --solutions-- + +```js +function purgeMostFrequent(arr) { + const freq = {}; + for (const val of arr) { + freq[val] = (freq[val] || 0) + 1; + } + + const maxFreq = Math.max(...Object.values(freq)); + + const toRemove = new Set( + Object.keys(freq).filter(key => freq[key] === maxFreq) + ); + + return arr.filter(val => !toRemove.has(String(val))); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691f7773cddba1caf1bf5ecc.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691f7773cddba1caf1bf5ecc.md new file mode 100644 index 0000000000000000000000000000000000000000..34bb054efaf53b4861ebb071f981cfe17ced943e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691f7773cddba1caf1bf5ecc.md @@ -0,0 +1,123 @@ +--- +id: 691f7773cddba1caf1bf5ecc +title: "Challenge 133: Daylight Hours" +challengeType: 28 +dashedName: challenge-133 +--- + +# --description-- + +December 21st is the winter solstice for the northern hemisphere and the summer solstice for the southern hemisphere. That means it's the day with the least daylight in the north and the most daylight in the south. + +Given a latitude number from -90 to 90, return a rough approximation of daylight hours on the solstice using the following table: + +|Latitude|Daylight Hours| +|-|-| +|-90|24| +|-75|23| +|-60|21| +|-45|15| +|-30|13| +|-15|12| +|0|12| +|15|11| +|30|10| +|45|9| +|60|6| +|75|2| +|90|0| + +- If the given latitude does not exactly match a table entry, use the value of the closest latitude. + +# --hints-- + +`daylightHours(45)` should return `9`. + +```js +assert.equal(daylightHours(45), 9); +``` + +`daylightHours(0)` should return `12`. + +```js +assert.equal(daylightHours(0), 12); +``` + +`daylightHours(-90)` should return `24`. + +```js +assert.equal(daylightHours(-90), 24); +``` + +`daylightHours(-10)` should return `12`. + +```js +assert.equal(daylightHours(-10), 12); +``` + +`daylightHours(23)` should return `10`. + +```js +assert.equal(daylightHours(23), 10); +``` + +`daylightHours(88)` should return `0`. + +```js +assert.equal(daylightHours(88), 0); +``` + +`daylightHours(-33)` should return `13`. + +```js +assert.equal(daylightHours(-33), 13); +``` + +`daylightHours(70)` should return `2`. + +```js +assert.equal(daylightHours(70), 2); +``` + +# --seed-- + +## --seed-contents-- + +```js +function daylightHours(latitude) { + + return latitude; +} +``` + +# --solutions-- + +```js +function daylightHours(latitude) { + const table = [ + { lat: -90, hours: 24 }, + { lat: -75, hours: 23 }, + { lat: -60, hours: 21 }, + { lat: -45, hours: 15 }, + { lat: -30, hours: 13 }, + { lat: -15, hours: 12 }, + { lat: 0, hours: 12 }, + { lat: 15, hours: 11 }, + { lat: 30, hours: 10 }, + { lat: 45, hours: 9 }, + { lat: 60, hours: 6 }, + { lat: 75, hours: 2 }, + { lat: 90, hours: 0 } + ]; + + let closest = table[0]; + + for (const entry of table) { + if (Math.abs(entry.lat - latitude) < Math.abs(closest.lat - latitude)) { + closest = entry; + } + } + + return closest.hours; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691f7773cddba1caf1bf5ecd.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691f7773cddba1caf1bf5ecd.md new file mode 100644 index 0000000000000000000000000000000000000000..2fc50c7aaba67d7180b3757cc01f6e8b55bc1f90 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691f7773cddba1caf1bf5ecd.md @@ -0,0 +1,99 @@ +--- +id: 691f7773cddba1caf1bf5ecd +title: "Challenge 134: Traveling Shopper" +challengeType: 28 +dashedName: challenge-134 +--- + +# --description-- + +Given an amount of money you have, and an array of items you want to buy, determine how many of them you can afford. + +- The given amount will be in the format `["Amount", "Currency Code"]`. For example: `["150.00", "USD"]` or `["6000", "JPY"]`. +- Each array item you want to purchase will be in the same format. + +Use the following exchange rates to convert values: + +|Currency|1 Unit Equals| +|-|-| +|USD|1.00 USD| +|EUR|1.10 USD| +|GBP|1.25 USD| +|JPY|0.0070 USD| +|CAD|0.75 USD| + +- If you can afford all the items in the list, return `"Buy them all!"`. +- Otherwise, return `"Buy the first X items."`, where `X` is the number of items you can afford when purchased in the order given. + +# --hints-- + +`buyItems(["150.00", "USD"], [["50.00", "USD"], ["75.00", "USD"], ["30.00", "USD"]])` should return `"Buy the first 2 items."`. + +```js +assert.equal(buyItems(["150.00", "USD"], [["50.00", "USD"], ["75.00", "USD"], ["30.00", "USD"]]), "Buy the first 2 items."); +``` + +`buyItems(["200.00", "EUR"], [["50.00", "USD"], ["50.00", "USD"]])` should return `"Buy them all!"`. + +```js +assert.equal(buyItems(["200.00", "EUR"], [["50.00", "USD"], ["50.00", "USD"]]), "Buy them all!"); +``` + +`buyItems(["100.00", "CAD"], [["20.00", "USD"], ["15.00", "EUR"], ["10.00", "GBP"], ["6000", "JPY"], ["5.00", "CAD"], ["10.00", "USD"]])` should return `"Buy the first 3 items."`. + +```js +assert.equal(buyItems(["100.00", "CAD"], [["20.00", "USD"], ["15.00", "EUR"], ["10.00", "GBP"], ["6000", "JPY"], ["5.00", "CAD"], ["10.00", "USD"]]), "Buy the first 3 items."); +``` + +`buyItems(["5000", "JPY"], [["3.00", "USD"], ["1000", "JPY"], ["5.00", "CAD"], ["2.00", "EUR"], ["4.00", "USD"], ["2000", "JPY"]])` should return `"Buy them all!"`. + +```js +assert.equal(buyItems(["5000", "JPY"], [["3.00", "USD"], ["1000", "JPY"], ["5.00", "CAD"], ["2.00", "EUR"], ["4.00", "USD"], ["2000", "JPY"]]), "Buy them all!"); +``` + +`buyItems(["200.00", "USD"], [["50.00", "USD"], ["40.00", "EUR"], ["30.00", "GBP"], ["5000", "JPY"], ["25.00", "CAD"], ["20.00", "USD"]])` should return `"Buy the first 5 items."`. + +```js +assert.equal(buyItems(["200.00", "USD"], [["50.00", "USD"], ["40.00", "EUR"], ["30.00", "GBP"], ["5000", "JPY"], ["25.00", "CAD"], ["20.00", "USD"]]), "Buy the first 5 items."); +``` + +# --seed-- + +## --seed-contents-- + +```js +function buyItems(funds, items) { + + return funds; +} +``` + +# --solutions-- + +```js +function buyItems(funds, items) { + const rates = { + USD: 1.00, + EUR: 1.10, + GBP: 1.25, + JPY: 0.0070, + CAD: 0.75 + }; + + const [amount, currency] = funds; + let money = parseFloat(amount) * rates[currency]; + + for (let i = 0; i < items.length; i++) { + const [itemAmount, itemCurrency] = items[i]; + const itemCostUSD = parseFloat(itemAmount) * rates[itemCurrency]; + + if (itemCostUSD > money) { + return `Buy the first ${i} items.`; + } + + money -= itemCostUSD; + } + + return "Buy them all!"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691f7773cddba1caf1bf5ece.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691f7773cddba1caf1bf5ece.md new file mode 100644 index 0000000000000000000000000000000000000000..756dc8524dd4ef2e9d1ecf6b50647c01cfc9c604 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691f7773cddba1caf1bf5ece.md @@ -0,0 +1,81 @@ +--- +id: 691f7773cddba1caf1bf5ece +title: "Challenge 135: Re: Fwd: Fw: Count" +challengeType: 28 +dashedName: challenge-135 +--- + +# --description-- + +Given a string representing the subject line of an email, determine how many times the email has been forwarded or replied to. + +For simplicity, consider an email forwarded or replied to if the string contains any of the following markers (case-insensitive): + +- `"fw:"` +- `"fwd:"` +- `"re:"` + +Return the total number of occurrences of these markers. + +# --hints-- + +`emailChainCount("Re: Meeting Notes")` should return `1`. + +```js +assert.equal(emailChainCount("Re: Meeting Notes"), 1); +``` + +`emailChainCount("Meeting Notes")` should return `0`. + +```js +assert.equal(emailChainCount("Meeting Notes"), 0); +``` + +`emailChainCount("Re: re: RE: rE: Meeting Notes")` should return `4`. + +```js +assert.equal(emailChainCount("Re: re: RE: rE: Meeting Notes"), 4); +``` + +`emailChainCount("Re: Fwd: Re: Fw: Re: Meeting Notes")` should return `5`. + +```js +assert.equal(emailChainCount("Re: Fwd: Re: Fw: Re: Meeting Notes"), 5); +``` + +`emailChainCount("re:Ref:fw:re:review:FW:Re:fw:report:Re:FW:followup:re:summary:Fwd:Re:fw:NextStep:RE:FW:re:Project:Fwd:Re:fw:Notes:RE:re:Update:FWD:Re:fw:Summary")` should return `23`. + +```js +assert.equal(emailChainCount("re:Ref:fw:re:review:FW:Re:fw:report:Re:FW:followup:re:summary:Fwd:Re:fw:NextStep:RE:FW:re:Project:Fwd:Re:fw:Notes:RE:re:Update:FWD:Re:fw:Summary"), 23); +``` + +# --seed-- + +## --seed-contents-- + +```js +function emailChainCount(subject) { + + return subject; +} +``` + +# --solutions-- + +```js +function emailChainCount(subject) { + const markers = ["re:", "fwd:", "fw:"]; + const lower = subject.toLowerCase(); + let count = 0; + + for (const marker of markers) { + let index = 0; + while ((index = lower.indexOf(marker, index)) !== -1) { + count++; + index += marker.length; + } + } + + return count; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6925e2068081f40f549ced1a.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6925e2068081f40f549ced1a.md new file mode 100644 index 0000000000000000000000000000000000000000..bdaae54f4a13ca4c8fa07275d0859772db0024c0 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6925e2068081f40f549ced1a.md @@ -0,0 +1,67 @@ +--- +id: 6925e2068081f40f549ced1a +title: "Challenge 136: Markdown Image Parser" +challengeType: 28 +dashedName: challenge-136 +--- + +# --description-- + +Given a string of an image in Markdown, return the equivalent HTML string. + +A Markdown image has the following format: `"![alt text](image_url)"`. Where: + +- `alt text` is the description of the image (the `alt` attribute value). +- `image_url` is the source URL of the image (the `src` attribute value). + +Return a string of the HTML `img` tag with the `src` set to the image URL and the `alt` set to the alt text. + +For example, given `"![Cute cat](cat.png)"` return `'Cute cat'`; + +- Make sure the tag, order of attributes, spacing, and quote usage is the same as above. + +Note: The console may not display HTML tags in strings when logging messages — check the browser console to see logs with tags included. + +# --hints-- + +`parseImage("![Cute cat](cat.png)")` should return `'Cute cat'`. + +```js +assert.equal(parseImage("![Cute cat](cat.png)"), 'Cute cat'); +``` + +`parseImage("![Rocket Ship](https://freecodecamp.org/cdn/rocket-ship.jpg)")` should return `'Rocket Ship'`. + +```js +assert.equal(parseImage("![Rocket Ship](https://freecodecamp.org/cdn/rocket-ship.jpg)"), 'Rocket Ship'); +``` + +`parseImage("![Cute cats!](https://freecodecamp.org/cats.jpeg)")` should return `'Cute cats!'`. + +```js +assert.equal(parseImage("![Cute cats!](https://freecodecamp.org/cats.jpeg)"), 'Cute cats!'); +``` + +# --seed-- + +## --seed-contents-- + +```js +function parseImage(markdown) { + + return markdown; +} +``` + +# --solutions-- + +```js +function parseImage(markdown) { + const regex = /!\[(.*?)\]\((.*?)\)/; + const match = markdown.match(regex); + if (!match) return ""; + const alt = match[1]; + const src = match[2]; + return `${alt}`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6925e2068081f40f549ced1b.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6925e2068081f40f549ced1b.md new file mode 100644 index 0000000000000000000000000000000000000000..8ea36a05b3a51f416203c3ac7551e1ae04d117e3 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6925e2068081f40f549ced1b.md @@ -0,0 +1,88 @@ +--- +id: 6925e2068081f40f549ced1b +title: "Challenge 137: Snowflake Generator" +challengeType: 28 +dashedName: challenge-137 +--- + +# --description-- + +Given a multi-line string that uses newline characters (`\n`) to represent a line break, return a new string where each line is mirrored horizontally and attached to the end of the original line. + +- Mirror a line by reversing all of its characters, including spaces. + +For example, given `"* \n *\n* "`, which logs to the console as: + +```sh +* + * +* +``` + +Return `"* *\n ** \n* *"`, which logs to the console as: + +```sh +* * + ** +* * +``` + +Take careful note of the whitespaces in the given and returned strings. Be sure not to trim any of them. + +# --hints-- + +`generateSnowflake("* \n *\n* ")` should return `"* *\n ** \n* *"`. + +```js +assert.equal(generateSnowflake("* \n *\n* "), "* *\n ** \n* *"); +``` + +`generateSnowflake("X=~")` should return `"X=~~=X"`. + +```js +assert.equal(generateSnowflake("X=~"), "X=~~=X"); +``` + +`generateSnowflake(" X \n v \nX--=\n ^ \n X ")` should return `" X X \n v v \nX--==--X\n ^ ^ \n X X "`. + +```js +assert.equal(generateSnowflake(" X \n v \nX--=\n ^ \n X "), " X X \n v v \nX--==--X\n ^ ^ \n X X "); +``` + +`generateSnowflake("* *\n * * \n* * *\n * * \n* *")` should return `"* ** *\n * * * * \n* * ** * *\n * * * * \n* ** *"`. + +```js +assert.equal(generateSnowflake("* *\n * * \n* * *\n * * \n* *"), "* ** *\n * * * * \n* * ** * *\n * * * * \n* ** *"); +``` + +`generateSnowflake("* -\n * -\n* -")` should return `"* -- *\n * -- * \n* -- *"`. + +```js +assert.equal(generateSnowflake("* -\n * -\n* -"), "* -- *\n * -- * \n* -- *"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function generateSnowflake(crystals) { + + return crystals; +} +``` + +# --solutions-- + +```js +function generateSnowflake(crystals) { + const lines = crystals.split("\n"); + + const mirroredLines = lines.map(line => { + const reversed = line.split("").reverse().join(""); + return line + reversed; + }); + + return mirroredLines.join("\n"); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6925e2068081f40f549ced1c.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6925e2068081f40f549ced1c.md new file mode 100644 index 0000000000000000000000000000000000000000..4d04bf9bb7b5f93f943e7e0d022427824fbcd22e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6925e2068081f40f549ced1c.md @@ -0,0 +1,78 @@ +--- +id: 6925e2068081f40f549ced1c +title: "Challenge 138: Sum of Divisors" +challengeType: 28 +dashedName: challenge-138 +--- + +# --description-- + +Given a positive integer, return the sum of all its divisors. + +- A divisor is any integer that divides the number evenly (the remainder is `0`). +- Only count each divisor once. + +For example, given `6`, return `12` because the divisors of `6` are `1`, `2`, `3`, and `6`, and the sum of those is `12`. + +# --hints-- + +`sumDivisors(6)` should return `12`. + +```js +assert.equal(sumDivisors(6), 12); +``` + +`sumDivisors(13)` should return `14`. + +```js +assert.equal(sumDivisors(13), 14); +``` + +`sumDivisors(28)` should return `56`. + +```js +assert.equal(sumDivisors(28), 56); +``` + +`sumDivisors(84)` should return `224`. + +```js +assert.equal(sumDivisors(84), 224); +``` + +`sumDivisors(549)` should return `806`. + +```js +assert.equal(sumDivisors(549), 806); +``` + +`sumDivisors(9348)` should return `23520`. + +```js +assert.equal(sumDivisors(9348), 23520); +``` + +# --seed-- + +## --seed-contents-- + +```js +function sumDivisors(n) { + + return n; +} +``` + +# --solutions-- + +```js +function sumDivisors(n) { + let sum = 0; + for (let i = 1; i <= n; i++) { + if (n % i === 0) { + sum += i; + } + } + return sum; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6925e2068081f40f549ced1d.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6925e2068081f40f549ced1d.md new file mode 100644 index 0000000000000000000000000000000000000000..b2747d092d8a1c1a14d08045a4b7bdfaf56af0f8 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6925e2068081f40f549ced1d.md @@ -0,0 +1,88 @@ +--- +id: 6925e2068081f40f549ced1d +title: "Challenge 139: Rock, Paper, Scissors" +challengeType: 28 +dashedName: challenge-139 +--- + +# --description-- + +Given two strings, the first representing Player 1 and the second representing Player 2, determine the winner of a match of Rock, Paper, Scissors. + +- The input strings will always be `"Rock"`, `"Paper"`, or `"Scissors"`. +- `"Rock"` beats `"Scissors"`. +- `"Paper"` beats `"Rock"`. +- `"Scissors"` beats `"Paper"`. + +Return: + +- `"Player 1 wins"` if Player 1 wins. +- `"Player 2 wins"` if Player 2 wins. +- `"Tie"` if both players choose the same option. + +# --hints-- + +`rockPaperScissors("Rock", "Rock")` should return `"Tie"`. + +```js +assert.equal(rockPaperScissors("Rock", "Rock"), "Tie"); +``` + +`rockPaperScissors("Rock", "Paper")` should return `"Player 2 wins"`. + +```js +assert.equal(rockPaperScissors("Rock", "Paper"), "Player 2 wins"); +``` + +`rockPaperScissors("Scissors", "Paper")` should return `"Player 1 wins"`. + +```js +assert.equal(rockPaperScissors("Scissors", "Paper"), "Player 1 wins"); +``` + +`rockPaperScissors("Rock", "Scissors")` should return `"Player 1 wins"`. + +```js +assert.equal(rockPaperScissors("Rock", "Scissors"), "Player 1 wins"); +``` + +`rockPaperScissors("Scissors", "Scissors")` should return `"Tie"`. + +```js +assert.equal(rockPaperScissors("Scissors", "Scissors"), "Tie"); +``` + +`rockPaperScissors("Scissors", "Rock")` should return `"Player 2 wins"`. + +```js +assert.equal(rockPaperScissors("Scissors", "Rock"), "Player 2 wins"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function rockPaperScissors(player1, player2) { + + return player1; +} +``` + +# --solutions-- + +```js +function rockPaperScissors(player1, player2) { + if (player1 === player2) return "Tie"; + + if ( + (player1 === "Rock" && player2 === "Scissors") || + (player1 === "Paper" && player2 === "Rock") || + (player1 === "Scissors" && player2 === "Paper") + ) { + return "Player 1 wins"; + } else { + return "Player 2 wins"; + } +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69272dcf1c24b44fd79137c3.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69272dcf1c24b44fd79137c3.md new file mode 100644 index 0000000000000000000000000000000000000000..09f0bb54584dad0631dcf661e68d101acdb7a3a9 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69272dcf1c24b44fd79137c3.md @@ -0,0 +1,84 @@ +--- +id: 69272dcf1c24b44fd79137c3 +title: "Challenge 140: SCREAMING_SNAKE_CASE" +challengeType: 28 +dashedName: challenge-140 +--- + +# --description-- + +Given a string representing a variable name, return the variable name converted to SCREAMING_SNAKE_CASE. + +The given variable names will be written in one of the following formats: + +- `camelCase` +- `PascalCase` +- `snake_case` +- `kebab-case` + +In the above formats, words are separated by an underscore (`_`), a hyphen (`-`), or a new word starts with a capital letter. + +To convert to SCREAMING_SNAKE_CASE: + +- Make all letters uppercase +- Separate words with an underscore (`_`) + +# --hints-- + +`toScreamingSnakeCase("userEmail")` should return `"USER_EMAIL"`. + +```js +assert.equal(toScreamingSnakeCase("userEmail"), "USER_EMAIL"); +``` + +`toScreamingSnakeCase("UserPassword")` should return `"USER_PASSWORD"`. + +```js +assert.equal(toScreamingSnakeCase("UserPassword"), "USER_PASSWORD"); +``` + +`toScreamingSnakeCase("user_id")` should return `"USER_ID"`. + +```js +assert.equal(toScreamingSnakeCase("user_id"), "USER_ID"); +``` + +`toScreamingSnakeCase("user-address")` should return `"USER_ADDRESS"`. + +```js +assert.equal(toScreamingSnakeCase("user-address"), "USER_ADDRESS"); +``` + +`toScreamingSnakeCase("username")` should return `"USERNAME"`. + +```js +assert.equal(toScreamingSnakeCase("username"), "USERNAME"); +``` + +`toScreamingSnakeCase("my_variable_name")` should return `"MY_VARIABLE_NAME"`. + +```js +assert.equal(toScreamingSnakeCase("my_variable_name"), "MY_VARIABLE_NAME"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function toScreamingSnakeCase(variableName) { + + return variableName; +} +``` + +# --solutions-- + +```js +function toScreamingSnakeCase(variableName) { + let temp = variableName.replace(/[-_]+/g, ' '); + temp = temp.replace(/([a-z0-9])([A-Z])/g, '$1 $2'); + const words = temp.trim().split(/\s+/); + return words.join('_').toUpperCase(); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69272dcf1c24b44fd79137c4.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69272dcf1c24b44fd79137c4.md new file mode 100644 index 0000000000000000000000000000000000000000..e2b8f5ced9843f6f8b067b9e763bc92d779d6b16 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69272dcf1c24b44fd79137c4.md @@ -0,0 +1,70 @@ +--- +id: 69272dcf1c24b44fd79137c4 +title: "Challenge 141: Takeoff Fuel" +challengeType: 28 +dashedName: challenge-141 +--- + +# --description-- + +Given the numbers of gallons of fuel currently in your airplane, and the required number of liters of fuel to reach your destination, determine how many additional gallons of fuel you should add. + +- 1 gallon equals 3.78541 liters. +- If the airplane already has enough fuel, return `0`. +- You can only add whole gallons. +- Do not include decimals in the return number. + +# --hints-- + +`fuelToAdd(0, 1)` should return `1`. + +```js +assert.equal(fuelToAdd(0, 1), 1); +``` + +`fuelToAdd(5, 40)` should return `6`. + +```js +assert.equal(fuelToAdd(5, 40), 6); +``` + +`fuelToAdd(10, 30)` should return `0`. + +```js +assert.equal(fuelToAdd(10, 30), 0); +``` + +`fuelToAdd(896, 20500)` should return `4520`. + +```js +assert.equal(fuelToAdd(896, 20500), 4520); +``` + +`fuelToAdd(1000, 50000)` should return `12209`. + +```js +assert.equal(fuelToAdd(1000, 50000), 12209); +``` + +# --seed-- + +## --seed-contents-- + +```js +function fuelToAdd(currentGallons, requiredLiters) { + + return currentGallons; +} +``` + +# --solutions-- + +```js +function fuelToAdd(currentGallons, requiredLiters) { + const litersPerGallon = 3.78541; + const currentLiters = currentGallons * litersPerGallon; + if (currentLiters >= requiredLiters) return 0; + const litersNeeded = requiredLiters - currentLiters; + return Math.ceil(litersNeeded / litersPerGallon); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69272dcf1c24b44fd79137c5.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69272dcf1c24b44fd79137c5.md new file mode 100644 index 0000000000000000000000000000000000000000..0d7fd9716e959f49e246ff325599b3d6b7457b73 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69272dcf1c24b44fd79137c5.md @@ -0,0 +1,65 @@ +--- +id: 69272dcf1c24b44fd79137c5 +title: "Challenge 142: Sum the String" +challengeType: 28 +dashedName: challenge-142 +--- + +# --description-- + +Given a string containing digits and other characters, return the sum of all numbers in the string. + +- Treat consecutive digits as a single number. For example, `"13"` counts as 13, not 1 + 3. +- Ignore any non-digit characters. + +# --hints-- + +`stringSum("3apples2bananas")` should return `5`. + +```js +assert.equal(stringSum("3apples2bananas"), 5); +``` + +`stringSum("10cats5dogs2birds")` should return `17`. + +```js +assert.equal(stringSum("10cats5dogs2birds"), 17); +``` + +`stringSum("125344")` should return `125344`. + +```js +assert.equal(stringSum("125344"), 125344); +``` + +`stringSum("a1b20c300")` should return `321`. + +```js +assert.equal(stringSum("a1b20c300"), 321); +``` + +`stringSum("a12b34c56d78e90f123g456h789i0j1k2l3m4n5")` should return `1653`. + +```js +assert.equal(stringSum("a12b34c56d78e90f123g456h789i0j1k2l3m4n5"), 1653); +``` + +# --seed-- + +## --seed-contents-- + +```js +function stringSum(str) { + + return str; +} +``` + +# --solutions-- + +```js +function stringSum(str) { + const matches = str.match(/\d+/g); // find all consecutive digits + return matches.reduce((sum, num) => sum + Number(num), 0); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69272dcf1c24b44fd79137c6.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69272dcf1c24b44fd79137c6.md new file mode 100644 index 0000000000000000000000000000000000000000..6398b5ab1c9ed0070589a54a03bfa74c832a7ba7 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69272dcf1c24b44fd79137c6.md @@ -0,0 +1,69 @@ +--- +id: 69272dcf1c24b44fd79137c6 +title: "Challenge 143: Markdown Italic Parser" +challengeType: 28 +dashedName: challenge-143 +--- + +# --description-- + +Given a string that may include some italic text in Markdown, return the equivalent HTML string. + +- Italic text in Markdown is any text that starts and ends with a single asterisk (`*`) or a single underscore (`_`). +- There cannot be any spaces between the text and the asterisk or underscore, but there can be spaces in the text itself. +- Convert all italic occurrences to HTML `i` tags and return the string. + +For example, given `"*This is italic*"`, return `"This is italic"`. + +Note: The console may not display HTML tags in strings when logging messages. Check the browser console to see logs with tags included. + +# --hints-- + +`parseItalics("*This is italic*")` should return `"This is italic"`. + +```js +assert.equal(parseItalics("*This is italic*"), "This is italic"); +``` + +`parseItalics("_This is also italic_")` should return `"This is also italic"`. + +```js +assert.equal(parseItalics("_This is also italic_"), "This is also italic"); +``` + +`parseItalics("*This is not italic *")` should return `"*This is not italic *"`. + +```js +assert.equal(parseItalics("*This is not italic *"), "*This is not italic *"); +``` + +`parseItalics("_ This is also not italic_")` should return `"_ This is also not italic_"`. + +```js +assert.equal(parseItalics("_ This is also not italic_"), "_ This is also not italic_"); +``` + +`parseItalics("The *quick* brown fox _jumps_ over the *lazy* dog.")` should return `"The quick brown fox jumps over the lazy dog."`. + +```js +assert.equal(parseItalics("The *quick* brown fox _jumps_ over the *lazy* dog."), "The quick brown fox jumps over the lazy dog."); +``` + +# --seed-- + +## --seed-contents-- + +```js +function parseItalics(markdown) { + + return markdown; +} +``` + +# --solutions-- + +```js +function parseItalics(markdown) { + return markdown.replace(/(\*|_)([^\s][^]*?[^\s])\1/g, '$2'); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69306364df283fcaff2e1ad5.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69306364df283fcaff2e1ad5.md new file mode 100644 index 0000000000000000000000000000000000000000..5f1fb8589a20f667080c57f282641ef217e87e8a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69306364df283fcaff2e1ad5.md @@ -0,0 +1,84 @@ +--- +id: 69306364df283fcaff2e1ad5 +title: "Challenge 144: Resolution Streak" +challengeType: 28 +dashedName: challenge-144 +--- + +# --description-- + +Given an array of arrays, where each sub-array represents a day of your resolution activities and contains three integers: the number of steps walked that day, the minutes of screen time that day, and the number of pages read that day; determine if you are keeping your resolutions. + +- The first sub-array is day 1, and second day 2, and so on. + +A day is considered successful if all three of the following goals are met: + +- You walked at least 10,000 steps. +- You had no more than 120 minutes of screen time. +- You read at least five pages. + +If all of the given days are successful, return `"Resolution on track: N day streak."` Where `N` is the number of successful days. + +If one or more days is not a success, return `"Resolution failed on day X: N day streak."`. Where `X` is the day number of the first unsuccessful day, and `N` is the number of successful days before the first unsuccessful day. + +# --hints-- + +`resolutionStreak([[10500, 75, 15], [11000, 90, 10], [10650, 100, 9]])` should return `"Resolution on track: 3 day streak."` + +```js +assert.equal(resolutionStreak([[10500, 75, 15], [11000, 90, 10], [10650, 100, 9]]), "Resolution on track: 3 day streak."); +``` + +`resolutionStreak([[10000, 120, 5], [10950, 121, 11]])` should return `"Resolution failed on day 2: 1 day streak."` + +```js +assert.equal(resolutionStreak([[10000, 120, 5], [10950, 121, 11]]), "Resolution failed on day 2: 1 day streak."); +``` + +`resolutionStreak([[15000, 110, 8], [12300, 60, 13], [10100, 120, 4], [9000, 125, 4]])` should return `"Resolution failed on day 3: 2 day streak."` + +```js +assert.equal(resolutionStreak([[15000, 110, 8], [12300, 60, 13], [10100, 120, 4], [9000, 125, 4]]), "Resolution failed on day 3: 2 day streak."); +``` + +`resolutionStreak([[11600, 76, 13], [12556, 64, 26], [10404, 32, 59], [9999, 44, 124], [7508, 23, 167], [10900, 80, 0]])` should return `"Resolution failed on day 4: 3 day streak."` + +```js +assert.equal(resolutionStreak([[11600, 76, 13], [12556, 64, 26], [10404, 32, 59], [9999, 44, 124], [7508, 23, 167], [10900, 80, 0]]), "Resolution failed on day 4: 3 day streak."); +``` + +`resolutionStreak([[10500, 75, 15], [11000, 90, 10], [10650, 100, 9], [10200, 60, 10], [10678, 87, 9], [12431, 67, 13], [10444, 107, 19], [10111, 95, 5], [10000, 120, 7], [11980, 101, 8]])` should return `"Resolution on track: 10 day streak."` + +```js +assert.equal(resolutionStreak([[10500, 75, 15], [11000, 90, 10], [10650, 100, 9], [10200, 60, 10], [10678, 87, 9], [12431, 67, 13], [10444, 107, 19], [10111, 95, 5], [10000, 120, 7], [11980, 101, 8]]), "Resolution on track: 10 day streak."); +``` + +# --seed-- + +## --seed-contents-- + +```js +function resolutionStreak(days) { + + return days; +} +``` + +# --solutions-- + +```js +function resolutionStreak(days) { + let streak = 0; + + for (let i = 0; i < days.length; i++) { + const [steps, screen, pages] = days[i]; + if (steps >= 10000 && screen <= 120 && pages >= 5) { + streak++; + } else { + return `Resolution failed on day ${i + 1}: ${streak} day streak.`; + } + } + + return `Resolution on track: ${streak} day streak.`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69306364df283fcaff2e1ad6.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69306364df283fcaff2e1ad6.md new file mode 100644 index 0000000000000000000000000000000000000000..27babddbad3ce4f627324c485c16095025dcdf7e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69306364df283fcaff2e1ad6.md @@ -0,0 +1,75 @@ +--- +id: 69306364df283fcaff2e1ad6 +title: "Challenge 145: Nth Fibonacci Number" +challengeType: 28 +dashedName: challenge-145 +--- + +# --description-- + +Given an integer `n`, return the `n`th number in the fibonacci sequence. + +The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. The first 10 numbers in the sequence are `0`, `1`, `1`, `2`, `3`, `5`, `8`, `13`, `21`, `34`. + +# --hints-- + +`nthFibonacci(4)` should return `2`. + +```js +assert.equal(nthFibonacci(4), 2); +``` + +`nthFibonacci(10)` should return `34`. + +```js +assert.equal(nthFibonacci(10), 34); +``` + +`nthFibonacci(15)` should return `377`. + +```js +assert.equal(nthFibonacci(15), 377); +``` + +`nthFibonacci(40)` should return `63245986`. + +```js +assert.equal(nthFibonacci(40), 63245986); +``` + +`nthFibonacci(75)` should return `1304969544928657`. + +```js +assert.equal(nthFibonacci(75), 1304969544928657); +``` + +# --seed-- + +## --seed-contents-- + +```js +function nthFibonacci(n) { + + return n; +} +``` + +# --solutions-- + +```js +function nthFibonacci(n) { + if (n === 1) return 0; + if (n === 2) return 1; + + let a = 0; + let b = 1; + + for (let i = 3; i <= n; i++) { + const next = a + b; + a = b; + b = next; + } + + return b; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69306364df283fcaff2e1ad7.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69306364df283fcaff2e1ad7.md new file mode 100644 index 0000000000000000000000000000000000000000..11baf2479edbcd0b16d562a04a9c93bf5a73559b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69306364df283fcaff2e1ad7.md @@ -0,0 +1,107 @@ +--- +id: 69306364df283fcaff2e1ad7 +title: "Challenge 146: Left-Handed Seat at the Table" +challengeType: 28 +dashedName: challenge-146 +--- + +# --description-- + +Given a 4x2 matrix (array of arrays) representing the seating arrangement for a meal, determine how many seats a left-handed person can sit at. + +- A left-handed person cannot sit where a right-handed person would be in the seat to the immediate left of them. + +In the given matrix: + +- An `"R"` is a seat occupied by a right-handed person. +- An `"L"` is a seat occupied by a left-handed person. +- A `"U"` is an unoccupied seat. +- Only unoccupied seats are available to sit at. +- The seats in the top row are facing "down", and the seats in the bottom row are facing "up" (like a table), so left and right are relative to the seat's orientation. +- Corner seats only have one seat next to them. + +For example, in the given matrix: + +```json +[ + ["U", "R", "U", "L"], + ["U", "R", "R", "R"] +] +``` + +The top-left seat is cannot be sat in because there's a right-handed person to the left. The other two open seats can be sat in because there isn't a right-handed person to the left. + +# --hints-- + +`findLeftHandedSeats([["U", "R", "U", "L"], ["U", "R", "R", "R"]])` should return `2`. + +```js +assert.equal(findLeftHandedSeats([["U", "R", "U", "L"], ["U", "R", "R", "R"]]), 2); +``` + +`findLeftHandedSeats([["U", "U", "U", "U"], ["U", "U", "U", "U"]])` should return `8`. + +```js +assert.equal(findLeftHandedSeats([["U", "U", "U", "U"], ["U", "U", "U", "U"]]), 8); +``` + +`findLeftHandedSeats([["U", "R", "U", "R"], ["L", "R", "R", "U"]])` should return `0`. + +```js +assert.equal(findLeftHandedSeats([["U", "R", "U", "R"], ["L", "R", "R", "U"]]), 0); +``` + +`findLeftHandedSeats([["L", "U", "R", "R"], ["L", "U", "R", "R"]])` should return `1`. + +```js +assert.equal(findLeftHandedSeats([["L", "U", "R", "R"], ["L", "U", "R", "R"]]), 1); +``` + +`findLeftHandedSeats([["U", "R", "U", "U"], ["U", "U", "L", "U"]])` should return `5`. + +```js +assert.equal(findLeftHandedSeats([["U", "R", "U", "U"], ["U", "U", "L", "U"]]), 5); +``` + +# --seed-- + +## --seed-contents-- + +```js +function findLeftHandedSeats(table) { + + return table; +} +``` + +# --solutions-- + +```js +function findLeftHandedSeats(table) { + let availableSeats = 0; + + const [topRow, bottomRow] = table; + + for (let i=0; i { + const bar = psi * psiToBar; + if (bar < minBar) return "Low"; + if (bar > maxBar) return "High"; + return "Good"; + }); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69306364df283fcaff2e1ada.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69306364df283fcaff2e1ada.md new file mode 100644 index 0000000000000000000000000000000000000000..26864c8702863ecef2d4cd8d79da14db544df94f --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69306364df283fcaff2e1ada.md @@ -0,0 +1,77 @@ +--- +id: 69306364df283fcaff2e1ada +title: "Challenge 149: vOwElcAsE" +challengeType: 28 +dashedName: challenge-149 +--- + +# --description-- + +Given a string, return a new string where all vowels are converted to uppercase and all other alphabetical characters are converted to lowercase. + +- Vowels are `"a"`, `"e"`, `"i"`, `"o"`, and `"u"` in any case. +- Non-alphabetical characters should remain unchanged. + +# --hints-- + +`vowelCase("vowelcase")` should return `"vOwElcAsE"`. + +```js +assert.equal(vowelCase("vowelcase"), "vOwElcAsE"); +``` + +`vowelCase("coding is fun")` should return `"cOdIng Is fUn"`. + +```js +assert.equal(vowelCase("coding is fun"), "cOdIng Is fUn"); +``` + +`vowelCase("HELLO, world!")` should return `"hEllO, wOrld!"`. + +```js +assert.equal(vowelCase("HELLO, world!"), "hEllO, wOrld!"); +``` + +`vowelCase("git cherry-pick")` should return `"gIt chErry-pIck"`. + +```js +assert.equal(vowelCase("git cherry-pick"), "gIt chErry-pIck"); +``` + +`vowelCase("HEAD~1")` should return `"hEAd~1"`. + +```js +assert.equal(vowelCase("HEAD~1"), "hEAd~1"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function vowelCase(str) { + + return str; +} +``` + +# --solutions-- + +```js +function vowelCase(str) { + const vowels = "aeiouAEIOU"; + let result = ""; + + for (let char of str) { + if (vowels.includes(char)) { + result += char.toUpperCase(); + } else if (/[a-zA-Z]/.test(char)) { + result += char.toLowerCase(); + } else { + result += char; + } + } + + return result; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69373793f5a867f769cde135.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69373793f5a867f769cde135.md new file mode 100644 index 0000000000000000000000000000000000000000..a79beb44a7af8115eadc0350f05c401b842f7a9d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69373793f5a867f769cde135.md @@ -0,0 +1,76 @@ +--- +id: 69373793f5a867f769cde135 +title: "Challenge 150: Markdown Unordered List Parser" +challengeType: 28 +dashedName: challenge-150 +--- + +# --description-- + +Given the string of a valid unordered list in Markdown, return the equivalent HTML string. + +An unordered list consists of one or more list items. A valid list item appears on its own line and: + +- Starts with a dash (`"-"`), followed by +- At least one space, and then +- The list item text. + +The list is given as a single string with new lines separated by the newline character (`"\n"`). Do not include the newline characters in the item text. + +Wrap each list item in HTML `li` tags, and the whole list of items in `ul` tags. + +For example, given `"- Item A\n- Item B"`, return `"
    • Item A
    • Item B
    "`. + +Note: The console may not display HTML tags in strings when logging messages. Check the browser console to see logs with tags included. + +# --hints-- + +`parseUnorderedList("- Item A\n- Item B")` should return `"
    • Item A
    • Item B
    "`. + +```js +assert.equal(parseUnorderedList("- Item A\n- Item B"), "
    • Item A
    • Item B
    "); +``` + +`parseUnorderedList("- JavaScript\n- Python")` should return `"
    • JavaScript
    • Python
    "`. + +```js +assert.equal(parseUnorderedList("- JavaScript\n- Python"), "
    • JavaScript
    • Python
    "); +``` + +`parseUnorderedList("- 2 C Flour\n- 1/2 C Sugar\n- 1 Tsp Vanilla")` should return `"
    • 2 C Flour
    • 1/2 C Sugar
    • 1 Tsp Vanilla
    "`. + +```js +assert.equal(parseUnorderedList("- 2 C Flour\n- 1/2 C Sugar\n- 1 Tsp Vanilla"), "
    • 2 C Flour
    • 1/2 C Sugar
    • 1 Tsp Vanilla
    "); +``` + +`parseUnorderedList("- A-1\n- A-2\n- B-1")` should return `"
    • A-1
    • A-2
    • B-1
    "`. + +```js +assert.equal(parseUnorderedList("- A-1\n- A-2\n- B-1"), "
    • A-1
    • A-2
    • B-1
    "); +``` + +# --seed-- + +## --seed-contents-- + +```js +function parseUnorderedList(markdown) { + + return markdown; +} +``` + +# --solutions-- + +```js +function parseUnorderedList(markdown) { + const lines = markdown.split("\n"); + const listItems = []; + + for (let line of lines) { + listItems.push(`
  • ${line.slice(1).trim()}
  • `); + } + + return `
      ${listItems.join("")}
    `; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69373793f5a867f769cde136.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69373793f5a867f769cde136.md new file mode 100644 index 0000000000000000000000000000000000000000..9d055b1a6eefa036bea2ea0293757c662609dccf --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69373793f5a867f769cde136.md @@ -0,0 +1,83 @@ +--- +id: 69373793f5a867f769cde136 +title: "Challenge 151: Sorted Array?" +challengeType: 28 +dashedName: challenge-151 +--- + +# --description-- + +Given an array of numbers, determine if the numbers are sorted in ascending order, descending order, or neither. + +If the given array is: + +- In ascending order (lowest to highest), return `"Ascending"`. +- In descending order (highest to lowest), return `"Descending"`. +- Not sorted in ascending or descending order, return `"Not sorted"`. + +# --hints-- + +`isSorted([1, 2, 3, 4, 5])` should return `"Ascending"`. + +```js +assert.equal(isSorted([1, 2, 3, 4, 5]), "Ascending"); +``` + +`isSorted([10, 8, 6, 4, 2])` should return `"Descending"`. + +```js +assert.equal(isSorted([10, 8, 6, 4, 2]), "Descending"); +``` + +`isSorted([1, 3, 2, 4, 5])` should return `"Not sorted"`. + +```js +assert.equal(isSorted([1, 3, 2, 4, 5]), "Not sorted"); +``` + +`isSorted([3.14, 2.71, 1.61, 0.57])` should return `"Descending"`. + +```js +assert.equal(isSorted([3.14, 2.71, 1.61, 0.57]), "Descending"); +``` + +`isSorted([12.3, 23.4, 34.5, 45.6, 56.7, 67.8, 78.9])` should return `"Ascending"`. + +```js +assert.equal(isSorted([12.3, 23.4, 34.5, 45.6, 56.7, 67.8, 78.9]), "Ascending"); +``` + +`isSorted([0.4, 0.5, 0.3])` should return `"Not sorted"`. + +```js +assert.equal(isSorted([0.4, 0.5, 0.3]), "Not sorted"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function isSorted(arr) { + + return arr; +} +``` + +# --solutions-- + +```js +function isSorted(arr) { + let ascending = true; + let descending = true; + + for (let i = 1; i < arr.length; i++) { + if (arr[i] < arr[i - 1]) ascending = false; + if (arr[i] > arr[i - 1]) descending = false; + } + + if (ascending) return "Ascending"; + if (descending) return "Descending"; + return "Not sorted"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69373793f5a867f769cde137.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69373793f5a867f769cde137.md new file mode 100644 index 0000000000000000000000000000000000000000..557cf94cb1e64bbf26fbf7d41a7a0d2cbbd66573 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69373793f5a867f769cde137.md @@ -0,0 +1,83 @@ +--- +id: 69373793f5a867f769cde137 +title: "Challenge 152: Circular Prime" +challengeType: 28 +dashedName: challenge-152 +--- + +# --description-- + +Given an integer, determine if it is a circular prime. + +A circular prime is an integer where all rotations of its digits are themselves prime. + +For example, `197` is a circular prime because all rotations of its digits: `197`, `971`, and `719`, are prime numbers. + +# --hints-- + +`isCircularPrime(197)` should return `true`. + +```js +assert.isTrue(isCircularPrime(197)); +``` + +`isCircularPrime(23)` should return `false`. + +```js +assert.isFalse(isCircularPrime(23)); +``` + +`isCircularPrime(13)` should return `true`. + +```js +assert.isTrue(isCircularPrime(13)); +``` + +`isCircularPrime(89)` should return `false`. + +```js +assert.isFalse(isCircularPrime(89)); +``` + +`isCircularPrime(1193)` should return `true`. + +```js +assert.isTrue(isCircularPrime(1193)); +``` + +# --seed-- + +## --seed-contents-- + +```js +function isCircularPrime(n) { + + return n; +} +``` + +# --solutions-- + +```js +function isPrime(n) { + if (n < 2) return false; + for (let i = 2, sqrt = Math.floor(Math.sqrt(n)); i <= sqrt; i++) { + if (n % i === 0) return false; + } + return true; +} + +function rotations(num) { + const str = num.toString(); + const result = []; + for (let i = 0; i < str.length; i++) { + result.push(str.slice(i) + str.slice(0, i)); + } + return result.map(Number); +} + +function isCircularPrime(num) { + const rots = rotations(num); + return rots.every(isPrime); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69373793f5a867f769cde138.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69373793f5a867f769cde138.md new file mode 100644 index 0000000000000000000000000000000000000000..1b9aa266206674a9a298d36be103f666b3bee69d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69373793f5a867f769cde138.md @@ -0,0 +1,95 @@ +--- +id: 69373793f5a867f769cde138 +title: "Challenge 153: Tic-Tac-Toe" +challengeType: 28 +dashedName: challenge-153 +--- + +# --description-- + +Given a 3×3 matrix (an array of arrays) representing a completed Tic-Tac-Toe game, determine the winner. + +- Each element in the given matrix is either an `"X"` or `"O"`. + +A player wins if they have three of their characters in a row - horizontally, vertically, or diagonally. + +Return: + +- `"X wins"` if player X has three in a row. +- `"O wins"` if player O has three in a row. +- `"Draw"` if no player has three in a row. + +# --hints-- + +`ticTacToe([["X", "X", "X"], ["O", "O", "X"], ["O", "X", "O"]])` should return `"X wins"`. + +```js +assert.equal(ticTacToe([["X", "X", "X"], ["O", "O", "X"], ["O", "X", "O"]]), "X wins"); +``` + +`ticTacToe([["O", "O", "X"], ["X", "O", "X"], ["O", "X", "X"]])` should return `"X wins"`. + +```js +assert.equal(ticTacToe([["O", "O", "X"], ["X", "O", "X"], ["O", "X", "X"]]), "X wins"); +``` + +`ticTacToe([["X", "O", "X"], ["O", "X", "O"], ["O", "X", "O"]])` should return `"Draw"`. + +```js +assert.equal(ticTacToe([["X", "O", "X"], ["O", "X", "O"], ["O", "X", "O"]]), "Draw"); +``` + +`ticTacToe([["X", "X", "O"], ["X", "O", "O"], ["O", "O", "X"]])` should return `"O wins"`. + +```js +assert.equal(ticTacToe([["X", "X", "O"], ["X", "O", "O"], ["O", "O", "X"]]), "O wins"); +``` + +`ticTacToe([["X", "O", "O"], ["O", "X", "O"], ["O", "X", "X"]])` should return `"X wins"`. + +```js +assert.equal(ticTacToe([["X", "O", "O"], ["O", "X", "O"], ["O", "X", "X"]]), "X wins"); +``` + +`ticTacToe([["O", "X", "X"], ["X", "O", "O"], ["X", "O", "X"]])` should return `"Draw"`. + +```js +assert.equal(ticTacToe([["O", "X", "X"], ["X", "O", "O"], ["X", "O", "X"]]), "Draw"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function ticTacToe(board) { + + return board; +} +``` + +# --solutions-- + +```js +function ticTacToe(board) { + const lines = []; + + for (let row of board) { + lines.push(row); + } + + for (let c = 0; c < 3; c++) { + lines.push([board[0][c], board[1][c], board[2][c]]); + } + + lines.push([board[0][0], board[1][1], board[2][2]]); + lines.push([board[0][2], board[1][1], board[2][0]]); + + for (let line of lines) { + if (line.every(cell => cell === "X")) return "X wins"; + if (line.every(cell => cell === "O")) return "O wins"; + } + + return "Draw"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69373793f5a867f769cde139.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69373793f5a867f769cde139.md new file mode 100644 index 0000000000000000000000000000000000000000..abf24d4b14a03be6c627e3018108dfc1712551c7 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69373793f5a867f769cde139.md @@ -0,0 +1,84 @@ +--- +id: 69373793f5a867f769cde139 +title: "Challenge 154: Par for the Hole" +challengeType: 28 +dashedName: challenge-154 +--- + +# --description-- + +Given two integers, the par for a golf hole and the number of strokes a golfer took on that hole, return the golfer's score using golf terms. + +Return: + +- `"Hole in one!"` if it took one stroke. +- `"Eagle"` if it took two strokes less than par. +- `"Birdie"` if it took one stroke less than par. +- `"Par"` if it took the same number of strokes as par. +- `"Bogey"` if it took one stroke more than par. +- `"Double bogey"` if took two strokes more than par. + +# --hints-- + +`golfScore(3, 3)` should return `"Par"`. + +```js +assert.equal(golfScore(3, 3), "Par"); +``` + +`golfScore(4, 3)` should return `"Birdie"`. + +```js +assert.equal(golfScore(4, 3), "Birdie"); +``` + +`golfScore(3, 1)` should return `"Hole in one!"`. + +```js +assert.equal(golfScore(3, 1), "Hole in one!"); +``` + +`golfScore(5, 7)` should return `"Double bogey"`. + +```js +assert.equal(golfScore(5, 7), "Double bogey"); +``` + +`golfScore(4, 5)` should return `"Bogey"`. + +```js +assert.equal(golfScore(4, 5), "Bogey"); +``` + +`golfScore(5, 3)` should return `"Eagle"`. + +```js +assert.equal(golfScore(5, 3), "Eagle"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function golfScore(par, strokes) { + + return par; +} +``` + +# --solutions-- + +```js +function golfScore(par, strokes) { + if (strokes === 1) return "Hole in one!"; + + const diff = strokes - par; + + if (diff === -2) return "Eagle"; + if (diff === -1) return "Birdie"; + if (diff === 0) return "Par"; + if (diff === 1) return "Bogey"; + if (diff === 2) return "Double bogey"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69373793f5a867f769cde13a.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69373793f5a867f769cde13a.md new file mode 100644 index 0000000000000000000000000000000000000000..894dd1b40b2bf1978acc1ddcebd127b3ad65f0f5 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69373793f5a867f769cde13a.md @@ -0,0 +1,86 @@ +--- +id: 69373793f5a867f769cde13a +title: "Challenge 155: Plant the Crop" +challengeType: 28 +dashedName: challenge-155 +--- + +# --description-- + +Given an integer representing the size of your farm field, and `"acres"` or `"hectares"` representing the unit for the size of your farm field, and a type of crop, determine how many plants of that type you can fit in your field. + +- 1 acre equals 4046.86 square meters. +- 1 hectare equals 10,000 square meters. + +Here's a list of crops that will be given as input and how much space a single plant takes: + +|Crop|Space per plant| +|-|-| +|`"corn"`|1 square meter| +|`"wheat"`|0.1 square meters| +|`"soybeans"`|0.5 square meters| +|`"tomatoes"`|0.25 square meters| +|`"lettuce"`|0.2 square meters| + +Return the number of plants that fit in the field, rounded down to the nearest whole plant. + +# --hints-- + +`getNumberOfPlants(1, "acres", "corn")` should return `4046`. + +```js +assert.equal(getNumberOfPlants(1, "acres", "corn"), 4046); +``` + +`getNumberOfPlants(2, "hectares", "lettuce")` should return `100000`. + +```js +assert.equal(getNumberOfPlants(2, "hectares", "lettuce"), 100000); +``` + +`getNumberOfPlants(20, "acres", "soybeans")` should return `161874`. + +```js +assert.equal(getNumberOfPlants(20, "acres", "soybeans"), 161874); +``` + +`getNumberOfPlants(3.75, "hectares", "tomatoes")` should return `150000`. + +```js +assert.equal(getNumberOfPlants(3.75, "hectares", "tomatoes"), 150000); +``` + +`getNumberOfPlants(16.75, "acres", "tomatoes")` should return `271139`. + +```js +assert.equal(getNumberOfPlants(16.75, "acres", "tomatoes"), 271139); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getNumberOfPlants(fieldSize, unit, crop) { + + return fieldSize; +} +``` + +# --solutions-- + +```js +function getNumberOfPlants(fieldSize, unit, crop) { + const cropSpace = { + corn: 1, + wheat: 0.1, + soybeans: 0.5, + tomatoes: 0.25, + lettuce: 0.2 + }; + + let fieldInSqM = unit === "acres" ? fieldSize * 4046.86 : fieldSize * 10000; + + return Math.floor(fieldInSqM / cropSpace[crop.toLowerCase()]); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6939b873185d8e00d453563b.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6939b873185d8e00d453563b.md new file mode 100644 index 0000000000000000000000000000000000000000..9d2daaf9adf6aaf0291195bff5dfa59fa1db622d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6939b873185d8e00d453563b.md @@ -0,0 +1,61 @@ +--- +id: 6939b873185d8e00d453563b +title: "Challenge 156: Odd or Even?" +challengeType: 28 +dashedName: challenge-156 +--- + +# --description-- + +Given a positive integer, return `"Odd"` if it's an odd number, and `"Even"` if it's even. + +# --hints-- + +`oddOrEven(1)` should return `"Odd"`. + +```js +assert.equal(oddOrEven(1), "Odd"); +``` + +`oddOrEven(2)` should return `"Even"`. + +```js +assert.equal(oddOrEven(2), "Even"); +``` + +`oddOrEven(13)` should return `"Odd"`. + +```js +assert.equal(oddOrEven(13), "Odd"); +``` + +`oddOrEven(196)` should return `"Even"`. + +```js +assert.equal(oddOrEven(196), "Even"); +``` + +`oddOrEven(123456789)` should return `"Odd"`. + +```js +assert.equal(oddOrEven(123456789), "Odd"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function oddOrEven(n) { + + return n; +} +``` + +# --solutions-- + +```js +function oddOrEven(n) { + return n % 2 === 0 ? "Even" : "Odd"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6939b873185d8e00d453563c.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6939b873185d8e00d453563c.md new file mode 100644 index 0000000000000000000000000000000000000000..e2cf90079bffc9b7fc3cd830667b3094375261a4 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6939b873185d8e00d453563c.md @@ -0,0 +1,58 @@ +--- +id: 6939b873185d8e00d453563c +title: "Challenge 157: Markdown Link Parser" +challengeType: 28 +dashedName: challenge-157 +--- + +# --description-- + +Given the string of a link in Markdown, return the equivalent HTML string. + +A Markdown image has the following format: `"[link_text](link_url)"`. Return the string of the HTML `a` tag with the `href` set to the `link_url` and the `link_text` as the tag content. + +For example, given `"[freeCodeCamp](https://freecodecamp.org/)"` return `'freeCodeCamp'`; + +Note: The console may not display HTML tags in strings when logging messages — check the browser console to see logs with tags included. + +# --hints-- + +`parseLink("[freeCodeCamp](https://freecodecamp.org/)")` should return `'freeCodeCamp'`. + +```js +assert.equal(parseLink("[freeCodeCamp](https://freecodecamp.org/)"), 'freeCodeCamp'); +``` + +`parseLink("[Donate to our charity.](https://www.freecodecamp.org/donate/)")` should return `'Donate to our charity.'`. + +```js +assert.equal(parseLink("[Donate to our charity.](https://www.freecodecamp.org/donate/)"), 'Donate to our charity.'); +``` + +`parseLink("[Contribute to our repository at https://github.com/freeCodeCamp/freeCodeCamp.](https://github.com/freeCodeCamp/freeCodeCamp/)")` should return `'Contribute to our repository at https://github.com/freeCodeCamp/freeCodeCamp.'`. + +```js +assert.equal(parseLink("[Contribute to our repository at https://github.com/freeCodeCamp/freeCodeCamp.](https://github.com/freeCodeCamp/freeCodeCamp/)"), 'Contribute to our repository at https://github.com/freeCodeCamp/freeCodeCamp.'); +``` + +# --seed-- + +## --seed-contents-- + +```js +function parseLink(markdown) { + + return markdown; +} +``` + +# --solutions-- + +```js +function parseLink(markdown) { + const match = markdown.match(/\[(.*?)\]\((.*?)\)/); + + const [, text, url] = match; + return `${text}`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6939b873185d8e00d453563d.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6939b873185d8e00d453563d.md new file mode 100644 index 0000000000000000000000000000000000000000..fa112d6b8dd6bc22cb1a71bcd1e50ae98d15f9ad --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6939b873185d8e00d453563d.md @@ -0,0 +1,58 @@ +--- +id: 6939b873185d8e00d453563d +title: "Challenge 158: Array Swap" +challengeType: 28 +dashedName: challenge-158 +--- + +# --description-- + +Given an array with two values, return an array with the values swapped. + +For example, given `["A", "B"]` return `["B", "A"]`. + +# --hints-- + +`arraySwap(["A", "B"])` should return `["B", "A"]`. + +```js +assert.deepEqual(arraySwap(["A", "B"]), ["B", "A"]); +``` + +`arraySwap([25, 20])` should return `[20, 25]`. + +```js +assert.deepEqual(arraySwap([25, 20]), [20, 25]); +``` + +`arraySwap([true, false])` should return `[false, true]`. + +```js +assert.deepEqual(arraySwap([true, false]), [false, true]); +``` + +`arraySwap(["1", 1])` should return `[1, "1"]`. + +```js +assert.deepEqual(arraySwap(["1", 1]), [1, "1"]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function arraySwap(arr) { + + return arr; +} +``` + +# --solutions-- + +```js +function arraySwap(arr) { + + return [arr[1], arr[0]]; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6939b873185d8e00d453563e.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6939b873185d8e00d453563e.md new file mode 100644 index 0000000000000000000000000000000000000000..1ddce8052b8a0f3dd9c5554c24c0c91aa70e0815 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6939b873185d8e00d453563e.md @@ -0,0 +1,71 @@ +--- +id: 6939b873185d8e00d453563e +title: "Challenge 159: Integer Hypotenuse" +challengeType: 28 +dashedName: challenge-159 +--- + +# --description-- + +Given two positive integers representing the lengths for the two legs (the two short sides) of a right triangle, determine whether the hypotenuse is an integer. + +The length of the hypotenuse is calculated by adding the squares of the two leg lengths together and then taking the square root of that total (a2 + b2 = c2). + +# --hints-- + +`isIntegerHypotenuse(3, 4)` should return `true`. + +```js +assert.isTrue(isIntegerHypotenuse(3, 4)); +``` + +`isIntegerHypotenuse(2, 3)` should return `false`. + +```js +assert.isFalse(isIntegerHypotenuse(2, 3)); +``` + +`isIntegerHypotenuse(5, 12)` should return `true`. + +```js +assert.isTrue(isIntegerHypotenuse(5, 12)); +``` + +`isIntegerHypotenuse(10, 10)` should return `false`. + +```js +assert.isFalse(isIntegerHypotenuse(10, 10)); +``` + +`isIntegerHypotenuse(780, 1040)` should return `true`. + +```js +assert.isTrue(isIntegerHypotenuse(780, 1040)); +``` + +`isIntegerHypotenuse(250, 333)` should return `false`. + +```js +assert.isFalse(isIntegerHypotenuse(250, 333)); +``` + +# --seed-- + +## --seed-contents-- + +```js +function isIntegerHypotenuse(a, b) { + + return a; +} +``` + +# --solutions-- + +```js +function isIntegerHypotenuse(a, b) { + const sum = a * a + b * b; + const c = Math.floor(Math.sqrt(sum)); + return c * c === sum; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6939b873185d8e00d453563f.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6939b873185d8e00d453563f.md new file mode 100644 index 0000000000000000000000000000000000000000..484df80b5045dfd60e217606db1924c7b90524de --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6939b873185d8e00d453563f.md @@ -0,0 +1,98 @@ +--- +id: 6939b873185d8e00d453563f +title: "Challenge 160: Knight Moves" +challengeType: 28 +dashedName: challenge-160 +--- + +# --description-- + +Given the position of a knight on a chessboard, return the number of valid squares the knight can move to. + +A standard chessboard is 8x8, with columns labeled `A` through `H` (left to right) and rows labeled `1` through `8` (bottom to top). It looks like this: + +|**A8**|**B8**|**C8**|**D8**|**E8**|**F8**|**G8**|**H8**| +|-|-|-|-|-|-|-|-| +|**A7**|**B7**|**C7**|**D7**|**E7**|**F7**|**G7**|**H7**| +|**A6**|**B6**|**C6**|**D6**|**E6**|**F6**|**G6**|**H6**| +|**A5**|**B5**|**C5**|**D5**|**E5**|**F5**|**G5**|**H5**| +|**A4**|**B4**|**C4**|**D4**|**E4**|**F4**|**G4**|**H4**| +|**A3**|**B3**|**C3**|**D3**|**E3**|**F3**|**G3**|**H3**| +|**A2**|**B2**|**C2**|**D2**|**E2**|**F2**|**G2**|**H2**| +|**A1**|**B1**|**C1**|**D1**|**E1**|**F1**|**G1**|**H1**| + +A knight moves in an "L" shape: two squares in one direction (horizontal or vertical), and one square in the perpendicular direction. + +This means a knight can move to up to eight possible positions, but fewer when near the edges of the board. For example, if a knight was at `A1`, it could only move to `B3` or `C2`. + +# --hints-- + +`knightMoves("A1")` should return `2`. + +```js +assert.equal(knightMoves("A1"), 2); +``` + +`knightMoves("D4")` should return `8`. + +```js +assert.equal(knightMoves("D4"), 8); +``` + +`knightMoves("G6")` should return `6`. + +```js +assert.equal(knightMoves("G6"), 6); +``` + +`knightMoves("B8")` should return `3`. + +```js +assert.equal(knightMoves("B8"), 3); +``` + +`knightMoves("H3")` should return `4`. + +```js +assert.equal(knightMoves("H3"), 4); +``` + +# --seed-- + +## --seed-contents-- + +```js +function knightMoves(position) { + + return position; +} +``` + +# --solutions-- + +```js +function knightMoves(position) { + const col = position[0].charCodeAt(0) - 65; + const row = parseInt(position[1]) - 1; + + const moves = [ + [2, 1], [2, -1], + [-2, 1], [-2, -1], + [1, 2], [1, -2], + [-1, 2], [-1, -2] + ]; + + let valid = 0; + + for (const [dx, dy] of moves) { + const newCol = col + dx; + const newRow = row + dy; + + if (newCol >= 0 && newCol < 8 && newRow >= 0 && newRow < 8) { + valid++; + } + } + + return valid; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/694596b0585c11170ac7c7f9.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/694596b0585c11170ac7c7f9.md new file mode 100644 index 0000000000000000000000000000000000000000..4b0aa29e2b76d50c29b078226400e1dbaa294f71 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/694596b0585c11170ac7c7f9.md @@ -0,0 +1,93 @@ +--- +id: 694596b0585c11170ac7c7f9 +title: "Challenge 161: Free Shipping" +challengeType: 28 +dashedName: challenge-161 +--- + +# --description-- + +Given an array of strings representing items in your shopping cart, and a number for the minimum order amount to qualify for free shipping, determine if the items in your shopping cart qualify for free shipping. + +The given array will contain items from the list below: + +| Item | Price | +| - | - | +| `"shirt"` | 34.25 | +| `"jeans"` | 48.50 | +| `"shoes"` | 75.00 | +| `"hat"` | 19.95 | +| `"socks"` | 15.00 | +| `"jacket"` | 109.95 | + +# --hints-- + +`getsFreeShipping(["shoes"], 50)` should return `true`. + +```js +assert.isTrue(getsFreeShipping(["shoes"], 50)); +``` + +`getsFreeShipping(["hat", "socks"], 50)` should return `false`. + +```js +assert.isFalse(getsFreeShipping(["hat", "socks"], 50)); +``` + +`getsFreeShipping(["jeans", "shirt", "jacket"], 75)` should return `true`. + +```js +assert.isTrue(getsFreeShipping(["jeans", "shirt", "jacket"], 75)); +``` + +`getsFreeShipping(["socks", "socks", "hat"], 75)` should return `false`. + +```js +assert.isFalse(getsFreeShipping(["socks", "socks", "hat"], 75)); +``` + +`getsFreeShipping(["shirt", "shirt", "jeans", "socks"], 100)` should return `true`. + +```js +assert.isTrue(getsFreeShipping(["shirt", "shirt", "jeans", "socks"], 100)); +``` + +`getsFreeShipping(["hat", "socks", "hat", "jeans", "shoes", "hat"], 200)` should return `false`. + +```js +assert.isFalse(getsFreeShipping(["hat", "socks", "hat", "jeans", "shoes", "hat"], 200)); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getsFreeShipping(cart, minimum) { + + return cart; +} +``` + +# --solutions-- + +```js +function getsFreeShipping(cart, minimum) { + const prices = { + shirt: 34.25, + jeans: 48.50, + shoes: 75.00, + hat: 19.95, + socks: 15.00, + jacket: 109.95 + }; + + let total = 0; + + for (const item of cart) { + total += prices[item]; + } + + return total >= minimum; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/694596b0585c11170ac7c7fa.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/694596b0585c11170ac7c7fa.md new file mode 100644 index 0000000000000000000000000000000000000000..876583cb670d699b4c0606e2faad20f70062caa4 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/694596b0585c11170ac7c7fa.md @@ -0,0 +1,85 @@ +--- +id: 694596b0585c11170ac7c7fa +title: "Challenge 162: Energy Consumption" +challengeType: 28 +dashedName: challenge-162 +--- + +# --description-- + +Given the number of Calories burned during a workout, and the number of watt-hours used by your electronic devices during that workout, determine which one used more energy. + +To compare them, convert both values to joules using the following conversions: + +- 1 Calorie equals 4184 joules. +- 1 watt-hour equals 3600 joules. + +Return: + +- `"Workout"` if the workout used more energy. +- `"Devices"` if the device used more energy. +- `"Equal"` if both used the same amount of energy. + +# --hints-- + +`compareEnergy(250, 50)` should return `"Workout"`. + +```js +assert.equal(compareEnergy(250, 50), "Workout"); +``` + +`compareEnergy(100, 200)` should return `"Devices"`. + +```js +assert.equal(compareEnergy(100, 200), "Devices"); +``` + +`compareEnergy(450, 523)` should return `"Equal"`. + +```js +assert.equal(compareEnergy(450, 523), "Equal"); +``` + +`compareEnergy(300, 75)` should return `"Workout"`. + +```js +assert.equal(compareEnergy(300, 75), "Workout"); +``` + +`compareEnergy(200, 250)` should return `"Devices"`. + +```js +assert.equal(compareEnergy(200, 250), "Devices"); +``` + +`compareEnergy(900, 1046)` should return `"Equal"`. + +```js +assert.equal(compareEnergy(900, 1046), "Equal"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function compareEnergy(caloriesBurned, wattHoursUsed) { + + return caloriesBurned; +} +``` + +# --solutions-- + +```js +function compareEnergy(caloriesBurned, wattHoursUsed) { + const workoutEnergy = caloriesBurned * 4184; + const deviceEnergy = wattHoursUsed * 3600; + + console.log(workoutEnergy); + console.log(deviceEnergy); + if (workoutEnergy > deviceEnergy) return "Workout"; + if (deviceEnergy > workoutEnergy) return "Devices"; + return "Equal"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/694596b0585c11170ac7c7fb.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/694596b0585c11170ac7c7fb.md new file mode 100644 index 0000000000000000000000000000000000000000..796436bfbc11db93d6858606a3eb5d5671d728d7 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/694596b0585c11170ac7c7fb.md @@ -0,0 +1,76 @@ +--- +id: 694596b0585c11170ac7c7fb +title: "Challenge 163: Consonant Case" +challengeType: 28 +dashedName: challenge-163 +--- + +# --description-- + +Given a string representing a variable name, convert it to consonant case using the following rules: + +- All consonants should be converted to uppercase. +- All vowels (`a`, `e`, `i`, `o`, `u` in any case) should be converted to lowercase. +- All hyphens (`-`) should be converted to underscores (`_`). + +# --hints-- + +`toConsonantCase("helloworld")` should return `"HeLLoWoRLD"`. + +```js +assert.equal(toConsonantCase("helloworld"), "HeLLoWoRLD"); +``` + +`toConsonantCase("HELLOWORLD")` should return `"HeLLoWoRLD"`. + +```js +assert.equal(toConsonantCase("HELLOWORLD"), "HeLLoWoRLD"); +``` + +`toConsonantCase("_hElLO-WOrlD-")` should return `"_HeLLo_WoRLD_"`. + +```js +assert.equal(toConsonantCase("_hElLO-WOrlD-"), "_HeLLo_WoRLD_"); +``` + +`toConsonantCase("_~-generic_~-variable_~-name_~-here-~_")` should return `"_~_GeNeRiC_~_VaRiaBLe_~_NaMe_~_HeRe_~_"`. + +```js +assert.equal(toConsonantCase("_~-generic_~-variable_~-name_~-here-~_"), "_~_GeNeRiC_~_VaRiaBLe_~_NaMe_~_HeRe_~_"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function toConsonantCase(str) { + + return str; +} +``` + +# --solutions-- + +```js +function toConsonantCase(str) { + const vowels = "aeiouAEIOU"; + let result = ""; + + for (let char of str) { + if (char === "-") { + result += "_"; + } else if (/[a-zA-Z]/.test(char)) { + if (vowels.includes(char)) { + result += char.toLowerCase(); + } else { + result += char.toUpperCase(); + } + } else { + result += char; + } + } + + return result; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/694596b0585c11170ac7c7fc.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/694596b0585c11170ac7c7fc.md new file mode 100644 index 0000000000000000000000000000000000000000..450d6eccb67c09f53ec21b65e79bec0ce5a6e774 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/694596b0585c11170ac7c7fc.md @@ -0,0 +1,57 @@ +--- +id: 694596b0585c11170ac7c7fc +title: "Challenge 164: Markdown Inline Code Parser" +challengeType: 28 +dashedName: challenge-164 +--- + +# --description-- + +Given a string of Markdown that includes one or more inline code blocks, return the equivalent HTML string. + +Inline code blocks in Markdown use a single backtick (``` ` ```) at the start and end of the code block text. + +Return the given string with all code blocks converted to HTML `code` tags. + +For example, given the string ```"Use `let` to declare the variable."```, return `"Use let to declare the variable."`. + +Note: The console may not display HTML tags in strings when logging messages. Check the browser console to see logs with tags included. + +# --hints-- + +```parseInlineCode("Use `let` to declare the variable.")``` should return `"Use let to declare the variable."`. + +```js +assert.equal(parseInlineCode("Use `let` to declare the variable."), "Use let to declare the variable."); +``` + +```parseInlineCode("Use `let` or `const` to declare a variable.")``` should return `"Use let or const to declare a variable."`. + +```js +assert.equal(parseInlineCode("Use `let` or `const` to declare a variable."), "Use let or const to declare a variable."); +``` + +```parseInlineCode("Run `npm install` then `npm start`.")``` should return `"Run npm install then npm start."`. + +```js +assert.equal(parseInlineCode("Run `npm install` then `npm start`."), "Run npm install then npm start."); +``` + +# --seed-- + +## --seed-contents-- + +```js +function parseInlineCode(markdown) { + + return markdown; +} +``` + +# --solutions-- + +```js +function parseInlineCode(markdown) { + return markdown.replace(/`([^`]+)`/g, "$1"); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/694596b0585c11170ac7c7fd.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/694596b0585c11170ac7c7fd.md new file mode 100644 index 0000000000000000000000000000000000000000..e15551a4e27321070b767960e0ae4927761ad3ea --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/694596b0585c11170ac7c7fd.md @@ -0,0 +1,104 @@ +--- +id: 694596b0585c11170ac7c7fd +title: "Challenge 165: Class Average" +challengeType: 28 +dashedName: challenge-165 +--- + +# --description-- + +Given an array of exam scores (numbers), return the average score in form of a letter grade according to the following chart: + +| Average Score | Letter Grade | +| - | - | +| 97-100 | `"A+"` | +| 93-96 | `"A"` | +| 90-92 | `"A-"` | +| 87-89 | `"B+"` | +| 83-86 | `"B"` | +| 80-82 | `"B-"` | +| 77-79 | `"C+"` | +| 73–76 | `"C"` | +| 70-72 | `"C-"` | +| 67-69 | `"D+"` | +| 63-66 | `"D"` | +| 60–62 | `"D-"` | +| below 60 | `"F"` | + +Calculate the average by adding all scores in the array and dividing by the total number of scores. + +# --hints-- + +`getAverageGrade([92, 91, 90, 94, 89, 93])` should return `"A-"`. + +```js +assert.equal(getAverageGrade([92, 91, 90, 94, 89, 93]), "A-"); +``` + +`getAverageGrade([84, 89, 85, 100, 91, 88, 79])` should return `"B+"`. + +```js +assert.equal(getAverageGrade([84, 89, 85, 100, 91, 88, 79]), "B+"); +``` + +`getAverageGrade([63, 69, 65, 66, 71, 64, 65])` should return `"D"`. + +```js +assert.equal(getAverageGrade([63, 69, 65, 66, 71, 64, 65]), "D"); +``` + +`getAverageGrade([97, 98, 99, 100, 96, 97, 98, 99, 100])` should return `"A+"`. + +```js +assert.equal(getAverageGrade([97, 98, 99, 100, 96, 97, 98, 99, 100]), "A+"); +``` + +`getAverageGrade([75, 100, 88, 79, 80, 78, 64, 60])` should return `"C+"`. + +```js +assert.equal(getAverageGrade([75, 100, 88, 79, 80, 78, 64, 60]), "C+"); +``` + +`getAverageGrade([45, 48, 50, 52, 100, 54, 56, 58, 59])` should return `"F"`. + +```js +assert.equal(getAverageGrade([45, 48, 50, 52, 100, 54, 56, 58, 59]), "F"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getAverageGrade(scores) { + + return scores; +} +``` + +# --solutions-- + +```js +function getAverageGrade(scores) { + const avg = + scores.reduce((sum, score) => sum + score, 0) / scores.length; + + if (avg >= 97) return "A+"; + if (avg >= 93) return "A"; + if (avg >= 90) return "A-"; + + if (avg >= 87) return "B+"; + if (avg >= 83) return "B"; + if (avg >= 80) return "B-"; + + if (avg >= 77) return "C+"; + if (avg >= 73) return "C"; + if (avg >= 70) return "C-"; + + if (avg >= 67) return "D+"; + if (avg >= 63) return "D"; + if (avg >= 60) return "D-"; + + return "F"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/696655d24b614176d4c9b789.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/696655d24b614176d4c9b789.md new file mode 100644 index 0000000000000000000000000000000000000000..eefeb547bb4f5a79d0b4c32ef5bd653576a7b97e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/696655d24b614176d4c9b789.md @@ -0,0 +1,95 @@ +--- +id: 696655d24b614176d4c9b789 +title: "Challenge 166: Hex Validator" +challengeType: 28 +dashedName: challenge-166 +--- + +# --description-- + +Given a string, determine whether it is a valid CSS hex color. A valid CSS hex color must: + +- Start with a `#`, and +- be followed by either 3 or 6 hexadecimal characters. + +Hexadecimal characters are numbers `0` through `9` and letters `a` through `f` (case-insensitive). + +# --hints-- + +`isValidHex("#123")` should return `true`. + +```js +assert.isTrue(isValidHex("#123")); +``` + +`isValidHex("#123abc")` should return `true`. + +```js +assert.isTrue(isValidHex("#123abc")); +``` + +`isValidHex("#ABCDEF")` should return `true`. + +```js +assert.isTrue(isValidHex("#ABCDEF")); +``` + +`isValidHex("#0a1B2c")` should return `true`. + +```js +assert.isTrue(isValidHex("#0a1B2c")); +``` + +`isValidHex("#12G")` should return `false`. + +```js +assert.isFalse(isValidHex("#12G")); +``` + +`isValidHex("#1234567")` should return `false`. + +```js +assert.isFalse(isValidHex("#1234567")); +``` + +`isValidHex("#12 3")` should return `false`. + +```js +assert.isFalse(isValidHex("#12 3")); +``` + +`isValidHex("fff")` should return `false`. + +```js +assert.isFalse(isValidHex("fff")); +``` + +# --seed-- + +## --seed-contents-- + +```js +function isValidHex(str) { + + return str; +} +``` + +# --solutions-- + +```js +function isValidHex(str) { + if (str[0] !== "#") return false; + + const hex = str.slice(1); + if (hex.length !== 3 && hex.length !== 6) return false; + + for (let char of hex) { + if (!/[0-9a-fA-F]/.test(char)) { + return false; + } + } + + return true; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/696655d24b614176d4c9b78a.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/696655d24b614176d4c9b78a.md new file mode 100644 index 0000000000000000000000000000000000000000..fa8bcd0b0c0d740f6eadfec0f5b1eefb6238d58c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/696655d24b614176d4c9b78a.md @@ -0,0 +1,74 @@ +--- +id: 696655d24b614176d4c9b78a +title: "Challenge 167: Bingo! Letter" +challengeType: 28 +dashedName: challenge-167 +--- + +# --description-- + +Given a number, return the bingo letter associated with it (capitalized). Bingo numbers are grouped as follows: + +| Letter | Number Range | +| - | - | +| `"B"` | 1-15 | +| `"I"` | 16-30 | +| `"N"` | 31-45 | +| `"G"` | 46-60 | +| `"O"` | 61-75 | + +# --hints-- + +`getBingoLetter(75)` should return `"O"`. + +```js +assert.equal(getBingoLetter(75), "O"); +``` + +`getBingoLetter(54)` should return `"G"`. + +```js +assert.equal(getBingoLetter(54), "G"); +``` + +`getBingoLetter(25)` should return `"I"`. + +```js +assert.equal(getBingoLetter(25), "I"); +``` + +`getBingoLetter(38)` should return `"N"`. + +```js +assert.equal(getBingoLetter(38), "N"); +``` + +`getBingoLetter(11)` should return `"B"`. + +```js +assert.equal(getBingoLetter(11), "B"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getBingoLetter(n) { + + return n; +} +``` + +# --solutions-- + +```js +function getBingoLetter(n) { + if (n >= 1 && n <= 15) return "B"; + if (n >= 16 && n <= 30) return "I"; + if (n >= 31 && n <= 45) return "N"; + if (n >= 46 && n <= 60) return "G"; + if (n >= 61 && n <= 75) return "O"; + return null; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/696655d24b614176d4c9b78b.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/696655d24b614176d4c9b78b.md new file mode 100644 index 0000000000000000000000000000000000000000..7ca2616b271cac7f9ce929e42b9b1c673abc30d2 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/696655d24b614176d4c9b78b.md @@ -0,0 +1,65 @@ +--- +id: 696655d24b614176d4c9b78b +title: "Challenge 168: Scaled Image" +challengeType: 28 +dashedName: challenge-168 +--- + +# --description-- + +Given a string representing the width and height of an image, and a number to scale the image, return the scaled width and height. + +- The input string is in the format `"WxH"`. For example, `"800x600"`. +- The scale is a number to multiply the width and height by. + +Return the scaled dimensions in the same `"WxH"` format. + +# --hints-- + +`scaleImage("800x600", 2)` should return `"1600x1200"`. + +```js +assert.equal(scaleImage("800x600", 2), "1600x1200"); +``` + +`scaleImage("100x100", 10)` should return `"1000x1000"`. + +```js +assert.equal(scaleImage("100x100", 10), "1000x1000"); +``` + +`scaleImage("1024x768", 0.5)` should return `"512x384"`. + +```js +assert.equal(scaleImage("1024x768", 0.5), "512x384"); +``` + +`scaleImage("300x200", 1.5)` should return `"450x300"`. + +```js +assert.equal(scaleImage("300x200", 1.5), "450x300"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function scaleImage(size, scale) { + + return size; +} +``` + +# --solutions-- + +```js +function scaleImage(size, scale) { + const [width, height] = size.split("x").map(Number); + + const newWidth = width * scale; + const newHeight = height * scale; + + return `${newWidth}x${newHeight}`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/696655d24b614176d4c9b78c.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/696655d24b614176d4c9b78c.md new file mode 100644 index 0000000000000000000000000000000000000000..c8eaedd36b9f511abbd1382080ca99b19489bfe1 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/696655d24b614176d4c9b78c.md @@ -0,0 +1,69 @@ +--- +id: 696655d24b614176d4c9b78c +title: "Challenge 169: FizzBuzz Mini" +challengeType: 28 +dashedName: challenge-169 +--- + +# --description-- + +Given an integer, return a string based on the following rules: + +- If the number is divisible by 3, return `"Fizz"`. +- If the number is divisible by 5, return `"Buzz"`. +- If the number is divisible by both 3 and 5, return `"FizzBuzz"`. +- Otherwise, return the given number as a string. + +# --hints-- + +`fizzBuzzMini(3)` should return `"Fizz"`. + +```js +assert.equal(fizzBuzzMini(3), "Fizz"); +``` + +`fizzBuzzMini(4)` should return `"4"`. + +```js +assert.strictEqual(fizzBuzzMini(4), "4"); +``` + +`fizzBuzzMini(35)` should return `"Buzz"`. + +```js +assert.equal(fizzBuzzMini(35), "Buzz"); +``` + +`fizzBuzzMini(75)` should return `"FizzBuzz"`. + +```js +assert.equal(fizzBuzzMini(75), "FizzBuzz"); +``` + +`fizzBuzzMini(98)` should return `"98"`. + +```js +assert.strictEqual(fizzBuzzMini(98), "98"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function fizzBuzzMini(n) { + + return n; +} +``` + +# --solutions-- + +```js +function fizzBuzzMini(n) { + if (n % 3 === 0 && n % 5 === 0) return "FizzBuzz"; + if (n % 3 === 0) return "Fizz"; + if (n % 5 === 0) return "Buzz"; + return String(n); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/696655d24b614176d4c9b78d.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/696655d24b614176d4c9b78d.md new file mode 100644 index 0000000000000000000000000000000000000000..7ad9a9bd80dd0244f49a19ede7c57b033f0925d5 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/696655d24b614176d4c9b78d.md @@ -0,0 +1,71 @@ +--- +id: 696655d24b614176d4c9b78d +title: "Challenge 170: Odd or Even Day" +challengeType: 28 +dashedName: challenge-170 +--- + +# --description-- + +Given a timestamp (number of milliseconds since the Unix epoch), return: + +- `"odd"` if the day of the month for that timestamp is odd. +- `"even"` if the day of the month for that timestamp is even. + +For example, given `1769472000000`, a timestamp for January 27th, 2026, return `"odd"` because the day number (`27`) is an odd number. + +Note: The timestamp is in milliseconds and you should use the date in the UTC timezone, not in your local time. + +# --hints-- + +`oddOrEvenDay(1769472000000)` should return `"odd"`. + +```js +assert.equal(oddOrEvenDay(1769472000000), "odd"); +``` + +`oddOrEvenDay(1769444440000)` should return `"even"`. + +```js +assert.equal(oddOrEvenDay(1769444440000), "even"); +``` + +`oddOrEvenDay(6739456780000)` should return `"odd"`. + +```js +assert.equal(oddOrEvenDay(6739456780000), "odd"); +``` + +`oddOrEvenDay(1)` should return `"odd"`. + +```js +assert.equal(oddOrEvenDay(1), "odd"); +``` + +`oddOrEvenDay(86400000)` should return `"even"`. + +```js +assert.equal(oddOrEvenDay(86400000), "even"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function oddOrEvenDay(timestamp) { + + return timestamp; +} +``` + +# --solutions-- + +```js +function oddOrEvenDay(timestamp) { + const date = new Date(timestamp); + const day = date.getUTCDate(); + + return day % 2 === 0 ? "even" : "odd"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69738771fb5a7b8b24cca29d.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69738771fb5a7b8b24cca29d.md new file mode 100644 index 0000000000000000000000000000000000000000..8fb254e259c6dd022f5130127b64f16b06d45ac3 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69738771fb5a7b8b24cca29d.md @@ -0,0 +1,71 @@ +--- +id: 69738771fb5a7b8b24cca29d +title: "Challenge 171: Flatten the Array" +challengeType: 28 +dashedName: challenge-171 +--- + +# --description-- + +Given an array that contains nested arrays, return a new array with all values flattened into a single, one-dimensional array. Retain the original order of the items in the arrays. + +# --hints-- + +`flatten([1, [2, 3], 4])` should return `[1, 2, 3, 4]`. + +```js +assert.deepEqual(flatten([1, [2, 3], 4]), [1, 2, 3, 4]); +``` + +`flatten([5, [4, [3, 2]], 1])` should return `[5, 4, 3, 2, 1]`. + +```js +assert.deepEqual(flatten([5, [4, [3, 2]], 1]), [5, 4, 3, 2, 1]); +``` + +`flatten(["A", [[[["B"]]]], "C"])` should return `["A", "B", "C"]`. + +```js +assert.deepEqual(flatten(["A", [[[["B"]]]], "C"]), ["A", "B", "C"]); +``` + +`flatten([["L", "M", "N"], ["O", ["P", "Q", ["R", ["S", ["T", "U"]]]]], "V", ["W", ["X", ["Y", ["Z"]]]]])` should return `["L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]`. + +```js +assert.deepEqual(flatten([["L", "M", "N"], ["O", ["P", "Q", ["R", ["S", ["T", "U"]]]]], "V", ["W", ["X", ["Y", ["Z"]]]]]), ["L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]); +``` + +`flatten([["red", ["blue", ["green", ["yellow", ["purple"]]]]], "orange", ["pink", ["brown"]]])` should return `["red","blue","green","yellow","purple","orange","pink","brown"]`. + +```js +assert.deepEqual(flatten([["red", ["blue", ["green", ["yellow", ["purple"]]]]], "orange", ["pink", ["brown"]]]), ["red","blue","green","yellow","purple","orange","pink","brown"]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function flatten(arr) { + + return arr; +} +``` + +# --solutions-- + +```js +function flatten(arr) { + let result = []; + + for (const item of arr) { + if (Array.isArray(item)) { + result = result.concat(flatten(item)); + } else { + result.push(item); + } + } + + return result; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69738771fb5a7b8b24cca29e.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69738771fb5a7b8b24cca29e.md new file mode 100644 index 0000000000000000000000000000000000000000..3c51b33e906b980f3f381d175981784ee2d31a98 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69738771fb5a7b8b24cca29e.md @@ -0,0 +1,73 @@ +--- +id: 69738771fb5a7b8b24cca29e +title: "Challenge 172: Letters-Numbers" +challengeType: 28 +dashedName: challenge-172 +--- + +# --description-- + +Given a string containing only letters and numbers, return a new string where a hyphen (`-`) is inserted every time the string switches from a letter to a number, or a number to a letter. + +# --hints-- + +`separateLettersAndNumbers("ABC123")` should return `"ABC-123"`. + +```js +assert.equal(separateLettersAndNumbers("ABC123"), "ABC-123"); +``` + +`separateLettersAndNumbers("Route66")` should return `"Route-66"`. + +```js +assert.equal(separateLettersAndNumbers("Route66"), "Route-66"); +``` + +`separateLettersAndNumbers("H3LL0W0RLD")` should return `"H-3-LL-0-W-0-RLD"`. + +```js +assert.equal(separateLettersAndNumbers("H3LL0W0RLD"), "H-3-LL-0-W-0-RLD"); +``` + +`separateLettersAndNumbers("a1b2c3d4")` should return `"a-1-b-2-c-3-d-4"`. + +```js +assert.equal(separateLettersAndNumbers("a1b2c3d4"), "a-1-b-2-c-3-d-4"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function separateLettersAndNumbers(str) { + + return str; +} +``` + +# --solutions-- + +```js +function separateLettersAndNumbers(str) { + if (str.length === 0) return str; + + let result = str[0]; + + for (let i = 1; i < str.length; i++) { + const prev = str[i - 1]; + const curr = str[i]; + + const prevIsLetter = /[a-zA-Z]/.test(prev); + const currIsLetter = /[a-zA-Z]/.test(curr); + + if (prevIsLetter !== currIsLetter) { + result += "-"; + } + + result += curr; + } + + return result; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69738771fb5a7b8b24cca29f.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69738771fb5a7b8b24cca29f.md new file mode 100644 index 0000000000000000000000000000000000000000..6cf00ebf698c6987e1dda0dd48a1e54c28f68f38 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69738771fb5a7b8b24cca29f.md @@ -0,0 +1,93 @@ +--- +id: 69738771fb5a7b8b24cca29f +title: "Challenge 173: Valid Pawn Moves" +challengeType: 28 +dashedName: challenge-173 +--- + +# --description-- + +Given the position of one of your pawns on a chessboard, return an array of all the valid squares it can move to in ascending order. + +A standard chessboard is 8x8, with columns labeled `A` through `H` (left to right) and rows labeled `1` through `8` (bottom to top). It looks like this: + +|**A8**|**B8**|**C8**|**D8**|**E8**|**F8**|**G8**|**H8**| +|-|-|-|-|-|-|-|-| +|**A7**|**B7**|**C7**|**D7**|**E7**|**F7**|**G7**|**H7**| +|**A6**|**B6**|**C6**|**D6**|**E6**|**F6**|**G6**|**H6**| +|**A5**|**B5**|**C5**|**D5**|**E5**|**F5**|**G5**|**H5**| +|**A4**|**B4**|**C4**|**D4**|**E4**|**F4**|**G4**|**H4**| +|**A3**|**B3**|**C3**|**D3**|**E3**|**F3**|**G3**|**H3**| +|**A2**|**B2**|**C2**|**D2**|**E2**|**F2**|**G2**|**H2**| +|**A1**|**B1**|**C1**|**D1**|**E1**|**F1**|**G1**|**H1**| + +For this challenge: + +- You are the player on the bottom of the board. +- Pawns can only move one square "up". +- Unless the pawn is in the starting row (row 2), then it can move one or two squares up. + +For example, given `"D4"`, return `["D5"]`, the only square your pawn can move to. +Given `"B2"`, return `["B3", "B4"]`, because it's on the starting row and needs to be in ascending order. + +# --hints-- + +`findPawnMoves("D4")` should return `["D5"]`. + +```js +assert.deepEqual(findPawnMoves("D4"), ["D5"]); +``` + +`findPawnMoves("B2")` should return `["B3", "B4"]`. + +```js +assert.deepEqual(findPawnMoves("B2"), ["B3", "B4"]); +``` + +`findPawnMoves("A7")` should return `["A8"]`. + +```js +assert.deepEqual(findPawnMoves("A7"), ["A8"]); +``` + +`findPawnMoves("G2")` should return `["G3", "G4"]`. + +```js +assert.deepEqual(findPawnMoves("G2"), ["G3", "G4"]); +``` + +`findPawnMoves("E3")` should return `["E4"]`. + +```js +assert.deepEqual(findPawnMoves("E3"), ["E4"]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function findPawnMoves(position) { + + return position; +} + +``` + +# --solutions-- + +```js +function findPawnMoves(position) { + const column = position[0].toUpperCase(); + const row = parseInt(position[1]); + const moves = []; + + if (row >= 8) return moves; + + moves.push(`${column}${row + 1}`); + + if (row === 2) moves.push(`${column}${row + 2}`); + + return moves; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69738771fb5a7b8b24cca2a0.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69738771fb5a7b8b24cca2a0.md new file mode 100644 index 0000000000000000000000000000000000000000..c6760ae8ad62933bfe83eb0d9f752bec3c457324 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69738771fb5a7b8b24cca2a0.md @@ -0,0 +1,117 @@ +--- +id: 69738771fb5a7b8b24cca2a0 +title: "Challenge 174: Zodiac Finder" +challengeType: 28 +dashedName: challenge-174 +--- + +# --description-- + +Given a date string in the format `"YYYY-MM-DD"`, return the zodiac sign for that date using the following chart: + +| Date Range | Zodiac Sign | +| - | - | +| March 21 - April 19 | `"Aries"` | +| April 20 - May 20 | `"Taurus"` | +| May 21 - June 20 | `"Gemini"` | +| June 21 - July 22 | `"Cancer"` | +| July 23 - August 22 | `"Leo"` | +| August 23 - September 22 | `"Virgo"` | +| September 23 - October 22 | `"Libra"` | +| October 23 - November 21 | `"Scorpio"` | +| November 22 - December 21 | `"Sagittarius"` | +| December 22 - January 19 | `"Capricorn"` | +| January 20 - February 18 | `"Aquarius"` | +| February 19 - March 20 | `"Pisces"` | + +- Zodiac signs are based only on the month and day, you can ignore the year. + +# --hints-- + +`getSign("2026-01-31")` should return `"Aquarius"`. + +```js +assert.equal(getSign("2026-01-31"), "Aquarius"); +``` + +`getSign("2001-06-10")` should return `"Gemini"`. + +```js +assert.equal(getSign("2001-06-10"), "Gemini"); +``` + +`getSign("1985-09-07")` should return `"Virgo"`. + +```js +assert.equal(getSign("1985-09-07"), "Virgo"); +``` + +`getSign("2023-03-19")` should return `"Pisces"`. + +```js +assert.equal(getSign("2023-03-19"), "Pisces"); +``` + +`getSign("2045-11-05")` should return `"Scorpio"`. + +```js +assert.equal(getSign("2045-11-05"), "Scorpio"); +``` + +`getSign("1985-12-06")` should return `"Sagittarius"`. + +```js +assert.equal(getSign("1985-12-06"), "Sagittarius"); +``` + +`getSign("2025-12-30")` should return `"Capricorn"`. + +```js +assert.equal(getSign("2025-12-30"), "Capricorn"); +``` + +`getSign("2018-10-08")` should return `"Libra"`. + +```js +assert.equal(getSign("2018-10-08"), "Libra"); +``` + +`getSign("1958-05-04")` should return `"Taurus"`. + +```js +assert.equal(getSign("1958-05-04"), "Taurus"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getSign(dateStr) { + + return dateStr; +} +``` + +# --solutions-- + +```js +function getSign(dateStr) { + const [, monthStr, dayStr] = dateStr.split("-"); + const month = Number(monthStr); + const day = Number(dayStr); + + if ((month === 3 && day >= 21) || (month === 4 && day <= 19)) return "Aries"; + if ((month === 4 && day >= 20) || (month === 5 && day <= 20)) return "Taurus"; + if ((month === 5 && day >= 21) || (month === 6 && day <= 20)) return "Gemini"; + if ((month === 6 && day >= 21) || (month === 7 && day <= 22)) return "Cancer"; + if ((month === 7 && day >= 23) || (month === 8 && day <= 22)) return "Leo"; + if ((month === 8 && day >= 23) || (month === 9 && day <= 22)) return "Virgo"; + if ((month === 9 && day >= 23) || (month === 10 && day <= 22)) return "Libra"; + if ((month === 10 && day >= 23) || (month === 11 && day <= 21)) return "Scorpio"; + if ((month === 11 && day >= 22) || (month === 12 && day <= 21)) return "Sagittarius"; + if ((month === 12 && day >= 22) || (month === 1 && day <= 19)) return "Capricorn"; + if ((month === 1 && day >= 20) || (month === 2 && day <= 18)) return "Aquarius"; + if ((month === 2 && day >= 19) || (month === 3 && day <= 20)) return "Pisces"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69738771fb5a7b8b24cca2a1.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69738771fb5a7b8b24cca2a1.md new file mode 100644 index 0000000000000000000000000000000000000000..38ac0dc831b76f39c2d46aa125e4c62831688980 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69738771fb5a7b8b24cca2a1.md @@ -0,0 +1,98 @@ +--- +id: 69738771fb5a7b8b24cca2a1 +title: "Challenge 175: Digital Detox" +challengeType: 28 +dashedName: challenge-175 +--- + +# --description-- + +Given an array of your login logs, determine whether you have met your digital detox goal. + +Each log is a string in the format `"YYYY-MM-DD HH:mm:ss"`. + +You have met your digital detox goal if both of the following statements are true: + +- You logged in no more than once within any four-hour period. +- You logged in no more than 2 times on any single day. + +# --hints-- + +`digitalDetox(["2026-02-01 08:00:00", "2026-02-01 12:30:00"])` should return `true`. + +```js +assert.isTrue(digitalDetox(["2026-02-01 08:00:00", "2026-02-01 12:30:00"])); +``` + +`digitalDetox(["2026-02-01 04:00:00", "2026-02-01 07:30:00"])` should return `false`. + +```js +assert.isFalse(digitalDetox(["2026-02-01 04:00:00", "2026-02-01 07:30:00"])); +``` + +`digitalDetox(["2026-01-31 08:21:30", "2026-01-31 14:30:00", "2026-02-01 08:00:00", "2026-02-01 12:30:00"])` should return `true`. + +```js +assert.isTrue(digitalDetox(["2026-01-31 08:21:30", "2026-01-31 14:30:00", "2026-02-01 08:00:00", "2026-02-01 12:30:00"])); +``` + +`digitalDetox(["2026-01-31 10:40:21", "2026-01-31 15:19:41", "2026-01-31 21:49:50", "2026-02-01 09:30:00"])` should return `false`. + +```js +assert.isFalse(digitalDetox(["2026-01-31 10:40:21", "2026-01-31 15:19:41", "2026-01-31 21:49:50", "2026-02-01 09:30:00"])); +``` + +`digitalDetox(["2026-02-05 10:00:00", "2026-02-01 09:00:00", "2026-02-03 22:15:00", "2026-02-02 12:10:00", "2026-02-02 07:15:00", "2026-02-04 09:45:00", "2026-02-01 16:50:00", "2026-02-03 09:30:00"])` should return `true`. + +```js +assert.isTrue(digitalDetox(["2026-02-05 10:00:00", "2026-02-01 09:00:00", "2026-02-03 20:15:00", "2026-02-02 12:10:00", "2026-02-02 07:15:00", "2026-02-04 09:45:00", "2026-02-01 16:50:00", "2026-02-03 09:30:00"])); +``` + +`digitalDetox(["2026-02-05 10:00:00", "2026-02-01 09:00:00", "2026-02-03 22:15:00", "2026-02-02 12:10:00", "2026-02-02 07:15:00", "2026-02-04 01:45:00", "2026-02-01 16:50:00", "2026-02-03 09:30:00"])` should return `false`. + +```js +assert.isFalse(digitalDetox(["2026-02-05 10:00:00", "2026-02-01 09:00:00", "2026-02-03 22:15:00", "2026-02-02 12:10:00", "2026-02-02 07:15:00", "2026-02-04 01:45:00", "2026-02-01 16:50:00", "2026-02-03 09:30:00"])); +``` + +# --seed-- + +## --seed-contents-- + +```js +function digitalDetox(logs) { + + return logs; +} +``` + +# --solutions-- + +```js +function digitalDetox(logs) { + if (logs.length === 0) return true; + + const times = logs + .map(log => new Date(log.replace(" ", "T") + "Z").getTime()) + .sort((a, b) => a - b); + + const ONE_DAY = 24 * 60 * 60 * 1000; + const FOUR_HOURS = 4 * 60 * 60 * 1000; + + for (let i = 1; i < times.length; i++) { + if (times[i] - times[i - 1] < FOUR_HOURS) { + return false; + } + } + + const dailyCounts = {}; + for (const time of times) { + const day = new Date(time).toISOString().slice(0, 10); + dailyCounts[day] = (dailyCounts[day] || 0) + 1; + if (dailyCounts[day] > 2) { + return false; + } + } + + return true; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69738771fb5a7b8b24cca2a2.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69738771fb5a7b8b24cca2a2.md new file mode 100644 index 0000000000000000000000000000000000000000..d7ce95a43b562bdc1d2bfb240969adfe2c11a0d5 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69738771fb5a7b8b24cca2a2.md @@ -0,0 +1,69 @@ +--- +id: 69738771fb5a7b8b24cca2a2 +title: "Challenge 176: Groundhog Day" +challengeType: 28 +dashedName: challenge-176 +--- + +# --description-- + +Today is Groundhog Day, in which a groundhog predicts the weather based on whether or not it sees its shadow. + +Given a value representing the groundhog's appearance, return the correct prediction: + +- If the given value is the boolean `true` (the groundhog saw its shadow), return `"Looks like we'll have six more weeks of winter."`. +- If the value is the boolean `false` (the groundhog did not see its shadow), return `"It's going to be an early spring."`. +- If the value is anything else (the groundhog did not show up), return `"No prediction this year."`. + +# --hints-- + +`groundhogDayPrediction(true)` should return `"Looks like we'll have six more weeks of winter."`. + +```js +assert.equal(groundhogDayPrediction(true), "Looks like we'll have six more weeks of winter."); +``` + +`groundhogDayPrediction(false)` should return `"It's going to be an early spring."`. + +```js +assert.equal(groundhogDayPrediction(false), "It's going to be an early spring."); +``` + +`groundhogDayPrediction(null)` should return `"No prediction this year."`. + +```js +assert.equal(groundhogDayPrediction(null), "No prediction this year."); +``` + +`groundhogDayPrediction(" ")` should return `"No prediction this year."`. + +```js +assert.equal(groundhogDayPrediction(" "), "No prediction this year."); +``` + +`groundhogDayPrediction("true")` should return `"No prediction this year."`. + +```js +assert.equal(groundhogDayPrediction("true"), "No prediction this year."); +``` + +# --seed-- + +## --seed-contents-- + +```js +function groundhogDayPrediction(appearance) { + + return appearance; +} +``` + +# --solutions-- + +```js +function groundhogDayPrediction(appearance) { + if (appearance === true) return "Looks like we'll have six more weeks of winter."; + if (appearance === false) return "It's going to be an early spring."; + return "No prediction this year."; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69738771fb5a7b8b24cca2a3.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69738771fb5a7b8b24cca2a3.md new file mode 100644 index 0000000000000000000000000000000000000000..a336dc027d44bbbd553eabeb7de18c48be7216e4 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69738771fb5a7b8b24cca2a3.md @@ -0,0 +1,56 @@ +--- +id: 69738771fb5a7b8b24cca2a3 +title: "Challenge 177: String Mirror" +challengeType: 28 +dashedName: challenge-177 +--- + +# --description-- + +Given a string, return a new string that consists of the given string with a reversed copy of itself appended to the end of it. + +# --hints-- + +`mirror("freeCodeCamp")` should return `"freeCodeCamppmaCedoCeerf"`. + +```js +assert.equal(mirror("freeCodeCamp"), "freeCodeCamppmaCedoCeerf"); +``` + +`mirror("RaceCar")` should return `"RaceCarraCecaR"`. + +```js +assert.equal(mirror("RaceCar"), "RaceCarraCecaR"); +``` + +`mirror("helloworld")` should return `"helloworlddlrowolleh"`. + +```js +assert.equal(mirror("helloworld"), "helloworlddlrowolleh"); +``` + +`mirror("The quick brown fox...")` should return `"The quick brown fox......xof nworb kciuq ehT"`. + +```js +assert.equal(mirror("The quick brown fox..."), "The quick brown fox......xof nworb kciuq ehT"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function mirror(str) { + + return str; +} +``` + +# --solutions-- + +```js +function mirror(str) { + const reversed = str.split("").reverse().join(""); + return str + reversed; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69738771fb5a7b8b24cca2a4.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69738771fb5a7b8b24cca2a4.md new file mode 100644 index 0000000000000000000000000000000000000000..1b4dd0baf91c934e780c7a0f63c88fe56e4d2a53 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69738771fb5a7b8b24cca2a4.md @@ -0,0 +1,56 @@ +--- +id: 69738771fb5a7b8b24cca2a4 +title: "Challenge 178: Truncate the Text" +challengeType: 28 +dashedName: challenge-178 +--- + +# --description-- + +Given a string, return it as-is if it's 20 characters or shorter. If it's longer than 20 characters, truncate it to the first 17 characters and append `"..."` to the end of it (so it's 20 characters total) and return the result. + +# --hints-- + +`truncateText("Hello, world!")` should return `"Hello, world!"`. + +```js +assert.equal(truncateText("Hello, world!"), "Hello, world!"); +``` + +`truncateText("This string should get truncated.")` should return `"This string shoul..."`. + +```js +assert.equal(truncateText("This string should get truncated."), "This string shoul..."); +``` + +`truncateText("Exactly twenty chars")` should return `"Exactly twenty chars"`. + +```js +assert.equal(truncateText("Exactly twenty chars"), "Exactly twenty chars"); +``` + +`truncateText(".....................")` should return `"...................."`. + +```js +assert.equal(truncateText("....................."), "...................."); +``` + +# --seed-- + +## --seed-contents-- + +```js +function truncateText(text) { + + return text; +} +``` + +# --solutions-- + +```js +function truncateText(text) { + if (text.length <= 20) return text; + return text.slice(0, 17) + "..."; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69738771fb5a7b8b24cca2a5.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69738771fb5a7b8b24cca2a5.md new file mode 100644 index 0000000000000000000000000000000000000000..dcdfdffb99a91e3e2cf5b70265d2466c7527c0d0 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69738771fb5a7b8b24cca2a5.md @@ -0,0 +1,75 @@ +--- +id: 69738771fb5a7b8b24cca2a5 +title: "Challenge 179: Pocket Change" +challengeType: 28 +dashedName: challenge-179 +--- + +# --description-- + +Given an array of integers representing the coins in your pocket, with each integer being the value of a coin in cents, return the total amount in the format `"$D.CC"`. + +- 100 cents equals 1 dollar. +- In the return value, include a leading zero for amounts less than one dollar and always exactly two digits for the cents. + +# --hints-- + +`countChange([25, 10, 5, 1])` should return `"$0.41"`. + +```js +assert.equal(countChange([25, 10, 5, 1]), "$0.41"); +``` + +`countChange([25, 10, 5, 1, 25, 10, 25, 1, 1, 10, 5, 25])` should return `"$1.43"`. + +```js +assert.equal(countChange([25, 10, 5, 1, 25, 10, 25, 1, 1, 10, 5, 25]), "$1.43"); +``` + +`countChange([100, 25, 100, 1000, 5, 500, 2000, 25])` should return `"$37.55"`. + +```js +assert.equal(countChange([100, 25, 100, 1000, 5, 500, 2000, 25]), "$37.55"); +``` + +`countChange([10, 5, 1, 10, 1, 25, 1, 1, 5, 1, 10])` should return `"$0.70"`. + +```js +assert.equal(countChange([10, 5, 1, 10, 1, 25, 1, 1, 5, 1, 10]), "$0.70"); +``` + +`countChange([1])` should return `"$0.01"`. + +```js +assert.equal(countChange([1]), "$0.01"); +``` + +`countChange([25, 25, 25, 25])` should return `"$1.00"`. + +```js +assert.equal(countChange([25, 25, 25, 25]), "$1.00"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function countChange(change) { + + return change; +} +``` + +# --solutions-- + +```js +function countChange(change) { + const totalCents = change.reduce((sum, coin) => sum + coin, 0); + + const dollars = Math.floor(totalCents / 100); + const cents = totalCents % 100; + + return `$${dollars}.${cents.toString().padStart(2, "0")}`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b6935d.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b6935d.md new file mode 100644 index 0000000000000000000000000000000000000000..bdcaba36161f7b958e1bf6e410e05715a26bc50c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b6935d.md @@ -0,0 +1,677 @@ +--- +id: 697a49e6ff50d756c9b6935d +title: "Challenge 180: Winter Games Day 1: Opening Day" +challengeType: 28 +dashedName: challenge-180 +--- + +# --description-- + +The next 17 days will bring you coding challenges inspired by the Winter Games. + +For the first one, you are given a two-letter country code and need to return the flag emoji for that country. + +Use this list: + +| Country | Code | Flag | +| - | -: | :--: | +| Albania | `"AL"` | `"🇦🇱"` | +| Andorra | `"AD"` | `"🇦🇩"` | +| Argentina | `"AR"` | `"🇦🇷"` | +| Armenia | `"AM"` | `"🇦🇲"` | +| Australia | `"AU"` | `"🇦🇺"` | +| Austria | `"AT"` | `"🇦🇹"` | +| Azerbaijan | `"AZ"` | `"🇦🇿"` | +| Belgium | `"BE"` | `"🇧🇪"` | +| Benin | `"BJ"` | `"🇧🇯"` | +| Bolivia | `"BO"` | `"🇧🇴"` | +| Bosnia and Herzegovina | `"BA"` | `"🇧🇦"` | +| Brazil | `"BR"` | `"🇧🇷"` | +| Bulgaria | `"BG"` | `"🇧🇬"` | +| Canada | `"CA"` | `"🇨🇦"` | +| Chile | `"CL"` | `"🇨🇱"` | +| China | `"CN"` | `"🇨🇳"` | +| Colombia | `"CO"` | `"🇨🇴"` | +| Croatia | `"HR"` | `"🇭🇷"` | +| Cyprus | `"CY"` | `"🇨🇾"` | +| Czech Republic | `"CZ"` | `"🇨🇿"` | +| Denmark | `"DK"` | `"🇩🇰"` | +| Ecuador | `"EC"` | `"🇪🇨"` | +| Eritrea | `"ER"` | `"🇪🇷"` | +| Estonia | `"EE"` | `"🇪🇪"` | +| Finland | `"FI"` | `"🇫🇮"` | +| France | `"FR"` | `"🇫🇷"` | +| Georgia | `"GE"` | `"🇬🇪"` | +| Germany | `"DE"` | `"🇩🇪"` | +| Great Britain | `"GB"` | `"🇬🇧"` | +| Greece | `"GR"` | `"🇬🇷"` | +| Guinea-Bissau | `"GW"` | `"🇬🇼"` | +| Haiti | `"HT"` | `"🇭🇹"` | +| Hong Kong | `"HK"` | `"🇭🇰"` | +| Hungary | `"HU"` | `"🇭🇺"` | +| Iceland | `"IS"` | `"🇮🇸"` | +| India | `"IN"` | `"🇮🇳"` | +| Iran | `"IR"` | `"🇮🇷"` | +| Ireland | `"IE"` | `"🇮🇪"` | +| Israel | `"IL"` | `"🇮🇱"` | +| Italy | `"IT"` | `"🇮🇹"` | +| Jamaica | `"JM"` | `"🇯🇲"` | +| Japan | `"JP"` | `"🇯🇵"` | +| Kazakhstan | `"KZ"` | `"🇰🇿"` | +| Kenya | `"KE"` | `"🇰🇪"` | +| Kosovo | `"XK"` | `"🇽🇰"` | +| Kyrgyzstan | `"KG"` | `"🇰🇬"` | +| Latvia | `"LV"` | `"🇱🇻"` | +| Lebanon | `"LB"` | `"🇱🇧"` | +| Liechtenstein | `"LI"` | `"🇱🇮"` | +| Lithuania | `"LT"` | `"🇱🇹"` | +| Luxembourg | `"LU"` | `"🇱🇺"` | +| Madagascar | `"MG"` | `"🇲🇬"` | +| Malaysia | `"MY"` | `"🇲🇾"` | +| Malta | `"MT"` | `"🇲🇹"` | +| Mexico | `"MX"` | `"🇲🇽"` | +| Moldova | `"MD"` | `"🇲🇩"` | +| Monaco | `"MC"` | `"🇲🇨"` | +| Mongolia | `"MN"` | `"🇲🇳"` | +| Montenegro | `"ME"` | `"🇲🇪"` | +| Morocco | `"MA"` | `"🇲🇦"` | +| Netherlands | `"NL"` | `"🇳🇱"` | +| New Zealand | `"NZ"` | `"🇳🇿"` | +| Nigeria | `"NG"` | `"🇳🇬"` | +| North Macedonia | `"MK"` | `"🇲🇰"` | +| Norway | `"NO"` | `"🇳🇴"` | +| Pakistan | `"PK"` | `"🇵🇰"` | +| Philippines | `"PH"` | `"🇵🇭"` | +| Poland | `"PL"` | `"🇵🇱"` | +| Portugal | `"PT"` | `"🇵🇹"` | +| Puerto Rico | `"PR"` | `"🇵🇷"` | +| Romania | `"RO"` | `"🇷🇴"` | +| San Marino | `"SM"` | `"🇸🇲"` | +| Saudi Arabia | `"SA"` | `"🇸🇦"` | +| Serbia | `"RS"` | `"🇷🇸"` | +| Singapore | `"SG"` | `"🇸🇬"` | +| Slovakia | `"SK"` | `"🇸🇰"` | +| Slovenia | `"SI"` | `"🇸🇮"` | +| South Africa | `"ZA"` | `"🇿🇦"` | +| South Korea | `"KR"` | `"🇰🇷"` | +| Spain | `"ES"` | `"🇪🇸"` | +| Sweden | `"SE"` | `"🇸🇪"` | +| Switzerland | `"CH"` | `"🇨🇭"` | +| Thailand | `"TH"` | `"🇹🇭"` | +| Trinidad & Tobago | `"TT"` | `"🇹🇹"` | +| Turkey | `"TR"` | `"🇹🇷"` | +| Ukraine | `"UA"` | `"🇺🇦"` | +| United Arab Emirates | `"AE"` | `"🇦🇪"` | +| United States | `"US"` | `"🇺🇸"` | +| Uruguay | `"UY"` | `"🇺🇾"` | +| Uzbekistan | `"UZ"` | `"🇺🇿"` | +| Venezuela | `"VE"` | `"🇻🇪"` | + +# --hints-- + +`getFlag("AL")` should return `"🇦🇱"`. + +```js +assert.equal(getFlag("AL"), "🇦🇱"); +``` + +`getFlag("AD")` should return `"🇦🇩"`. + +```js +assert.equal(getFlag("AD"), "🇦🇩"); +``` + +`getFlag("AR")` should return `"🇦🇷"`. + +```js +assert.equal(getFlag("AR"), "🇦🇷") +``` + +`getFlag("AM")` should return `"🇦🇲"`. + +```js +assert.equal(getFlag("AM"), "🇦🇲") +``` + +`getFlag("AU")` should return `"🇦🇺"`. + +```js +assert.equal(getFlag("AU"), "🇦🇺") +``` + +`getFlag("AT")` should return `"🇦🇹"`. + +```js +assert.equal(getFlag("AT"), "🇦🇹") +``` + +`getFlag("AZ")` should return `"🇦🇿"`. + +```js +assert.equal(getFlag("AZ"), "🇦🇿") +``` + +`getFlag("BE")` should return `"🇧🇪"`. + +```js +assert.equal(getFlag("BE"), "🇧🇪") +``` + +`getFlag("BJ")` should return `"🇧🇯"`. + +```js +assert.equal(getFlag("BJ"), "🇧🇯") +``` + +`getFlag("BO")` should return `"🇧🇴"`. + +```js +assert.equal(getFlag("BO"), "🇧🇴") +``` + +`getFlag("BA")` should return `"🇧🇦"`. + +```js +assert.equal(getFlag("BA"), "🇧🇦") +``` + +`getFlag("BR")` should return `"🇧🇷"`. + +```js +assert.equal(getFlag("BR"), "🇧🇷") +``` + +`getFlag("BG")` should return `"🇧🇬"`. + +```js +assert.equal(getFlag("BG"), "🇧🇬") +``` + +`getFlag("CA")` should return `"🇨🇦"`. + +```js +assert.equal(getFlag("CA"), "🇨🇦") +``` + +`getFlag("CL")` should return `"🇨🇱"`. + +```js +assert.equal(getFlag("CL"), "🇨🇱") +``` + +`getFlag("CN")` should return `"🇨🇳"`. + +```js +assert.equal(getFlag("CN"), "🇨🇳") +``` + +`getFlag("CO")` should return `"🇨🇴"`. + +```js +assert.equal(getFlag("CO"), "🇨🇴") +``` + +`getFlag("HR")` should return `"🇭🇷"`. + +```js +assert.equal(getFlag("HR"), "🇭🇷") +``` + +`getFlag("CY")` should return `"🇨🇾"`. + +```js +assert.equal(getFlag("CY"), "🇨🇾") +``` + +`getFlag("CZ")` should return `"🇨🇿"`. + +```js +assert.equal(getFlag("CZ"), "🇨🇿") +``` + +`getFlag("DK")` should return `"🇩🇰"`. + +```js +assert.equal(getFlag("DK"), "🇩🇰") +``` + +`getFlag("EC")` should return `"🇪🇨"`. + +```js +assert.equal(getFlag("EC"), "🇪🇨") +``` + +`getFlag("ER")` should return `"🇪🇷"`. + +```js +assert.equal(getFlag("ER"), "🇪🇷") +``` + +`getFlag("EE")` should return `"🇪🇪"`. + +```js +assert.equal(getFlag("EE"), "🇪🇪") +``` + +`getFlag("FI")` should return `"🇫🇮"`. + +```js +assert.equal(getFlag("FI"), "🇫🇮") +``` + +`getFlag("FR")` should return `"🇫🇷"`. + +```js +assert.equal(getFlag("FR"), "🇫🇷") +``` + +`getFlag("GE")` should return `"🇬🇪"`. + +```js +assert.equal(getFlag("GE"), "🇬🇪") +``` + +`getFlag("DE")` should return `"🇩🇪"`. + +```js +assert.equal(getFlag("DE"), "🇩🇪") +``` + +`getFlag("GB")` should return `"🇬🇧"`. + +```js +assert.equal(getFlag("GB"), "🇬🇧") +``` + +`getFlag("GR")` should return `"🇬🇷"`. + +```js +assert.equal(getFlag("GR"), "🇬🇷") +``` + +`getFlag("GW")` should return `"🇬🇼"`. + +```js +assert.equal(getFlag("GW"), "🇬🇼") +``` + +`getFlag("HT")` should return `"🇭🇹"`. + +```js +assert.equal(getFlag("HT"), "🇭🇹") +``` + +`getFlag("HK")` should return `"🇭🇰"`. + +```js +assert.equal(getFlag("HK"), "🇭🇰") +``` + +`getFlag("HU")` should return `"🇭🇺"`. + +```js +assert.equal(getFlag("HU"), "🇭🇺") +``` + +`getFlag("IS")` should return `"🇮🇸"`. + +```js +assert.equal(getFlag("IS"), "🇮🇸") +``` + +`getFlag("IN")` should return `"🇮🇳"`. + +```js +assert.equal(getFlag("IN"), "🇮🇳") +``` + +`getFlag("IR")` should return `"🇮🇷"`. + +```js +assert.equal(getFlag("IR"), "🇮🇷") +``` + +`getFlag("IE")` should return `"🇮🇪"`. + +```js +assert.equal(getFlag("IE"), "🇮🇪") +``` + +`getFlag("IL")` should return `"🇮🇱"`. + +```js +assert.equal(getFlag("IL"), "🇮🇱") +``` + +`getFlag("IT")` should return `"🇮🇹"`. + +```js +assert.equal(getFlag("IT"), "🇮🇹") +``` + +`getFlag("JM")` should return `"🇯🇲"`. + +```js +assert.equal(getFlag("JM"), "🇯🇲") +``` + +`getFlag("JP")` should return `"🇯🇵"`. + +```js +assert.equal(getFlag("JP"), "🇯🇵") +``` + +`getFlag("KZ")` should return `"🇰🇿"`. + +```js +assert.equal(getFlag("KZ"), "🇰🇿") +``` + +`getFlag("KE")` should return `"🇰🇪"`. + +```js +assert.equal(getFlag("KE"), "🇰🇪") +``` + +`getFlag("XK")` should return `"🇽🇰"`. + +```js +assert.equal(getFlag("XK"), "🇽🇰") +``` + +`getFlag("KG")` should return `"🇰🇬"`. + +```js +assert.equal(getFlag("KG"), "🇰🇬") +``` + +`getFlag("LV")` should return `"🇱🇻"`. + +```js +assert.equal(getFlag("LV"), "🇱🇻") +``` + +`getFlag("LB")` should return `"🇱🇧"`. + +```js +assert.equal(getFlag("LB"), "🇱🇧") +``` + +`getFlag("LI")` should return `"🇱🇮"`. + +```js +assert.equal(getFlag("LI"), "🇱🇮") +``` + +`getFlag("LT")` should return `"🇱🇹"`. + +```js +assert.equal(getFlag("LT"), "🇱🇹") +``` + +`getFlag("LU")` should return `"🇱🇺"`. + +```js +assert.equal(getFlag("LU"), "🇱🇺") +``` + +`getFlag("MG")` should return `"🇲🇬"`. + +```js +assert.equal(getFlag("MG"), "🇲🇬") +``` + +`getFlag("MY")` should return `"🇲🇾"`. + +```js +assert.equal(getFlag("MY"), "🇲🇾") +``` + +`getFlag("MT")` should return `"🇲🇹"`. + +```js +assert.equal(getFlag("MT"), "🇲🇹") +``` + +`getFlag("MX")` should return `"🇲🇽"`. + +```js +assert.equal(getFlag("MX"), "🇲🇽") +``` + +`getFlag("MD")` should return `"🇲🇩"`. + +```js +assert.equal(getFlag("MD"), "🇲🇩") +``` + +`getFlag("MC")` should return `"🇲🇨"`. + +```js +assert.equal(getFlag("MC"), "🇲🇨") +``` + +`getFlag("MN")` should return `"🇲🇳"`. + +```js +assert.equal(getFlag("MN"), "🇲🇳") +``` + +`getFlag("ME")` should return `"🇲🇪"`. + +```js +assert.equal(getFlag("ME"), "🇲🇪") +``` + +`getFlag("MA")` should return `"🇲🇦"`. + +```js +assert.equal(getFlag("MA"), "🇲🇦") +``` + +`getFlag("NL")` should return `"🇳🇱"`. + +```js +assert.equal(getFlag("NL"), "🇳🇱") +``` + +`getFlag("NZ")` should return `"🇳🇿"`. + +```js +assert.equal(getFlag("NZ"), "🇳🇿") +``` + +`getFlag("NG")` should return `"🇳🇬"`. + +```js +assert.equal(getFlag("NG"), "🇳🇬") +``` + +`getFlag("MK")` should return `"🇲🇰"`. + +```js +assert.equal(getFlag("MK"), "🇲🇰") +``` + +`getFlag("NO")` should return `"🇳🇴"`. + +```js +assert.equal(getFlag("NO"), "🇳🇴") +``` + +`getFlag("PK")` should return `"🇵🇰"`. + +```js +assert.equal(getFlag("PK"), "🇵🇰") +``` + +`getFlag("PH")` should return `"🇵🇭"`. + +```js +assert.equal(getFlag("PH"), "🇵🇭") +``` + +`getFlag("PL")` should return `"🇵🇱"`. + +```js +assert.equal(getFlag("PL"), "🇵🇱") +``` + +`getFlag("PT")` should return `"🇵🇹"`. + +```js +assert.equal(getFlag("PT"), "🇵🇹") +``` + +`getFlag("PR")` should return `"🇵🇷"`. + +```js +assert.equal(getFlag("PR"), "🇵🇷") +``` + +`getFlag("RO")` should return `"🇷🇴"`. + +```js +assert.equal(getFlag("RO"), "🇷🇴") +``` + +`getFlag("SM")` should return `"🇸🇲"`. + +```js +assert.equal(getFlag("SM"), "🇸🇲") +``` + +`getFlag("SA")` should return `"🇸🇦"`. + +```js +assert.equal(getFlag("SA"), "🇸🇦") +``` + +`getFlag("RS")` should return `"🇷🇸"`. + +```js +assert.equal(getFlag("RS"), "🇷🇸") +``` + +`getFlag("SG")` should return `"🇸🇬"`. + +```js +assert.equal(getFlag("SG"), "🇸🇬") +``` + +`getFlag("SK")` should return `"🇸🇰"`. + +```js +assert.equal(getFlag("SK"), "🇸🇰") +``` + +`getFlag("SI")` should return `"🇸🇮"`. + +```js +assert.equal(getFlag("SI"), "🇸🇮") +``` + +`getFlag("ZA")` should return `"🇿🇦"`. + +```js +assert.equal(getFlag("ZA"), "🇿🇦") +``` + +`getFlag("KR")` should return `"🇰🇷"`. + +```js +assert.equal(getFlag("KR"), "🇰🇷") +``` + +`getFlag("ES")` should return `"🇪🇸"`. + +```js +assert.equal(getFlag("ES"), "🇪🇸") +``` + +`getFlag("SE")` should return `"🇸🇪"`. + +```js +assert.equal(getFlag("SE"), "🇸🇪") +``` + +`getFlag("CH")` should return `"🇨🇭"`. + +```js +assert.equal(getFlag("CH"), "🇨🇭") +``` + +`getFlag("TH")` should return `"🇹🇭"`. + +```js +assert.equal(getFlag("TH"), "🇹🇭") +``` + +`getFlag("TT")` should return `"🇹🇹"`. + +```js +assert.equal(getFlag("TT"), "🇹🇹") +``` + +`getFlag("TR")` should return `"🇹🇷"`. + +```js +assert.equal(getFlag("TR"), "🇹🇷") +``` + +`getFlag("UA")` should return `"🇺🇦"`. + +```js +assert.equal(getFlag("UA"), "🇺🇦") +``` + +`getFlag("AE")` should return `"🇦🇪"`. + +```js +assert.equal(getFlag("AE"), "🇦🇪") +``` + +`getFlag("US")` should return `"🇺🇸"`. + +```js +assert.equal(getFlag("US"), "🇺🇸") +``` + +`getFlag("UY")` should return `"🇺🇾"`. + +```js +assert.equal(getFlag("UY"), "🇺🇾") +``` + +`getFlag("UZ")` should return `"🇺🇿"`. + +```js +assert.equal(getFlag("UZ"), "🇺🇿") +``` + +`getFlag("VE")` should return `"🇻🇪"`. + +```js +assert.equal(getFlag("VE"), "🇻🇪") +``` + +# --seed-- + +## --seed-contents-- + +```js +function getFlag(code) { + + return code; +} +``` + +# --solutions-- + +```js +function getFlag(code) { + return [...code] + .map(char => String.fromCodePoint(127397 + char.charCodeAt())) + .join(""); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b6935e.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b6935e.md new file mode 100644 index 0000000000000000000000000000000000000000..40a47cf20a95f88af33774db88d6229e193d9f24 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b6935e.md @@ -0,0 +1,84 @@ +--- +id: 697a49e6ff50d756c9b6935e +title: "Challenge 181: Winter Games Day 2: Snowboarding" +challengeType: 28 +dashedName: challenge-181 +--- + +# --description-- + +Given a snowboarder's starting stance and a rotation in degrees, determine their landing stance. + +- A snowboarder's stance is either `"Regular"` or `"Goofy"`. +- Trick rotations are multiples of 90 degrees. Positive indicates clockwise rotation, and negative indicate counterclockwise rotation. +- The landing stance flips every 180 degrees of rotation. + +For example, given `"Regular"` and `90`, return `"Regular"`. Given `"Regular"` and `180` degrees, return `"Goofy"`. + +# --hints-- + +`getLandingStance("Regular", 90)` should return `"Regular"`. + +```js +assert.equal(getLandingStance("Regular", 90), "Regular"); +``` + +`getLandingStance("Regular", 180)` should return `"Goofy"`. + +```js +assert.equal(getLandingStance("Regular", 180), "Goofy"); +``` + +`getLandingStance("Goofy", -270)` should return `"Regular"`. + +```js +assert.equal(getLandingStance("Goofy", -270), "Regular"); +``` + +`getLandingStance("Regular", 2340)` should return `"Goofy"`. + +```js +assert.equal(getLandingStance("Regular", 2340), "Goofy"); +``` + +`getLandingStance("Goofy", 2160)` should return `"Goofy"`. + +```js +assert.equal(getLandingStance("Goofy", 2160), "Goofy"); +``` + +`getLandingStance("Goofy", -540)` should return `"Regular"`. + +```js +assert.equal(getLandingStance("Goofy", -540), "Regular"); +``` + +`getLandingStance("Goofy", 90)` should return `"Goofy"`. + +```js +assert.equal(getLandingStance("Goofy", 90), "Goofy"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getLandingStance(startStance, rotation) { + + return startStance; +} +``` + +# --solutions-- + +```js +function getLandingStance(startStance, rotation) { + const flips = Math.floor(Math.abs(rotation) / 180); + if (flips % 2 === 0) { + return startStance; + } else { + return startStance === "Regular" ? "Goofy" : "Regular"; + } +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b6935f.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b6935f.md new file mode 100644 index 0000000000000000000000000000000000000000..e09cffc58a4f0c58727bac285ddf45651b08ec3b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b6935f.md @@ -0,0 +1,71 @@ +--- +id: 697a49e6ff50d756c9b6935f +title: "Challenge 182: Winter Games Day 3: Biathlon" +challengeType: 28 +dashedName: challenge-182 +--- + +# --description-- + +Given an array of integers, where each value represents the number of targets hit in a single round of a biathlon, return the total penalty distance the athlete must ski. + +- Each round consists of 5 targets. +- Each missed target results in a 150 meter penalty loop. + +# --hints-- + +`calculatePenaltyDistance([4, 4])` should return `300`. + +```js +assert.equal(calculatePenaltyDistance([4, 4]), 300); +``` + +`calculatePenaltyDistance([5, 5])` should return `0`. + +```js +assert.equal(calculatePenaltyDistance([5, 5]), 0); +``` + +`calculatePenaltyDistance([4, 5, 3, 5])` should return `450`. + +```js +assert.equal(calculatePenaltyDistance([4, 5, 3, 5]), 450); +``` + +`calculatePenaltyDistance([5, 4, 5, 5])` should return `150`. + +```js +assert.equal(calculatePenaltyDistance([5, 4, 5, 5]), 150); +``` + +`calculatePenaltyDistance([4, 3, 0, 3])` should return `1500`. + +```js +assert.equal(calculatePenaltyDistance([4, 3, 0, 3]), 1500); +``` + +# --seed-- + +## --seed-contents-- + +```js +function calculatePenaltyDistance(rounds) { + + return rounds; +} +``` + +# --solutions-- + +```js +function calculatePenaltyDistance(rounds) { + let totalPenalty = 0; + + for (const hits of rounds) { + const misses = 5 - hits; + totalPenalty += misses * 150; + } + + return totalPenalty; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b69360.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b69360.md new file mode 100644 index 0000000000000000000000000000000000000000..65ee695ca79d9f3f122c0d33564750aea4e32891 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b69360.md @@ -0,0 +1,96 @@ +--- +id: 697a49e6ff50d756c9b69360 +title: "Challenge 183: Winter Games Day 4: Ski Jumping" +challengeType: 28 +dashedName: challenge-183 +--- + +# --description-- + +Given distance points, style points, a wind compensation value, and K-point bonus value, calculate your score for the ski jump and determine if you won a medal or not. + +- Your score is calculated by summing the above four values. + +The current total scores of the other jumpers are: + +```sh +165.5 +172.0 +158.0 +180.0 +169.5 +175.0 +162.0 +170.0 +``` + +- If your score is the best, return `"Gold"` +- If it's second best, return `"Silver"` +- If it's third best, return `"Bronze"` +- Otherwise, return `"No Medal"` + +# --hints-- + +`skiJumpMedal(125.0, 58.0, 0.0, 6.0)` should return `"Gold"`. + +```js +assert.equal(skiJumpMedal(125.0, 58.0, 0.0, 6.0), "Gold"); +``` + +`skiJumpMedal(119.0, 50.0, 1.0, 4.0)` should return `"Bronze"`. + +```js +assert.equal(skiJumpMedal(119.0, 50.0, 1.0, 4.0), "Bronze"); +``` + +`skiJumpMedal(122.0, 52.0, -1.0, 4.0)` should return `"Silver"`. + +```js +assert.equal(skiJumpMedal(122.0, 52.0, -1.0, 4.0), "Silver"); +``` + +`skiJumpMedal(118.0, 50.5, -1.5, 4.0)` should return `"No Medal"`. + +```js +assert.equal(skiJumpMedal(118.0, 50.5, -1.5, 4.0), "No Medal"); +``` + +`skiJumpMedal(124.0, 50.5, 2.0, 5.0)` should return `"Gold"`. + +```js +assert.equal(skiJumpMedal(124.0, 50.5, 2.0, 5.0), "Gold"); +``` + +`skiJumpMedal(119.0, 49.5, 0.0, 3.0)` should return `"No Medal"`. + +```js +assert.equal(skiJumpMedal(119.0, 49.5, 0.0, 3.0), "No Medal"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function skiJumpMedal(distancePoints, stylePoints, windComp, kPointBonus) { + + return distancePoints; +} +``` + +# --solutions-- + +```js +function skiJumpMedal(distancePoints, stylePoints, windComp, kPointBonus) { + const myScore = distancePoints + stylePoints + windComp + kPointBonus; + const otherScores = [165.5, 172.0, 158.0, 180.0, 169.5, 175.0, 162.0, 170.0]; + const allScores = [...otherScores, myScore]; + allScores.sort((a, b) => b - a); + const rank = allScores.indexOf(myScore) + 1; + + if (rank === 1) return "Gold"; + if (rank === 2) return "Silver"; + if (rank === 3) return "Bronze"; + return "No Medal"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b69361.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b69361.md new file mode 100644 index 0000000000000000000000000000000000000000..c2d147cfd6f55e67111f53b0e481d6106c3c7ab2 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b69361.md @@ -0,0 +1,86 @@ +--- +id: 697a49e6ff50d756c9b69361 +title: "Challenge 184: Winter Games Day 5: Cross-Country Skiing" +challengeType: 28 +dashedName: challenge-184 +--- + +# --description-- + +Given an array of finish times for a cross-country ski race, convert them into times behind the winner. + +- Given times are strings in `"H:MM:SS"` format. +- Given times will be in order from fastest to slowest. +- The winners time (fastest time) should correspond to `"0"`. +- Each other time should show the time behind the winner, in the format `"+M:SS"`. + +For example, given `["1:25:32", "1:26:10", "1:27:05"]`, return `["0", "+0:38", "+1:33"]`. + +# --hints-- + +`getRelativeResults(["1:25:32", "1:26:10", "1:27:05"])` should return `["0", "+0:38", "+1:33"]`. + +```js +assert.deepEqual(getRelativeResults(["1:25:32", "1:26:10", "1:27:05"]), ["0", "+0:38", "+1:33"]); +``` + +`getRelativeResults(["1:00:01", "1:00:05", "1:00:10"])` should return `["0", "+0:04", "+0:09"]`. + +```js +assert.deepEqual(getRelativeResults(["1:00:01", "1:00:05", "1:00:10"]), ["0", "+0:04", "+0:09"]); +``` + +`getRelativeResults(["1:10:06", "1:10:23", "1:10:48", "1:12:11"])` should return `["0", "+0:17", "+0:42", "+2:05"]`. + +```js +assert.deepEqual(getRelativeResults(["1:10:06", "1:10:23", "1:10:48", "1:12:11"]), ["0", "+0:17", "+0:42", "+2:05"]); +``` + +`getRelativeResults(["0:49:13", "0:49:15", "0:50:14", "0:51:30", "0:51:58", "0:52:16", "0:53:12", "0:53:31", "0:56:19", "1:02:20"])` should return `["0", "+0:02", "+1:01", "+2:17", "+2:45", "+3:03", "+3:59", "+4:18", "+7:06", "+13:07"]`. + +```js +assert.deepEqual(getRelativeResults(["0:49:13", "0:49:15", "0:50:14", "0:51:30", "0:51:58", "0:52:16", "0:53:12", "0:53:31", "0:56:19", "1:02:20"]), ["0", "+0:02", "+1:01", "+2:17", "+2:45", "+3:03", "+3:59", "+4:18", "+7:06", "+13:07"]); +``` + +`getRelativeResults(["2:01:15", "2:10:45", "2:10:53", "2:11:04", "2:11:55", "2:13:27", "2:14:30", "2:15:10"])` should return `["0", "+9:30", "+9:38", "+9:49", "+10:40", "+12:12", "+13:15", "+13:55"]`. + +```js +assert.deepEqual(getRelativeResults(["2:01:15", "2:10:45", "2:10:53", "2:11:04", "2:11:55", "2:13:27", "2:14:30", "2:15:10"]), ["0", "+9:30", "+9:38", "+9:49", "+10:40", "+12:12", "+13:15", "+13:55"]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getRelativeResults(results) { + + return results; +} +``` + +# --solutions-- + +```js +function getRelativeResults(results) { + const timeToSeconds = (timeStr) => { + const [hours, minutes, seconds] = timeStr.split(':').map(Number); + return hours * 3600 + minutes * 60 + seconds; + }; + + const secondsToTimeFormat = (secs) => { + const mins = Math.floor(secs / 60); + const secsRemainder = secs % 60; + return `+${mins}:${String(secsRemainder).padStart(2, '0')}`; + }; + + const winnerSeconds = timeToSeconds(results[0]); + + return results.map((time, index) => { + if (index === 0) return '0'; + const currentSeconds = timeToSeconds(time); + const difference = currentSeconds - winnerSeconds; + return secondsToTimeFormat(difference); + }); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b69362.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b69362.md new file mode 100644 index 0000000000000000000000000000000000000000..76bcaccdf53bd9c6022d5b0875c324010cd2a998 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b69362.md @@ -0,0 +1,69 @@ +--- +id: 697a49e6ff50d756c9b69362 +title: "Challenge 185: Winter Games Day 6: Figure Skating" +challengeType: 28 +dashedName: challenge-185 +--- + +# --description-- + +Given an array of judge scores and optional penalties, calculate the final score for a figure skating routine. + +The first argument is an array of 10 judge scores, each a number from 0 to 10. Remove the highest and lowest judge scores and sum the remaining 8 scores to get the base score. + +Any additional arguments passed to the function are penalties. Subtract all penalties from the base score to get the final score. + +# --hints-- + +`computeScore([10, 8, 9, 6, 9, 8, 8, 9, 7, 7], 1)` should return `64`. + +```js +assert.equal(computeScore([10, 8, 9, 6, 9, 8, 8, 9, 7, 7], 1), 64); +``` + +`computeScore([10, 10, 10, 10, 10, 10, 10, 10, 10, 10])` should return `80`. + +```js +assert.equal(computeScore([10, 10, 10, 10, 10, 10, 10, 10, 10, 10]), 80); +``` + +`computeScore([10, 8, 9, 10, 9, 8, 8, 9, 10, 7], 1, 2, 1)` should return `67`. + +```js +assert.equal(computeScore([10, 8, 9, 10, 9, 8, 8, 9, 10, 7], 1, 2, 1), 67); +``` + +`computeScore([8.0, 8.5, 9.0, 8.5, 9.0, 8.0, 9.0, 8.5, 9.0, 8.5], 0.5, 1.0)` should return `67.5`. + +```js +assert.equal(computeScore([8.0, 8.5, 9.0, 8.5, 9.0, 8.0, 9.0, 8.5, 9.0, 8.5], 0.5, 1.0), 67.5); +``` + +`computeScore([6.0, 8.5, 7.0, 9.0, 7.5, 8.0, 6.5, 9.5, 7.0, 8.0], 1.5, 0.5, 0.5)` should return `59`. + +```js +assert.equal(computeScore([6.0, 8.5, 7.0, 9.0, 7.5, 8.0, 6.5, 9.5, 7.0, 8.0], 1.5, 0.5, 0.5), 59); +``` + +# --seed-- + +## --seed-contents-- + +```js +function computeScore(judgeScores, ...penalties) { + + return judgeScores; +} +``` + +# --solutions-- + +```js +function computeScore(judgeScores, ...penalties) { + const sortedScores = [...judgeScores].sort((a, b) => a - b); + const baseScore = sortedScores.slice(1, 9).reduce((sum, s) => sum + s, 0); + const totalPenalty = penalties.reduce((sum, p) => sum + p, 0); + + return baseScore - totalPenalty; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b69363.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b69363.md new file mode 100644 index 0000000000000000000000000000000000000000..60f3b6c7d2f167445a2dcdab112e1912d8d0be49 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b69363.md @@ -0,0 +1,74 @@ +--- +id: 697a49e6ff50d756c9b69363 +title: "Challenge 186: Winter Games Day 7: Speed Skating" +challengeType: 28 +dashedName: challenge-186 +--- + +# --description-- + +Given two arrays representing the lap times (in seconds) for two speed skaters, return the lap number where the difference in lap times is the largest. + +The first element of each array corresponds to lap 1, the second to lap 2, and so on. + +# --hints-- + +`largestDifference([26.11, 25.80, 25.92, 26.23, 26.07], [25.93, 25.74, 26.53, 26.11, 26.30])` should return `3`. + +```js +assert.equal(largestDifference([26.11, 25.80, 25.92, 26.23, 26.07], [25.93, 25.74, 26.53, 26.11, 26.30]), 3); +``` + +`largestDifference([27.04, 25.94, 26.22, 26.07, 26.18], [25.59, 25.80, 26.11, 26.01, 26.23])` should return `1`. + +```js +assert.equal(largestDifference([27.04, 25.94, 26.22, 26.07, 26.18], [25.59, 25.80, 26.11, 26.01, 26.23]), 1); +``` + +`largestDifference([25.82, 25.90, 26.05, 26.00, 26.48], [25.85, 25.92, 26.07, 25.98, 25.95])` should return `5`. + +```js +assert.equal(largestDifference([25.82, 25.90, 26.05, 26.00, 26.48], [25.85, 25.92, 26.07, 25.98, 25.95]), 5); +``` + +`largestDifference([25.88, 26.10, 25.95, 26.05, 26.00], [25.90, 26.55, 25.92, 26.03, 26.01])` should return `2`. + +```js +assert.equal(largestDifference([25.88, 26.10, 25.95, 26.05, 26.00], [25.90, 26.55, 25.92, 26.03, 26.01]), 2); +``` + +`largestDifference([25.92, 26.01, 26.05, 25.88, 26.12], [25.95, 26.00, 26.03, 26.45, 26.10])` should return `4`. + +```js +assert.equal(largestDifference([25.92, 26.01, 26.05, 25.88, 26.12], [25.95, 26.00, 26.03, 26.45, 26.10]), 4); +``` + +# --seed-- + +## --seed-contents-- + +```js +function largestDifference(skater1, skater2) { + + return skater1; +} +``` + +# --solutions-- + +```js +function largestDifference(skater1, skater2) { + let maxDiff = -1; + let lapNumber = 1; + + for (let i = 0; i < skater1.length; i++) { + const diff = Math.abs(skater1[i] - skater2[i]); + if (diff > maxDiff) { + maxDiff = diff; + lapNumber = i + 1; + } + } + + return lapNumber; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b69364.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b69364.md new file mode 100644 index 0000000000000000000000000000000000000000..5de0b9a0d08b970df9ce9533fe8f6d69236a1d9b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b69364.md @@ -0,0 +1,87 @@ +--- +id: 697a49e6ff50d756c9b69364 +title: "Challenge 187: Winter Games Day 8: Luge" +challengeType: 28 +dashedName: challenge-187 +--- + +# --description-- + +Given an array of five numbers, each representing the time (in seconds) it took a luger to complete a segment of a track, determine which segment had the fastest speed and what that speed was. + +The track is divided into the following segments: + +- Segment 1: 320 meters +- Segment 2: 280 meters +- Segment 3: 350 meters +- Segment 4: 300 meters +- Segment 5: 250 meters + +The first value in the given array corresponds to the time for segment 1, the second value to segment 2, and so on. + +To calculate the speed (in meters per second) for a segment, divide the distance by the time. + +Return `"The luger's fastest speed was X m/s on segment Y."`. Where `X` is the fastest speed, rounded to two decimal places, and `Y` is the segment number where the fastest speed occurred. + +# --hints-- + +`getFastestSpeed([9.523, 8.234, 10.012, 9.001, 7.128])` should return `"The luger's fastest speed was 35.07 m/s on segment 5."` + +```js +assert.equal(getFastestSpeed([9.523, 8.234, 10.012, 9.001, 7.128]), "The luger's fastest speed was 35.07 m/s on segment 5."); +``` + +`getFastestSpeed([9.381, 7.417, 9.912, 8.815, 7.284])` should return `"The luger's fastest speed was 37.75 m/s on segment 2."` + +```js +assert.equal(getFastestSpeed([9.381, 7.417, 9.912, 8.815, 7.284]), "The luger's fastest speed was 37.75 m/s on segment 2."); +``` + +`getFastestSpeed([8.890, 7.601, 9.093, 8.392, 6.912])` should return `"The luger's fastest speed was 38.49 m/s on segment 3."` + +```js +assert.equal(getFastestSpeed([8.890, 7.601, 9.093, 8.392, 6.912]), "The luger's fastest speed was 38.49 m/s on segment 3."); +``` + +`getFastestSpeed([8.490, 7.732, 10.103, 8.489, 6.840])` should return `"The luger's fastest speed was 37.69 m/s on segment 1."` + +```js +assert.equal(getFastestSpeed([8.490, 7.732, 10.103, 8.489, 6.840]), "The luger's fastest speed was 37.69 m/s on segment 1."); +``` + +`getFastestSpeed([8.204, 7.230, 9.673, 7.645, 6.508])` should return `"The luger's fastest speed was 39.24 m/s on segment 4."` + +```js +assert.equal(getFastestSpeed([8.204, 7.230, 9.673, 7.645, 6.508]), "The luger's fastest speed was 39.24 m/s on segment 4."); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getFastestSpeed(times) { + + return times; +} +``` + +# --solutions-- + +```js +function getFastestSpeed(times) { + const distances = [320, 280, 350, 300, 250]; + let fastestSpeed = 0; + let fastestSegment = 0; + + for (let i = 0; i < times.length; i++) { + const speed = distances[i] / times[i]; + if (speed > fastestSpeed) { + fastestSpeed = speed; + fastestSegment = i + 1; + } + } + + return `The luger's fastest speed was ${fastestSpeed.toFixed(2)} m/s on segment ${fastestSegment}.`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b69365.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b69365.md new file mode 100644 index 0000000000000000000000000000000000000000..36ccac2b3484550f3340c1e4cc7cd623b2a0129b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b69365.md @@ -0,0 +1,103 @@ +--- +id: 697a49e6ff50d756c9b69365 +title: "Challenge 188: Winter Games Day 9: Skeleton" +challengeType: 28 +dashedName: challenge-188 +--- + +# --description-- + +Given a string representing the curves on a skeleton track, determine the difficulty of the track. + +- The given string will only consist of the letters: + - `"L"` for a left turn + - `"R"` for a right turn + - `"S"` for a straight segment + +- Each direction change adds 15 points (an `"L"` followed by an `"R"` or vice versa). +- All other curves add 5 points each (all other `"L"` or `"R"` characters). +- Straight segments add 0 points. + +The difficulty of the track is based on the total score. Return: + +- `"Easy"` if the total is 0 - 100 +- `"Medium"` if the total is 101-200 +- `"Hard"` if the total is over 200 + +# --hints-- + +`getDifficulty("SLSLLSRRLSRLRL")` should return `"Easy"`. + +```js +assert.equal(getDifficulty("SLSLLSRRLSRLRL"), "Easy"); +``` + +`getDifficulty("LLRSLRLRSLLRLRSLRRLRSRLLS")` should return `"Hard"`. + +```js +assert.equal(getDifficulty("LLRSLRLRSLLRLRSLRRLRSRLLS"), "Hard"); +``` + +`getDifficulty("SRRRRLSLLRLRSSRLSRL")` should return `"Medium"`. + +```js +assert.equal(getDifficulty("SRRRRLSLLRLRSSRLSRL"), "Medium"); +``` + +`getDifficulty("LSRLRLSRLRLSLRSLRLLRLSRLRLRSL")` should return `"Hard"`. + +```js +assert.equal(getDifficulty("LSRLRLSRLRLSLRSLRLLRLSRLRLRSL"), "Hard"); +``` + +`getDifficulty("SLLSSLRLSLSLRSLSSLRL")` should return `"Medium"`. + +```js +assert.equal(getDifficulty("SLLSSLRLSLSLRSLSSLRL"), "Medium"); +``` + +`getDifficulty("SRSLSRSLSRRSLSRSRSLSRLSRSR")` should return `"Easy"`. + +```js +assert.equal(getDifficulty("SRSLSRSLSRRSLSRSRSLSRLSRSR"), "Easy"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getDifficulty(track) { + + return track; +} +``` + +# --solutions-- + +```js +function getDifficulty(track) { + let score = 0; + + for (let i = 0; i < track.length; i++) { + const current = track[i]; + const previous = i > 0 ? track[i - 1] : null; + + if (current === 'S') { + score += 0; + } else if (current === 'L' || current === 'R') { + if (previous && previous !== 'S' && previous !== current) { + score += 15; + } else if (previous !== 'S') { + score += 5; + } else { + score += 5; + } + } + } + + if (score <= 100) return 'Easy'; + if (score <= 200) return 'Medium'; + return 'Hard'; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b69366.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b69366.md new file mode 100644 index 0000000000000000000000000000000000000000..ddedf501038f8a646f36c9dbeb84055691925905 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e6ff50d756c9b69366.md @@ -0,0 +1,97 @@ +--- +id: 697a49e6ff50d756c9b69366 +title: "Challenge 189: Winter Games Day 10: Alpine Skiing" +challengeType: 28 +dashedName: challenge-189 +--- + +# --description-- + +Given a ski hill's vertical drop, horizontal distance, and type, determine the difficulty rating of the hill. + +To determine the rating: + +- Calculate the steepness of the hill by taking the drop divided by the distance. +- Then, calculate the adjusted steepness based on the hill type: + - `"Downhill"`: multiply steepness by 1.2 + - `"Slalom"`: multiply steepness by 0.9 + - `"Giant Slalom"`: multiply steepness by 1.0 + +Return: + +- `"Green"` if the adjusted steepness is less than or equal to 0.1 +- `"Blue"` if the adjusted steepness is greater than 0.1 and less than or equal to 0.25 +- `"Black"` if the adjusted steepness is greater than 0.25 + +# --hints-- + +`getHillRating(95, 900, "Slalom")` should return `"Green"`. + +```js +assert.equal(getHillRating(95, 900, "Slalom"), "Green"); +``` + +`getHillRating(620, 2800, "Downhill")` should return `"Black"`. + +```js +assert.equal(getHillRating(620, 2800, "Downhill"), "Black"); +``` + +`getHillRating(420, 1680, "Giant Slalom")` should return `"Blue"`. + +```js +assert.equal(getHillRating(420, 1680, "Giant Slalom"), "Blue"); +``` + +`getHillRating(250, 3000, "Downhill")` should return `"Green"`. + +```js +assert.equal(getHillRating(250, 3000, "Downhill"), "Green"); +``` + +`getHillRating(110, 900, "Slalom")` should return `"Blue"`. + +```js +assert.equal(getHillRating(110, 900, "Slalom"), "Blue"); +``` + +`getHillRating(380, 1500, "Giant Slalom")` should return `"Black"`. + +```js +assert.equal(getHillRating(380, 1500, "Giant Slalom"), "Black"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getHillRating(drop, distance, type) { + + return drop; +} +``` + +# --solutions-- + +```js +function getHillRating(drop, distance, type) { + let steepness = drop / distance; + + if (type === "Downhill") { + steepness *= 1.2; + } else if (type === "Slalom") { + steepness *= 0.9; + } else if (type === "Giant Slalom") { + steepness *= 1.0; + } + + if (steepness <= 0.1) { + return "Green"; + } else if (steepness <= 0.25) { + return "Blue"; + } else { + return "Black"; + } +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e9860d24853adef67b.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e9860d24853adef67b.md new file mode 100644 index 0000000000000000000000000000000000000000..7a2caaffcac130c28ea75d4079cc20fb5e0987d6 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e9860d24853adef67b.md @@ -0,0 +1,75 @@ +--- +id: 697a49e9860d24853adef67b +title: "Challenge 190: Winter Games Day 11: Ice Hockey" +challengeType: 28 +dashedName: challenge-190 +--- + +# --description-- + +Given an array of 6 ice hockey teams and their records after the round robin games, determine the match-ups for the semi-final round. + +- Each array item will have a team and their record in the format `"TEAM: W-OTW-OTL-L"`. Where: + - `"W"` is the number of wins in regulation, worth 3 points each + - `"OTW"` is the number of overtime wins, worth 2 points each + - `"OTL"` is the number of overtime losses, worth 1 point each + - `"L"` is the number of losses, worth 0 points each + +For example, `"FIN: 2-2-1-0"` would have 11 points after adding up their record. + +Find the total number of points for each team and return `"The semi-final games will be (1st) vs (4th) and (2nd) vs (3rd)."`. For example, `"The semi-final games will be FIN vs SWE and CAN vs USA."` + +# --hints-- + +`getSemifinalMatchups(["CAN: 2-2-0-1", "FIN: 2-2-1-0", "GER: 1-0-1-3", "SUI: 0-1-3-1", "SWE: 1-1-2-1", "USA: 2-1-0-2"])` should return `"The semi-final games will be FIN vs SWE and CAN vs USA."`. + +```js +assert.equal(getSemifinalMatchups(["CAN: 2-2-0-1", "FIN: 2-2-1-0", "GER: 1-0-1-3", "SUI: 0-1-3-1", "SWE: 1-1-2-1", "USA: 2-1-0-2"]), "The semi-final games will be FIN vs SWE and CAN vs USA."); +``` + +`getSemifinalMatchups(["CAN: 2-1-1-1", "CZE: 1-1-1-2", "FIN: 1-2-1-1", "NOR: 0-1-1-3", "SLO: 1-0-1-3", "USA: 5-0-0-0"])` should return `"The semi-final games will be USA vs CZE and CAN vs FIN."`. + +```js +assert.equal(getSemifinalMatchups(["CAN: 2-1-1-1", "CZE: 1-1-1-2", "FIN: 1-2-1-1", "NOR: 0-1-1-3", "SLO: 1-0-1-3", "USA: 5-0-0-0"]), "The semi-final games will be USA vs CZE and CAN vs FIN."); +``` + +`getSemifinalMatchups(["CAN: 3-2-0-0", "CZE: 2-1-2-0", "LAT: 0-0-1-4", "ITA: 1-1-1-2", "DEN: 1-0-0-4", "USA: 3-1-1-0"])` should return `"The semi-final games will be CAN vs ITA and USA vs CZE."`. + +```js +assert.equal(getSemifinalMatchups(["CAN: 3-2-0-0", "CZE: 2-1-2-0", "LAT: 0-0-1-4", "ITA: 1-1-1-2", "DEN: 1-0-0-4", "USA: 3-1-1-0"]), "The semi-final games will be CAN vs ITA and USA vs CZE."); +``` + +`getSemifinalMatchups(["AUT: 2-2-1-0", "DEN: 1-0-0-4", "ITA: 1-1-1-2", "JPN: 3-2-0-0", "KOR: 2-1-2-0", "LAT: 0-0-1-4"])` should return `"The semi-final games will be JPN vs ITA and AUT vs KOR."`. + +```js +assert.equal(getSemifinalMatchups(["AUT: 2-2-1-0", "DEN: 1-0-0-4", "ITA: 1-1-1-2", "JPN: 3-2-0-0", "KOR: 2-1-2-0", "LAT: 0-0-1-4"]), "The semi-final games will be JPN vs ITA and AUT vs KOR."); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getSemifinalMatchups(teams) { + + return teams; +} +``` + +# --solutions-- + +```js +function getSemifinalMatchups(teams) { + const teamPoints = teams.map(teamStr => { + const [name, record] = teamStr.split(": "); + const [W, OTW, OTL, L] = record.split("-").map(Number); + const points = W * 3 + OTW * 2 + OTL * 1 + L * 0; + return { name, points }; + }); + + teamPoints.sort((a, b) => b.points - a.points); + const [first, second, third, fourth] = teamPoints; + + return `The semi-final games will be ${first.name} vs ${fourth.name} and ${second.name} vs ${third.name}.`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e9860d24853adef67c.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e9860d24853adef67c.md new file mode 100644 index 0000000000000000000000000000000000000000..e2f05e4cda0b5a737aaba12aa6a95db1d87488b1 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e9860d24853adef67c.md @@ -0,0 +1,122 @@ +--- +id: 697a49e9860d24853adef67c +title: "Challenge 191: Winter Games Day 12: Bobsled" +challengeType: 28 +dashedName: challenge-191 +--- + +# --description-- + +Given an array representing the weights of the athletes on a bobsled team and a number representing the weight of the bobsled, determine whether the team is eligible to race. + +- The length of the array determines the team size: 1, 2 or 4 person teams. +- All given weight values are in kilograms (kg). + +The bobsled (sled by itself) must have a minimum weight of: + +- 162 kg for a 1-person team +- 170 kg for a 2-person team +- 210 kg for a 4-person team + +The total weight of the bobsled (athletes plus sled) must not exceed: + +- 247 kg for a 1-person team +- 390 kg for a 2-person team +- 630 kg for a 4-person team + +Return `"Eligible"` if the team meets all the requirements, or `"Not Eligible"` if the team fails to meet one or more of the requirements. + +# --hints-- + +`checkEligibility([78], 165)` should return `"Eligible"`. + +```js +assert.equal(checkEligibility([78], 165), "Eligible"); +``` + +`checkEligibility([80], 160)` should return `"Not Eligible"`. + +```js +assert.equal(checkEligibility([80], 160), "Not Eligible"); +``` + +`checkEligibility([80], 170)` should return `"Not Eligible"`. + +```js +assert.equal(checkEligibility([80], 170), "Not Eligible"); +``` + +`checkEligibility([85, 90], 170)` should return `"Eligible"`. + +```js +assert.equal(checkEligibility([85, 90], 170), "Eligible"); +``` + +`checkEligibility([85, 95], 168)` should return `"Not Eligible"`. + +```js +assert.equal(checkEligibility([85, 95], 168), "Not Eligible"); +``` + +`checkEligibility([112, 97], 185)` should return `"Not Eligible"`. + +```js +assert.equal(checkEligibility([112, 97], 185), "Not Eligible"); +``` + +`checkEligibility([110, 102, 90, 106], 222)` should return `"Eligible"`. + +```js +assert.equal(checkEligibility([110, 102, 90, 106], 222), "Eligible"); +``` + +`checkEligibility([106, 99, 90, 88], 205)` should return `"Not Eligible"`. + +```js +assert.equal(checkEligibility([106, 99, 90, 88], 205), "Not Eligible"); +``` + +`checkEligibility([106, 99, 103, 96], 227)` should return `"Not Eligible"`. + +```js +assert.equal(checkEligibility([106, 99, 103, 96], 227), "Not Eligible"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function checkEligibility(athleteWeights, sledWeight) { + + return athleteWeights; +} +``` + +# --solutions-- + +```js +function checkEligibility(athleteWeights, sledWeight) { + const teamSize = athleteWeights.length; + + const rules = { + 1: { minSled: 162, maxTotal: 247 }, + 2: { minSled: 170, maxTotal: 390 }, + 4: { minSled: 210, maxTotal: 630 } + }; + + const { minSled, maxTotal } = rules[teamSize]; + const athleteTotal = athleteWeights.reduce((sum, w) => sum + w, 0); + const totalWeight = athleteTotal + sledWeight; + + if (sledWeight < minSled) { + return "Not Eligible"; + } + + if (totalWeight > maxTotal) { + return "Not Eligible"; + } + + return "Eligible"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e9860d24853adef67d.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e9860d24853adef67d.md new file mode 100644 index 0000000000000000000000000000000000000000..fbc96e29c4463b28c69e5f34b9bf58d89e4d885f --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e9860d24853adef67d.md @@ -0,0 +1,60 @@ +--- +id: 697a49e9860d24853adef67d +title: "Challenge 192: Winter Games Day 13: Nordic Combined" +challengeType: 28 +dashedName: challenge-192 +--- + +# --description-- + +Given an array of jump scores for athletes, calculate their start delay times for the cross-country portion of the Nordic Combined. + +The athlete with the highest jump score starts first (0 second delay). All other athletes start later based on how far behind their jump score is compared to the best jump. + +To calculate the delay for each athlete, subtract the athlete's jump score from the best overall jump score and multiply the result by 1.5. Round the delay up to the nearest integer. + +# --hints-- + +`calculateStartDelays([120, 110, 125])` should return `[8, 23, 0]`. + +```js +assert.deepEqual(calculateStartDelays([120, 110, 125]), [8, 23, 0]); +``` + +`calculateStartDelays([118, 125, 122, 120])` should return `[11, 0, 5, 8]`. + +```js +assert.deepEqual(calculateStartDelays([118, 125, 122, 120]), [11, 0, 5, 8]); +``` + +`calculateStartDelays([100, 105, 95, 110, 120, 115, 108])` should return `[30, 23, 38, 15, 0, 8, 18]`. + +```js +assert.deepEqual(calculateStartDelays([100, 105, 95, 110, 120, 115, 108]), [30, 23, 38, 15, 0, 8, 18]); +``` + +`calculateStartDelays([130, 125, 128, 120, 118, 122, 127, 115, 132, 124])` should return `[3, 11, 6, 18, 21, 15, 8, 26, 0, 12]`. + +```js +assert.deepEqual(calculateStartDelays([130, 125, 128, 120, 118, 122, 127, 115, 132, 124]), [3, 11, 6, 18, 21, 15, 8, 26, 0, 12]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function calculateStartDelays(jumpScores) { + + return jumpScores; +} +``` + +# --solutions-- + +```js +function calculateStartDelays(jumpScores) { + const bestJump = Math.max(...jumpScores); + return jumpScores.map(score => Math.ceil((bestJump - score) * 1.5)); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e9860d24853adef67e.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e9860d24853adef67e.md new file mode 100644 index 0000000000000000000000000000000000000000..1cbf52f0dbaf77587ee45112c169cea2395ec97c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e9860d24853adef67e.md @@ -0,0 +1,114 @@ +--- +id: 697a49e9860d24853adef67e +title: "Challenge 193: Winter Games Day 14: Ski Mountaineering" +challengeType: 28 +dashedName: challenge-193 +--- + +# --description-- + +Given the snow depth and slope of a mountain, determine if there's an avalanche risk. + +- The snow depth values are `"Shallow"`, `"Moderate"`, or `"Deep"`. +- Slope values are `"Gentle"`, `"Steep"`, or `"Very Steep"`. + +Return `"Safe"` or `"Risky"` based on this table: + +| |`"Shallow"`|`"Moderate"`|`"Deep"`| +|-|-|-|-| +|`"Gentle"`|`"Safe"`|`"Safe"`|`"Safe"`| +|`"Steep"`|`"Safe"`|`"Risky"`|`"Risky"`| +|`"Very Steep"`|`"Safe"`| `"Risky"`|`"Risky"`| + +# --hints-- + +`avalancheRisk("Shallow", "Gentle")` should return `"Safe"`. + +```js +assert.equal(avalancheRisk("Shallow", "Gentle"), "Safe"); +``` + +`avalancheRisk("Shallow", "Steep")` should return `"Safe"`. + +```js +assert.equal(avalancheRisk("Shallow", "Steep"), "Safe"); +``` + +`avalancheRisk("Shallow", "Very Steep")` should return `"Safe"`. + +```js +assert.equal(avalancheRisk("Shallow", "Very Steep"), "Safe"); +``` + +`avalancheRisk("Moderate", "Gentle")` should return `"Safe"`. + +```js +assert.equal(avalancheRisk("Moderate", "Gentle"), "Safe"); +``` + +`avalancheRisk("Moderate", "Steep")` should return `"Risky"`. + +```js +assert.equal(avalancheRisk("Moderate", "Steep"), "Risky"); +``` + +`avalancheRisk("Moderate", "Very Steep")` should return `"Risky"`. + +```js +assert.equal(avalancheRisk("Moderate", "Very Steep"), "Risky"); +``` + +`avalancheRisk("Deep", "Gentle")` should return `"Safe"`. + +```js +assert.equal(avalancheRisk("Deep", "Gentle"), "Safe"); +``` + +`avalancheRisk("Deep", "Steep")` should return `"Risky"`. + +```js +assert.equal(avalancheRisk("Deep", "Steep"), "Risky"); +``` + +`avalancheRisk("Deep", "Very Steep")` should return `"Risky"`. + +```js +assert.equal(avalancheRisk("Deep", "Very Steep"), "Risky"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function avalancheRisk(snowDepth, slope) { + + return snowDepth; +} +``` + +# --solutions-- + +```js +function avalancheRisk(snowDepth, slope) { + const riskTable = { + Gentle: { + Shallow: "Safe", + Moderate: "Safe", + Deep: "Safe", + }, + Steep: { + Shallow: "Safe", + Moderate: "Risky", + Deep: "Risky", + }, + "Very Steep": { + Shallow: "Safe", + Moderate: "Risky", + Deep: "Risky", + }, + }; + + return riskTable[slope][snowDepth]; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e9860d24853adef67f.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e9860d24853adef67f.md new file mode 100644 index 0000000000000000000000000000000000000000..7d0dd2e750974c7fab54f49e9eeb24a633fb6fee --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e9860d24853adef67f.md @@ -0,0 +1,106 @@ +--- +id: 697a49e9860d24853adef67f +title: "Challenge 194: Winter Games Day 15: Freestyle Skiing" +challengeType: 28 +dashedName: challenge-194 +--- + +# --description-- + +Given a trick name consisting of two words, determine if it is a valid freestyle skiing trick name. + +A trick is valid if the first word is in the list of valid first words, and the second word is in the list of valid second words. + +- The two words will be separated by a single space. + +Valid first words: + +|`"Misty"`| +|-| +|`"Ghost"`| +|`"Thunder"`| +|`"Solar"`| +|`"Sky"`| +|`"Phantom"`| +|`"Frozen"`| +|`"Polar"`| + +Valid second words: + +|`"Twister"`| +|-| +|`"Icequake"`| +|`"Avalanche"`| +|`"Vortex"`| +|`"Snowstorm"`| +|`"Frostbite"`| +|`"Blizzard"`| +|`"Shadow"`| + +# --hints-- + +`isValidTrick("Polar Vortex")` should return `true`. + +```js +assert.isTrue(isValidTrick("Polar Vortex")); +``` + +`isValidTrick("Solar Icequake")` should return `true`. + +```js +assert.isTrue(isValidTrick("Solar Icequake")); +``` + +`isValidTrick("Thunder Blizzard")` should return `true`. + +```js +assert.isTrue(isValidTrick("Thunder Blizzard")); +``` + +`isValidTrick("Phantom Frostbite")` should return `true`. + +```js +assert.isTrue(isValidTrick("Phantom Frostbite")); +``` + +`isValidTrick("Ghost Avalanche")` should return `true`. + +```js +assert.isTrue(isValidTrick("Ghost Avalanche")); +``` + +`isValidTrick("Snowstorm Shadow")` should return `false`. + +```js +assert.isFalse(isValidTrick("Snowstorm Shadow")); +``` + +`isValidTrick("Solar Sky")` should return `false`. + +```js +assert.isFalse(isValidTrick("Solar Sky")); +``` + +# --seed-- + +## --seed-contents-- + +```js +function isValidTrick(trickName) { + + return trickName; +} +``` + +# --solutions-- + +```js +function isValidTrick(trickName) { + const validFirst = ["Misty", "Ghost", "Thunder", "Solar", "Sky", "Phantom", "Frozen", "Polar"]; + const validSecond = ["Twister", "Icequake", "Avalanche", "Vortex", "Snowstorm", "Frostbite", "Blizzard", "Shadow"]; + + const words = trickName.split(" "); + const [first, second] = words; + return validFirst.includes(first) && validSecond.includes(second); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e9860d24853adef680.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e9860d24853adef680.md new file mode 100644 index 0000000000000000000000000000000000000000..b0f6c97ec759cdae13aeff3eb7702a60280993df --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e9860d24853adef680.md @@ -0,0 +1,142 @@ +--- +id: 697a49e9860d24853adef680 +title: "Challenge 195: Winter Games Day 16: Curling" +challengeType: 28 +dashedName: challenge-195 +--- + +# --description-- + +Given a 5x5 matrix representing the "house" at the end of a curling round, determine which team scores and how many points they score. + +The layout: + +- The center cell (index `[2, 2]`) is the "button". +- The 8 cells directly surrounding the button represent ring 1. +- And the 16 cells on the outer edge of the house represent ring 2. + +In the given matrix: + +- `"."` represents an empty space. +- `"R"` represents a space with a red stone. +- `"Y"` represents a space with a yellow stone. + +Scoring rules: + +- Only one team can score per round. +- The team with the stone closest to the button scores. +- The scoring team earns 1 point for each of their stones that is closer to the button than the opponent's closest stone. +- The lower the ring number, the closer to the center the stone is. +- If both teams' closest stone is the same distance from the center, no team scores. + +Return: + +- A string in the format `"team: number_of_points"`. e.g: `"R: 2"`. +- or `"No points awarded"` if neither team scored any points. + +For example, given: + +```js +[ + [".", ".", "R", ".", "."], + [".", "R", ".", ".", "."], + ["Y", ".", ".", ".", "."], + [".", "R", ".", ".", "."], + [".", ".", ".", ".", "."] +] +``` + +Return `"R: 2"`. The two red stones in ring 1 are tied for the closest and are the only two stones closer than yellows closest. + +# --hints-- + +`scoreCurling([[".", ".", "R", ".", "."], [".", "R", ".", ".", "."], ["Y", ".", ".", ".", "."], [".", "R", ".", ".", "."], [".", ".", ".", ".", "."]])` should return `"R: 2"`. + +```js +assert.equal(scoreCurling([[".", ".", "R", ".", "."], [".", "R", ".", ".", "."], ["Y", ".", ".", ".", "."], [".", "R", ".", ".", "."], [".", ".", ".", ".", "."]]), "R: 2"); +``` + +`scoreCurling([[".", ".", "R", ".", "."], [".", ".", ".", ".", "."], [".", ".", "Y", ".", "R"], [".", ".", "Y", "Y", "."], [".", "Y", "R", "R", "."]])` should return `"Y: 3"`. + +```js +assert.equal(scoreCurling([[".", ".", "R", ".", "."], [".", ".", ".", ".", "."], [".", ".", "Y", ".", "R"], [".", ".", "Y", "Y", "."], [".", "Y", "R", "R", "."]]), "Y: 3"); +``` + +`scoreCurling([[".", "R", "Y", ".", "."], ["Y", ".", ".", ".", "."], [".", ".", ".", ".", "."], [".", "Y", "R", "Y", "."], [".", ".", "R", "R", "."]])` should return `"No points awarded"`. + +```js +assert.equal(scoreCurling([[".", "R", "Y", ".", "."], ["Y", ".", ".", ".", "."], [".", ".", ".", ".", "."], [".", "Y", "R", "Y", "."], [".", ".", "R", "R", "."]]), "No points awarded"); +``` + +`scoreCurling([[".", "Y", "Y", ".", "."], ["Y", ".", ".", "R", "."], [".", ".", "R", ".", "."], [".", ".", "R", "R", "."], [".", "Y", "R", "Y", "."]])` should return `"R: 4"`. + +```js +assert.equal(scoreCurling([[".", "Y", "Y", ".", "."], ["Y", ".", ".", "R", "."], [".", ".", "R", ".", "."], [".", ".", "R", "R", "."], [".", "Y", "R", "Y", "."]]), "R: 4"); +``` + +`scoreCurling([["Y", "Y", "Y", "Y", "Y"], ["Y", "R", "R", "R", "Y"], ["Y", "R", "Y", "R", "Y"], ["Y", "R", "R", "R", "Y"], ["Y", "Y", "Y", "Y", "Y"]])` should return `"Y: 1"`. + +```js +assert.equal(scoreCurling([["Y", "Y", "Y", "Y", "Y"], ["Y", "R", "R", "R", "Y"], ["Y", "R", "Y", "R", "Y"], ["Y", "R", "R", "R", "Y"], ["Y", "Y", "Y", "Y", "Y"]]), "Y: 1"); +``` + +`scoreCurling([["Y", "R", "Y", "R", "Y"], ["R", ".", ".", ".", "R"], ["Y", ".", ".", ".", "Y"], ["R", ".", ".", ".", "R"], ["Y", ".", ".", "R", "Y"]])` should return `"No points awarded"`. + +```js +assert.equal(scoreCurling([["Y", "R", "Y", "R", "Y"], ["R", ".", ".", ".", "R"], ["Y", ".", ".", ".", "Y"], ["R", ".", ".", ".", "R"], ["Y", ".", ".", "R", "Y"]]), "No points awarded"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function scoreCurling(house) { + + return house; +} +``` + +# --solutions-- + +```js +function scoreCurling(house) { + const stones = { R: [], Y: [] }; + + for (let i = 0; i < 5; i++) { + for (let j = 0; j < 5; j++) { + const cell = house[i][j]; + if (cell === 'R' || cell === 'Y') { + const distance = Math.max(Math.abs(i - 2), Math.abs(j - 2)); + stones[cell].push(distance); + } + } + } + + const redClosest = stones.R.length > 0 ? Math.min(...stones.R) : Infinity; + const yellowClosest = stones.Y.length > 0 ? Math.min(...stones.Y) : Infinity; + + if (redClosest === Infinity && yellowClosest === Infinity) { + return "No points awarded"; + } + + if (redClosest === yellowClosest) { + return "No points awarded"; + } + +let winner, opponentClosest, winningStones; + if (redClosest < yellowClosest) { + winner = 'R'; + opponentClosest = yellowClosest; + winningStones = stones.R; + } else { + winner = 'Y'; + opponentClosest = redClosest; + winningStones = stones.Y; + } + + const points = winningStones.filter(d => d < opponentClosest).length; + + return points === 0 ? "No points awarded" : `${winner}: ${points}`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e9860d24853adef681.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e9860d24853adef681.md new file mode 100644 index 0000000000000000000000000000000000000000..badde9d37200fcf5d31b2e058dc7fe2c0f8bf159 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/697a49e9860d24853adef681.md @@ -0,0 +1,133 @@ +--- +id: 697a49e9860d24853adef681 +title: "Challenge 196: Winter Games Day 17: Closing Day" +challengeType: 28 +dashedName: challenge-196 +--- + +# --description-- + +Given a 2D array of medal winners, return a medal count for each country as a CSV string. + +- In the given array, each sub-array represents a single event: `[gold_winner, silver_winner, bronze_winner]` + +- The returned CSV string should have the following format, with the first line being headers: + +```sh +Country,Gold,Silver,Bronze,Total +country_name,gold_count,silver_count,bronze_count,total_medals +``` + +- Separate new lines with the new line character (`"\n"`). +- Do not include spaces around commas or at the end of lines. +- Sort the returned CSV by gold medal count, highest first. If two countries have the same gold medal count, sort the tied ones alphabetically. + +For example, given: + +```js +[ + ["USA", "CAN", "NOR"], + ["NOR", "USA", "CAN"], + ["USA", "NOR", "SWE"] +] +``` + +Return: + +```sh +"Country,Gold,Silver,Bronze,Total\nUSA,2,1,0,3\nNOR,1,1,1,3\nCAN,0,1,1,2\nSWE,0,0,1,1" +``` + +Which looks like this when printed: + +```sh +Country,Gold,Silver,Bronze,Total +USA,2,1,0,3 +NOR,1,1,1,3 +CAN,0,1,1,2 +SWE,0,0,1,1 +``` + +# --hints-- + +`countMedals([["USA", "CAN", "NOR"], ["NOR", "USA", "CAN"], ["USA", "NOR", "SWE"]])` should return `"Country,Gold,Silver,Bronze,Total\nUSA,2,1,0,3\nNOR,1,1,1,3\nCAN,0,1,1,2\nSWE,0,0,1,1"`. + +```js +assert.equal(countMedals([["USA", "CAN", "NOR"], ["NOR", "USA", "CAN"], ["USA", "NOR", "SWE"]]), "Country,Gold,Silver,Bronze,Total\nUSA,2,1,0,3\nNOR,1,1,1,3\nCAN,0,1,1,2\nSWE,0,0,1,1"); +``` + +`countMedals([["NOR","SWE","FIN"]])` should return `"Country,Gold,Silver,Bronze,Total\nNOR,1,0,0,1\nFIN,0,0,1,1\nSWE,0,1,0,1"`. + +```js +assert.equal(countMedals([["NOR","SWE","FIN"]]), "Country,Gold,Silver,Bronze,Total\nNOR,1,0,0,1\nFIN,0,0,1,1\nSWE,0,1,0,1"); +``` + +`countMedals([["ITA", "CHN", "CHN"], ["JPN", "ITA", "JPN"]])` should return `"Country,Gold,Silver,Bronze,Total\nITA,1,1,0,2\nJPN,1,0,1,2\nCHN,0,1,1,2"`. + +```js +assert.equal(countMedals([["ITA", "CHN", "CHN"], ["JPN", "ITA", "JPN"]]), "Country,Gold,Silver,Bronze,Total\nITA,1,1,0,2\nJPN,1,0,1,2\nCHN,0,1,1,2"); +``` + +`countMedals([["USA","CAN","NOR"], ["GER","FRA","ITA"], ["JPN","KOR","CHN"], ["SWE","FIN","NOR"], ["CAN","USA","SWE"], ["FRA","GER","ITA"]])` should return `"Country,Gold,Silver,Bronze,Total\nCAN,1,1,0,2\nFRA,1,1,0,2\nGER,1,1,0,2\nJPN,1,0,0,1\nSWE,1,0,1,2\nUSA,1,1,0,2\nCHN,0,0,1,1\nFIN,0,1,0,1\nITA,0,0,2,2\nKOR,0,1,0,1\nNOR,0,0,2,2"`. + +```js +assert.equal(countMedals([["USA","CAN","NOR"], ["GER","FRA","ITA"], ["JPN","KOR","CHN"], ["SWE","FIN","NOR"], ["CAN","USA","SWE"], ["FRA","GER","ITA"]]), "Country,Gold,Silver,Bronze,Total\nCAN,1,1,0,2\nFRA,1,1,0,2\nGER,1,1,0,2\nJPN,1,0,0,1\nSWE,1,0,1,2\nUSA,1,1,0,2\nCHN,0,0,1,1\nFIN,0,1,0,1\nITA,0,0,2,2\nKOR,0,1,0,1\nNOR,0,0,2,2"); +``` + +`countMedals([["ESP","ITA","FRA"], ["ITA","ESP","GER"], ["NOR","SWE","FIN"], ["FIN","NOR","SWE"], ["USA","CAN","MEX"], ["CAN","USA","MEX"], ["JPN","KOR","CHN"], ["CHN","JPN","KOR"]])` should return `"Country,Gold,Silver,Bronze,Total\nCAN,1,1,0,2\nCHN,1,0,1,2\nESP,1,1,0,2\nFIN,1,0,1,2\nITA,1,1,0,2\nJPN,1,1,0,2\nNOR,1,1,0,2\nUSA,1,1,0,2\nFRA,0,0,1,1\nGER,0,0,1,1\nKOR,0,1,1,2\nMEX,0,0,2,2\nSWE,0,1,1,2"`. + +```js +assert.equal(countMedals([["ESP","ITA","FRA"], ["ITA","ESP","GER"], ["NOR","SWE","FIN"], ["FIN","NOR","SWE"], ["USA","CAN","MEX"], ["CAN","USA","MEX"], ["JPN","KOR","CHN"], ["CHN","JPN","KOR"]]), "Country,Gold,Silver,Bronze,Total\nCAN,1,1,0,2\nCHN,1,0,1,2\nESP,1,1,0,2\nFIN,1,0,1,2\nITA,1,1,0,2\nJPN,1,1,0,2\nNOR,1,1,0,2\nUSA,1,1,0,2\nFRA,0,0,1,1\nGER,0,0,1,1\nKOR,0,1,1,2\nMEX,0,0,2,2\nSWE,0,1,1,2"); +``` + +`countMedals([["USA","CAN","GER"], ["NOR","SWE","FIN"], ["USA","NOR","SWE"], ["GER","FRA","ITA"], ["JPN","KOR","CHN"], ["USA","GER","CAN"], ["SWE","NOR","FIN"], ["CAN","USA","NOR"], ["FRA","GER","ITA"], ["JPN","CHN","KOR"], ["SWE","FIN","NOR"], ["GER","ITA","FRA"]])` should return `"Country,Gold,Silver,Bronze,Total\nUSA,3,1,0,4\nGER,2,2,1,5\nJPN,2,0,0,2\nSWE,2,1,1,4\nCAN,1,1,1,3\nFRA,1,1,1,3\nNOR,1,2,2,5\nCHN,0,1,1,2\nFIN,0,1,2,3\nITA,0,1,2,3\nKOR,0,1,1,2"`. + +```js +assert.equal(countMedals([["USA","CAN","GER"], ["NOR","SWE","FIN"], ["USA","NOR","SWE"], ["GER","FRA","ITA"], ["JPN","KOR","CHN"], ["USA","GER","CAN"], ["SWE","NOR","FIN"], ["CAN","USA","NOR"], ["FRA","GER","ITA"], ["JPN","CHN","KOR"], ["SWE","FIN","NOR"], ["GER","ITA","FRA"]]), "Country,Gold,Silver,Bronze,Total\nUSA,3,1,0,4\nGER,2,2,1,5\nJPN,2,0,0,2\nSWE,2,1,1,4\nCAN,1,1,1,3\nFRA,1,1,1,3\nNOR,1,2,2,5\nCHN,0,1,1,2\nFIN,0,1,2,3\nITA,0,1,2,3\nKOR,0,1,1,2"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function countMedals(winners) { + + return winners; +} +``` + +# --solutions-- + +```js +function countMedals(winners) { + const counts = {}; + + for (const [gold, silver, bronze] of winners) { + if (!counts[gold]) counts[gold] = { Gold: 0, Silver: 0, Bronze: 0 }; + if (!counts[silver]) counts[silver] = { Gold: 0, Silver: 0, Bronze: 0 }; + if (!counts[bronze]) counts[bronze] = { Gold: 0, Silver: 0, Bronze: 0 }; + + counts[gold].Gold += 1; + counts[silver].Silver += 1; + counts[bronze].Bronze += 1; + } + + const countries = Object.entries(counts).map(([country, medals]) => ({ + Country: country, + Gold: medals.Gold, + Silver: medals.Silver, + Bronze: medals.Bronze, + Total: medals.Gold + medals.Silver + medals.Bronze + })); + + countries.sort((a, b) => b.Gold - a.Gold || a.Country.localeCompare(b.Country)); + + const lines = ["Country,Gold,Silver,Bronze,Total"]; + for (const c of countries) { + lines.push(`${c.Country},${c.Gold},${c.Silver},${c.Bronze},${c.Total}`); + } + + return lines.join("\n"); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa0.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa0.md new file mode 100644 index 0000000000000000000000000000000000000000..0974adf41b92405f7c992a0a190e211f72e6da70 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa0.md @@ -0,0 +1,129 @@ +--- +id: 698a1a73ade5ac0e19180fa0 +title: "Challenge 197: Blood Type Compatibility" +challengeType: 28 +dashedName: challenge-197 +--- + +# --description-- + +Given a donor blood type and a recipient blood type, determine whether the donor can give blood to the recipient. + +Each blood type consists of: + +- A letter: `"A"`, `"B"`, `"AB"`, or `"O"` +- And an Rh factor: `"+"` or `"-"` + +Blood types will be one of the valid letters followed by an Rh factor. For example, `"AB+"` and `"O-"` are valid blood types. + +Letter Rules: + +- `"O"` can donate to other letter type. +- `"A"` can donate to `"A"` and `"AB"`. +- `"B"` can donate to `"B"` and `"AB"`. +- `"AB"` can donate only to `"AB"`. + +Rh Rules: + +- Negative (`"-"`) can donate to both `"-"` and `"+"`. +- Positive (`"+"`) can donate only to `"+"`. + +Both letter and Rh rule must pass for a donor to be able to donate to the recipient. + +# --hints-- + +`canDonate("B+", "B+")` should return `true`. + +```js +assert.isTrue(canDonate("B+", "B+")); +``` + +`canDonate("O-", "AB-")` should return `true`. + +```js +assert.isTrue(canDonate("O-", "AB-")); +``` + +`canDonate("O+", "A-")` should return `false`. + +```js +assert.isFalse(canDonate("O+", "A-")); +``` + +`canDonate("A+", "AB+")` should return `true`. + +```js +assert.isTrue(canDonate("A+", "AB+")); +``` + +`canDonate("A-", "B-")` should return `false`. + +```js +assert.isFalse(canDonate("A-", "B-")); +``` + +`canDonate("B-", "AB+")` should return `true`. + +```js +assert.isTrue(canDonate("B-", "AB+")); +``` + +`canDonate("B-", "A+")` should return `false`. + +```js +assert.isFalse(canDonate("B-", "A+")); +``` + +`canDonate("O-", "O+")` should return `true`. + +```js +assert.isTrue(canDonate("O-", "O+")); +``` + +`canDonate("O+", "O-")` should return `false`. + +```js +assert.isFalse(canDonate("O+", "O-")); +``` + +`canDonate("AB+", "AB-")` should return `false`. + +```js +assert.isFalse(canDonate("AB+", "AB-")); +``` + +# --seed-- + +## --seed-contents-- + +```js +function canDonate(donor, recipient) { + + return donor; +} +``` + +# --solutions-- + +```js +function canDonate(donor, recipient) { + const donorType = donor.slice(0, -1); + const donorRh = donor.slice(-1); + + const recipientType = recipient.slice(0, -1); + const recipientRh = recipient.slice(-1); + + const aboCompatibility = { + "O": ["A", "B", "AB", "O"], + "A": ["A", "AB"], + "B": ["B", "AB"], + "AB": ["AB"] + }; + + const aboMatch = aboCompatibility[donorType].includes(recipientType); + const rhMatch = + donorRh === "-" || (donorRh === "+" && recipientRh === "+"); + + return aboMatch && rhMatch; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa1.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa1.md new file mode 100644 index 0000000000000000000000000000000000000000..8c288dc5ad312faf70e9508ddeee5569451b3937 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa1.md @@ -0,0 +1,78 @@ +--- +id: 698a1a73ade5ac0e19180fa1 +title: "Challenge 198: Business Day Count" +challengeType: 28 +dashedName: challenge-198 +--- + +# --description-- + +Given a start date and an end date, return the number of business days between the two. + +- Given dates are in the format `"YYYY-MM-DD"`. +- Weekdays are business days (Monday through Friday). +- Weekends are not business days (Saturday and Sunday). +- Include both the start and end dates when counting. + +# --hints-- + +`countBusinessDays("2026-02-24", "2026-02-26")` should return `3`. + +```js +assert.equal(countBusinessDays("2026-02-24", "2026-02-26"), 3); +``` + +`countBusinessDays("2026-02-24", "2026-02-28")` should return `4`. + +```js +assert.equal(countBusinessDays("2026-02-24", "2026-02-28"), 4); +``` + +`countBusinessDays("2026-02-21", "2026-03-01")` should return `5`. + +```js +assert.equal(countBusinessDays("2026-02-21", "2026-03-01"), 5); +``` + +`countBusinessDays("2026-03-08", "2026-03-17")` should return `7`. + +```js +assert.equal(countBusinessDays("2026-03-08", "2026-03-17"), 7); +``` + +`countBusinessDays("2026-02-24", "2027-02-24")` should return `262`. + +```js +assert.equal(countBusinessDays("2026-02-24", "2027-02-24"), 262); +``` + +# --seed-- + +## --seed-contents-- + +```js +function countBusinessDays(start, end) { + + return start; +} +``` + +# --solutions-- + +```js +function countBusinessDays(start, end) { + const startDate = new Date(start + "T00:00:00Z"); + const endDate = new Date(end + "T00:00:00Z"); + + let count = 0; + let current = new Date(startDate); + + while (current <= endDate) { + const day = current.getUTCDay(); + if (day !== 0 && day !== 6) count++; + current.setUTCDate(current.getUTCDate() + 1); + } + + return count; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa2.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa2.md new file mode 100644 index 0000000000000000000000000000000000000000..98d47ccd3a16c8dce4fa1d154e4ec707b42cc465 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa2.md @@ -0,0 +1,71 @@ +--- +id: 698a1a73ade5ac0e19180fa2 +title: "Challenge 199: Sequential Difference" +challengeType: 28 +dashedName: challenge-199 +--- + +# --description-- + +Given an array of numbers, return a new array containing the value needed to get from each number to the next number. + +- For the last number, use `0` since there is no next number. + +For example, given `[1, 2, 4, 7]`, return `[1, 2, 3, 0]`. + +# --hints-- + +`findDifferences([1, 2, 4, 7])` should return `[1, 2, 3, 0]`. + +```js +assert.deepEqual(findDifferences([1, 2, 4, 7]), [1, 2, 3, 0]); +``` + +`findDifferences([10, 15, 19, 22, 24, 25])` should return `[5, 4, 3, 2, 1, 0]`. + +```js +assert.deepEqual(findDifferences([10, 15, 19, 22, 24, 25]), [5, 4, 3, 2, 1, 0]); +``` + +`findDifferences([25, 20, 16, 13, 11, 10])` should return `[-5, -4, -3, -2, -1, 0]`. + +```js +assert.deepEqual(findDifferences([25, 20, 16, 13, 11, 10]), [-5, -4, -3, -2, -1, 0]); +``` + +`findDifferences([0, 1, 2, 2, 3, 3, 4, 5])` should return `[ 1, 1, 0, 1, 0, 1, 1, 0 ]`. + +```js +assert.deepEqual(findDifferences([0, 1, 2, 2, 3, 3, 4, 5]), [ 1, 1, 0, 1, 0, 1, 1, 0 ]); +``` + +`findDifferences([1, 2, 5, 12, 34, -15, -1, 41, 113, -222, -99, -40, 10, -18, -6, -2, -1])` should return `[1, 3, 7, 22, -49, 14, 42, 72, -335, 123, 59, 50, -28, 12, 4, 1, 0]`. + +```js +assert.deepEqual(findDifferences([1, 2, 5, 12, 34, -15, -1, 41, 113, -222, -99, -40, 10, -18, -6, -2, -1]), [1, 3, 7, 22, -49, 14, 42, 72, -335, 123, 59, 50, -28, 12, 4, 1, 0]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function findDifferences(arr) { + + return arr; +} +``` + +# --solutions-- + +```js +function findDifferences(arr) { + const result = []; + + for (let i = 0; i < arr.length; i++) { + result.push(arr[i + 1] - arr[i] || 0); + } + + return result; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa3.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa3.md new file mode 100644 index 0000000000000000000000000000000000000000..70e0620afef76ac797e7c5dfed950509b2e18f19 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa3.md @@ -0,0 +1,81 @@ +--- +id: 698a1a73ade5ac0e19180fa3 +title: "Challenge 200: Letter and Number Count" +challengeType: 28 +dashedName: challenge-200 +--- + +# --description-- + +Given a string, return a message with the count of how many letters and numbers it contains. + +- Letters are `A-Z` and `a-z`. +- Numbers are `0-9`. +- Ignore all other characters. + +Return `"The string has X letters and Y numbers."`, where `"X"` is the count of letters and `"Y"` is the count of numbers. If either count is 1, use the singular form for that item. E.g: `"1 letter"` instead of `"1 letters"` and `"1 number"` instead of `"1 numbers"`. + +# --hints-- + +`countLettersAndNumbers("helloworld123")` should return `"The string has 10 letters and 3 numbers."`. + +```js +assert.equal(countLettersAndNumbers("helloworld123"), "The string has 10 letters and 3 numbers."); +``` + +`countLettersAndNumbers("Catch 22")` should return `"The string has 5 letters and 2 numbers."`. + +```js +assert.equal(countLettersAndNumbers("Catch 22"), "The string has 5 letters and 2 numbers."); +``` + +`countLettersAndNumbers("A1!")` should return `"The string has 1 letter and 1 number."`. + +```js +assert.equal(countLettersAndNumbers("A1!"), "The string has 1 letter and 1 number."); +``` + +`countLettersAndNumbers("12345")` should return `"The string has 0 letters and 5 numbers."`. + +```js +assert.equal(countLettersAndNumbers("12345"), "The string has 0 letters and 5 numbers."); +``` + +`countLettersAndNumbers("password")` should return `"The string has 8 letters and 0 numbers."`. + +```js +assert.equal(countLettersAndNumbers("password"), "The string has 8 letters and 0 numbers."); +``` + +# --seed-- + +## --seed-contents-- + +```js +function countLettersAndNumbers(str) { + + return str; +} +``` + +# --solutions-- + +```js +function countLettersAndNumbers(str) { + let letterCount = 0; + let numberCount = 0; + + for (let char of str) { + if ((char >= 'A' && char <= 'Z') || (char >= 'a' && char <= 'z')) { + letterCount++; + } else if (char >= '0' && char <= '9') { + numberCount++; + } + } + + const letterWord = letterCount === 1 ? "letter" : "letters"; + const numberWord = numberCount === 1 ? "number" : "numbers"; + + return `The string has ${letterCount} ${letterWord} and ${numberCount} ${numberWord}.`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa4.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa4.md new file mode 100644 index 0000000000000000000000000000000000000000..42ef6792b8bb006c07acd5c8dda4ae34a5f3126b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa4.md @@ -0,0 +1,106 @@ +--- +id: 698a1a73ade5ac0e19180fa4 +title: "Challenge 201: Matrix Shift" +challengeType: 28 +dashedName: challenge-201 +--- + +# --description-- + +Given a matrix (array of arrays) of numbers and an integer, shift all values in the matrix by the given amount. + +- A positive shift moves values to the right. +- A negative shift moves values to the left. + +Values should wrap: + +- Treat the matrix as one continuous sequence of values. +- When a value moves past the end of a row, it continues at the beginning of the next row. +- When a value moves past the last position in the matrix, it wraps to the first position. +- The same applies in reverse when shifting left. + +For example, given: + +```js +[ + [1, 2, 3], + [4, 5, 6] +] +``` + +with a shift of `1`, move all the numbers to the right one: + +```js +[ + [6, 1, 2], + [3, 4, 5] +] +``` + +# --hints-- + +`shiftMatrix([[1, 2, 3], [4, 5, 6]], 1)` should return `[[6, 1, 2], [3, 4, 5]]`. + +```js +assert.deepEqual(shiftMatrix([[1, 2, 3], [4, 5, 6]], 1), [[6, 1, 2], [3, 4, 5]]); +``` + +`shiftMatrix([[1, 2, 3], [4, 5, 6]], -1)` should return `[[2, 3, 4], [5, 6, 1]]`. + +```js +assert.deepEqual(shiftMatrix([[1, 2, 3], [4, 5, 6]], -1), [[2, 3, 4], [5, 6, 1]]); +``` + +`shiftMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 5)` should return `[[5, 6, 7], [8, 9, 1], [2, 3, 4]]`. + +```js +assert.deepEqual(shiftMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 5), [[5, 6, 7], [8, 9, 1], [2, 3, 4]]); +``` + +`shiftMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]], -6)` should return `[[7, 8, 9], [1, 2, 3], [4, 5, 6]]`. + +```js +assert.deepEqual(shiftMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]], -6), [[7, 8, 9], [1, 2, 3], [4, 5, 6]]); +``` + +`shiftMatrix([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 7)` should return `[[10, 11, 12, 13], [14, 15, 16, 1], [2, 3, 4, 5], [6, 7, 8, 9]]`. + +```js +assert.deepEqual(shiftMatrix([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 7), [[10, 11, 12, 13], [14, 15, 16, 1], [2, 3, 4, 5], [6, 7, 8, 9]]); +``` + +`shiftMatrix([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], -54)` should return `[[7, 8, 9, 10], [11, 12, 13, 14], [15, 16, 1, 2], [3, 4, 5, 6]]`. + +```js +assert.deepEqual(shiftMatrix([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], -54), [[7, 8, 9, 10], [11, 12, 13, 14], [15, 16, 1, 2], [3, 4, 5, 6]]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function shiftMatrix(matrix, shift) { + + return matrix; +} +``` + +# --solutions-- + +```js +function shiftMatrix(matrix, shift) { + const rows = matrix.length; + const cols = matrix[0].length; + const flat = matrix.flat(); + const n = flat.length; + const s = ((shift % n) + n) % n; + const shifted = flat.slice(-s).concat(flat.slice(0, n - s)); + const result = []; + for (let i = 0; i < rows; i++) { + result.push(shifted.slice(i * cols, (i + 1) * cols)); + } + + return result; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa5.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa5.md new file mode 100644 index 0000000000000000000000000000000000000000..4aa0a08862c680a1720ed4745d7d10697e79427e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa5.md @@ -0,0 +1,76 @@ +--- +id: 698a1a73ade5ac0e19180fa5 +title: "Challenge 202: Add Punctuation" +challengeType: 28 +dashedName: challenge-202 +--- + +# --description-- + +Given a string of sentences with missing periods, add a period (`"."`) in the following places: + +- Before each space that comes immediately before an uppercase letter +- And at the end of the string + +Return the resulting string. + +# --hints-- + +`addPunctuation("Hello world")` should return `"Hello world."` + +```js +assert.equal(addPunctuation("Hello world"), "Hello world."); +``` + +`addPunctuation("Hello world It's nice today")` should return `"Hello world. It's nice today."` + +```js +assert.equal(addPunctuation("Hello world It's nice today"), "Hello world. It's nice today."); +``` + +`addPunctuation("JavaScript is great Sometimes")` should return `"JavaScript is great. Sometimes."` + +```js +assert.equal(addPunctuation("JavaScript is great Sometimes"), "JavaScript is great. Sometimes."); +``` + +`addPunctuation("A b c D e F g h I J k L m n o P Q r S t U v w X Y Z")` should return `"A b c. D e. F g h. I. J k. L m n o. P. Q r. S t. U v w. X. Y. Z."` + +```js +assert.equal(addPunctuation("A b c D e F g h I J k L m n o P Q r S t U v w X Y Z"), "A b c. D e. F g h. I. J k. L m n o. P. Q r. S t. U v w. X. Y. Z."); +``` + +`addPunctuation("Wait.. For it")` should return `"Wait... For it."` + +```js +assert.equal(addPunctuation("Wait.. For it"), "Wait... For it."); +``` + +# --seed-- + +## --seed-contents-- + +```js +function addPunctuation(sentences) { + + return sentences; +} +``` + +# --solutions-- + +```js +function addPunctuation(sentences) { + let result = ""; + + for (let i = 0; i < sentences.length; i++) { + if (sentences[i] === " " && i + 1 < sentences.length && /[A-Z]/.test(sentences[i + 1])) { + result += "."; + } + result += sentences[i]; + } + result += "."; + + return result; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa6.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa6.md new file mode 100644 index 0000000000000000000000000000000000000000..8b591f3188b359794d9e9bcdcef9cca96fb65436 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa6.md @@ -0,0 +1,66 @@ +--- +id: 698a1a73ade5ac0e19180fa6 +title: "Challenge 203: Flattened" +challengeType: 28 +dashedName: challenge-203 +--- + +# --description-- + +Given an array, determine if it is flat. + +- An array is flat if none of its elements are arrays. + +# --hints-- + +`isFlat([1, 2, 3, 4])` should return `true`. + +```js +assert.isTrue(isFlat([1, 2, 3, 4])); +``` + +`isFlat([1, [2, 3], 4])` should return `false`. + +```js +assert.isFalse(isFlat([1, [2, 3], 4])); +``` + +`isFlat([1, 0, false, true, "a", "b"])` should return `true`. + +```js +assert.isTrue(isFlat([1, 0, false, true, "a", "b"])); +``` + +`isFlat(["a", [0], "b", true])` should return `false`. + +```js +assert.isFalse(isFlat(["a", [0], "b", true])); +``` + +`isFlat([1, [2, [3, [4, [5]]]], 6])` should return `false`. + +```js +assert.isFalse(isFlat([1, [2, [3, [4, [5]]]], 6])); +``` + +# --seed-- + +## --seed-contents-- + +```js +function isFlat(arr) { + + return arr; +} +``` + +# --solutions-- + +```js +function isFlat(arr) { + for (let el of arr) { + if (Array.isArray(el)) return false; + } + return true; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa7.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa7.md new file mode 100644 index 0000000000000000000000000000000000000000..599d03329f18146f45a2f99abc464bb8bb364f2b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa7.md @@ -0,0 +1,73 @@ +--- +id: 698a1a73ade5ac0e19180fa7 +title: "Challenge 204: Sum the Letters" +challengeType: 28 +dashedName: challenge-204 +--- + +# --description-- + +Given a string, return the sum of its letters. + +- Letters are A-Z in uppercase or lowercase +- Letter values are: `"A"` = 1, `"B"` = 2, ..., `"Z"` = 26 +- Uppercase and lowercase letters have the same value. +- Ignore all non-letter characters. + +# --hints-- + +`sumLetters("Hello")` should return `52`. + +```js +assert.equal(sumLetters("Hello"), 52); +``` + +`sumLetters("freeCodeCamp")` should return `94`. + +```js +assert.equal(sumLetters("freeCodeCamp"), 94); +``` + +`sumLetters("The quick brown fox jumps over the lazy dog.")` should return `473`. + +```js +assert.equal(sumLetters("The quick brown fox jumps over the lazy dog."), 473); +``` + +`sumLetters("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ex nisl, pretium eu varius blandit, facilisis quis eros. Vestibulum ante ipsum primis in faucibus orci.")` should return `1681`. + +```js +assert.equal(sumLetters("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ex nisl, pretium eu varius blandit, facilisis quis eros. Vestibulum ante ipsum primis in faucibus orci."), 1681); +``` + +`sumLetters("")` should return `0`. + +```js +assert.equal(sumLetters(""), 0); +``` + +# --seed-- + +## --seed-contents-- + +```js +function sumLetters(str) { + + return str; +} +``` + +# --solutions-- + +```js +function sumLetters(str) { + let total = 0; + for (let char of str) { + let upper = char.toUpperCase(); + if (upper >= "A" && upper <= "Z") { + total += upper.charCodeAt(0) - "A".charCodeAt(0) + 1; + } + } + return total; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa8.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa8.md new file mode 100644 index 0000000000000000000000000000000000000000..4777a938a69f1fe042f712c8a24ce289525f24b4 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa8.md @@ -0,0 +1,81 @@ +--- +id: 698a1a73ade5ac0e19180fa8 +title: "Challenge 205: Perfect Cube Count" +challengeType: 28 +dashedName: challenge-205 +--- + +# --description-- + +Given two integers, determine how many perfect cubes exist in the range between and including the two numbers. + +- The lower number is not guaranteed to be the first argument. +- A number is a perfect cube if there exists an integer (`n`) where `n * n * n = number`. For example, 27 is a perfect cube because `3 * 3 * 3 = 27`. + +# --hints-- + +`countPerfectCubes(3, 30)` should return `2`. + +```js +assert.equal(countPerfectCubes(3, 30), 2); +``` + +`countPerfectCubes(1, 30)` should return `3`. + +```js +assert.equal(countPerfectCubes(1, 30), 3); +``` + +`countPerfectCubes(30, 0)` should return `4`. + +```js +assert.equal(countPerfectCubes(30, 0), 4); +``` + +`countPerfectCubes(-64, 64)` should return `9`. + +```js +assert.equal(countPerfectCubes(-64, 64), 9); +``` + +`countPerfectCubes(9214, -8127)` should return `41`. + +```js +assert.equal(countPerfectCubes(9214, -8127), 41); +``` + +# --seed-- + +## --seed-contents-- + +```js +function countPerfectCubes(a, b) { + + return a; +} +``` + +# --solutions-- + +```js +function countPerfectCubes(a, b) { + const start = Math.min(a, b); + const end = Math.max(a, b); + + let count = 0; + let n = 0; + + while (n ** 3 <= end) { + if (n ** 3 >= start) count++; + n++; + } + + n = -1; + while (n ** 3 >= start) { + if (n ** 3 <= end) count++; + n--; + } + + return count; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa9.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa9.md new file mode 100644 index 0000000000000000000000000000000000000000..a1a2cad3dd0cfbba95675f0dd4eeb99efd3167e6 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a73ade5ac0e19180fa9.md @@ -0,0 +1,92 @@ +--- +id: 698a1a73ade5ac0e19180fa9 +title: "Challenge 206: Playing Card Values" +challengeType: 28 +dashedName: challenge-206 +--- + +# --description-- + +Given an array of playing cards, return a new array with the numeric value of each card. + +Card Values: + +- An Ace (`"A"`) has a value of 1. +- Numbered cards (`"2"` - `"10"`) have their face value: 2 - 10, respectively. +- Face cards: Jack (`"J"`), Queen (`"Q"`), and King (`"K"`) are each worth 10. + +Suits: + +- Each card has a suit: Spades (`"S"`), Clubs (`"C"`), Diamonds (`"D"`), or Hearts (`"H"`). + +Card Format: + +- Each card is represented as a string: `"valueSuit"`. For Example: `"AS"` is the Ace of Spades, `"10H"` is the Ten of Hearts, and `"QC"` is the Queen of Clubs. + +# --hints-- + +`cardValues(["3H", "4D", "5S"])` should return `[3, 4, 5]`. + +```js +assert.deepEqual(cardValues(["3H", "4D", "5S"]), [3, 4, 5]); +``` + +`cardValues(["AS", "10S", "10H", "6D", "7D"])` should return `[1, 10, 10, 6, 7]`. + +```js +assert.deepEqual(cardValues(["AS", "10S", "10H", "6D", "7D"]), [1, 10, 10, 6, 7]); +``` + +`cardValues(["8D", "QS", "2H", "JC", "9C"])` should return `[8, 10, 2, 10, 9]`. + +```js +assert.deepEqual(cardValues(["8D", "QS", "2H", "JC", "9C"]), [8, 10, 2, 10, 9]); +``` + +`cardValues(["AS", "KS"])` should return `[1, 10]`. + +```js +assert.deepEqual(cardValues(["AS", "KS"]), [1, 10]); +``` + +`cardValues(["10H", "JH", "QH", "KH", "AH"])` should return `[10, 10, 10, 10, 1]`. + +```js +assert.deepEqual(cardValues(["10H", "JH", "QH", "KH", "AH"]), [10, 10, 10, 10, 1]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function cardValues(cards) { + + return cards; +} +``` + +# --solutions-- + +```js +function cardValues(cards) { + const values = []; + + for (let card of cards) { + let valueStr = card.slice(0, card.length - 1); + + let value; + if (valueStr === "A") { + value = 1; + } else if (["J", "Q", "K"].includes(valueStr)) { + value = 10; + } else { + value = parseInt(valueStr, 10); + } + + values.push(value); + } + + return values; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a863194f1f4e63f645e.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a863194f1f4e63f645e.md new file mode 100644 index 0000000000000000000000000000000000000000..eeb9646390c42e02793ca687b27cd069e8624117 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a863194f1f4e63f645e.md @@ -0,0 +1,89 @@ +--- +id: 698a1a863194f1f4e63f645e +title: "Challenge 207: Smallest Gap" +challengeType: 28 +dashedName: challenge-207 +--- + +# --description-- + +Given a string, return the substring between the two identical characters that have the smallest number of characters between them (smallest gap). + +- There will always be at least one pair of matching characters. +- The returned substring should exclude the matching characters. +- If two or more gaps are the same length, return the characters from the first one. + +For example, given `"ABCDAC"`, return `"DA"` because: + +- Only `"A"` and `"C"` repeat in the string. +- The number of characters between the two `"A"` characters is 3, and between the `"C"` characters is 2. +- So return the string between the two `"C"` characters. + +# --hints-- + +`smallestGap("ABCDAC")` should return `"DA"`. + +```js +assert.equal(smallestGap("ABCDAC"), "DA"); +``` + +`smallestGap("racecar")` should return `"e"`. + +```js +assert.equal(smallestGap("racecar"), "e"); +``` + +`smallestGap("A{5e^SD*F4i!o#q6e&rkf(po8|we9+kr-2!3}=4")` should return `"#q6e&rkf(p"`. + +```js +assert.equal(smallestGap("A{5e^SD*F4i!o#q6e&rkf(po8|we9+kr-2!3}=4"), "#q6e&rkf(p"); +``` + +`smallestGap("Hello World")` should return `""`. + +```js +assert.equal(smallestGap("Hello World"), ""); +``` + +`smallestGap("The quick brown fox jumps over the lazy dog.")` should return `"fox"`. + +```js +assert.equal(smallestGap("The quick brown fox jumps over the lazy dog."), "fox"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function smallestGap(str) { + + return str; +} +``` + +# --solutions-- + +```js +function smallestGap(str) { + let minGap = Infinity; + let result = ""; + + for (let i = 0; i < str.length; i++) { + for (let j = i + 1; j < str.length; j++) { + if (str[i] === str[j]) { + const gap = j - i - 1; + + if (gap < minGap) { + minGap = gap; + result = str.slice(i + 1, j); + } + + break; + } + } + } + + return result; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a863194f1f4e63f645f.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a863194f1f4e63f645f.md new file mode 100644 index 0000000000000000000000000000000000000000..fafee2ad4b05fb17b6ccf9ada73fa424e38ae2dd --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a863194f1f4e63f645f.md @@ -0,0 +1,138 @@ +--- +id: 698a1a863194f1f4e63f645f +title: "Challenge 208: Trail Traversal" +challengeType: 28 +dashedName: challenge-208 +--- + +# --description-- + +Given an array of strings representing your trail map, return a string of the moves needed to get to your goal. + +The given strings will contain the values: + +- `"C"`: Your current location +- `"G"`: Your goal +- `"T"`: Traversable parts of the trail +- `"-"`: Untraversable parts of the map + +Return a string with the moves needed to follow the trail from your location to your goal where: + +- `"R"` is a move right +- `"D"` is a move down +- `"L"` is a move left +- `"U"` is a move up + +- There will always be a single continuous trail, without any branching, from your current location to your goal. +- Each trail location will have a maximum of two traversable locations touching it. + +For example, given: + +```js +[ + "-CT--", + "--T--", + "--TT-", + "---T-", + "---G-" +] +``` + +Return `"RDDRDD"`. + +# --hints-- + +`navigateTrail(["-CT--", "--T--", "--TT-", "---T-", "---G-"])` should return `"RDDRDD"`. + +```js +assert.equal(navigateTrail(["-CT--", "--T--", "--TT-", "---T-", "---G-"]), "RDDRDD"); +``` + +`navigateTrail(["-----", "--TTG", "--T--", "--T--", "CTT--"])` should return `"RRUUURR"`. + +```js +assert.equal(navigateTrail(["-----", "--TTG", "--T--", "--T--", "CTT--"]), "RRUUURR"); +``` + +`navigateTrail(["-C----", "TT----", "T-----", "TTTTT-", "----G-"])` should return `"DLDDRRRRD"`. + +```js +assert.equal(navigateTrail(["-C----", "TT----", "T-----", "TTTTT-", "----G-"]), "DLDDRRRRD"); +``` + +`navigateTrail(["--------", "-CTTT---", "----T---", "---GT---", "--------"])` should return `"RRRDDL"`. + +```js +assert.equal(navigateTrail(["--------", "-CTTT---", "----T---", "---GT---", "--------"]), "RRRDDL"); +``` + +`navigateTrail(["TTTTTTT-", "T-----T-", "T-----T-", "TTTT--TG", "---C----"])` should return `"ULLLUUURRRRRRDDDR"`. + +```js +assert.equal(navigateTrail(["TTTTTTT-", "T-----T-", "T-----T-", "TTTT--TG", "---C----"]), "ULLLUUURRRRRRDDDR"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function navigateTrail(map) { + + return map; +} +``` + +# --solutions-- + +```js +function navigateTrail(map) { + const rows = map.length; + const cols = map[0].length; + + const directions = [ + [0, 1, "R"], + [1, 0, "D"], + [0, -1, "L"], + [-1, 0, "U"], + ]; + + let row, col; + for (let r = 0; r < rows; r++) { + for (let c = 0; c < cols; c++) { + if (map[r][c] === "C") { + row = r; + col = c; + } + } + } + + let result = ""; + let prev = null; + + while (map[row][col] !== "G") { + for (let [dr, dc, move] of directions) { + const newRow = row + dr; + const newCol = col + dc; + + if ( + newRow >= 0 && + newRow < rows && + newCol >= 0 && + newCol < cols && + (map[newRow][newCol] === "T" || + map[newRow][newCol] === "G") && + (!prev || newRow !== prev[0] || newCol !== prev[1]) + ) { + result += move; + prev = [row, col]; + row = newRow; + col = newCol; + break; + } + } + } + + return result; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a863194f1f4e63f6460.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a863194f1f4e63f6460.md new file mode 100644 index 0000000000000000000000000000000000000000..189ed134ce8bcc455e1226bd3db8ae7961f8f3a7 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/698a1a863194f1f4e63f6460.md @@ -0,0 +1,82 @@ +--- +id: 698a1a863194f1f4e63f6460 +title: "Challenge 209: Element Size" +challengeType: 28 +dashedName: challenge-209 +--- + +# --description-- + +Given a window size, the width of an element in viewport width `"vw"` units, and the height of an element in viewport height `"vh"` units, determine the size of the element in pixels. + +- The given window size and returned element size are strings in the format `"width x height"`, `"1200 x 800"` for example. + +- `"vw"` units are the percent of window width. `"50vw"` for example, is 50% of the width of the window. +- `"vh"` units are the percent of window height. `"50vh"` for example, is 50% of the height of the window. + +# --hints-- + +`getElementSize("1200 x 800", "50vw", "50vh")` should return `"600 x 400"`. + +```js +assert.equal(getElementSize("1200 x 800", "50vw", "50vh"), "600 x 400"); +``` + +`getElementSize("320 x 480", "25vw", "50vh")` should return `"80 x 240"`. + +```js +assert.equal(getElementSize("320 x 480", "25vw", "50vh"), "80 x 240"); +``` + +`getElementSize("1000 x 500", "7vw", "3vh")` should return `"70 x 15"`. + +```js +assert.equal(getElementSize("1000 x 500", "7vw", "3vh"), "70 x 15"); +``` + +`getElementSize("1920 x 1080", "95vw", "100vh")` should return `"1824 x 1080"`. + +```js +assert.equal(getElementSize("1920 x 1080", "95vw", "100vh"), "1824 x 1080"); +``` + +`getElementSize("1200 x 800", "0vw", "0vh")` should return `"0 x 0"`. + +```js +assert.equal(getElementSize("1200 x 800", "0vw", "0vh"), "0 x 0"); +``` + +`getElementSize("1440 x 900", "100vw", "114vh")` should return `"1440 x 1026"`. + +```js +assert.equal(getElementSize("1440 x 900", "100vw", "114vh"), "1440 x 1026"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getElementSize(windowSize, elementVw, elementVh) { + + return windowSize; +} +``` + +# --solutions-- + +```js +function getElementSize(windowSize, elementVw, elementVh) { + const [windowWidth, windowHeight] = windowSize + .split(" x ") + .map(Number); + + const vw = Number(elementVw.replace("vw", "")); + const vh = Number(elementVh.replace("vh", "")); + + const widthPx = (vw / 100) * windowWidth; + const heightPx = (vh / 100) * windowHeight; + + return `${widthPx} x ${heightPx}`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6994cff2290543b3aec9f50f.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6994cff2290543b3aec9f50f.md new file mode 100644 index 0000000000000000000000000000000000000000..dacefa8dcf0afda89cec1f2d94f1a58be672d507 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6994cff2290543b3aec9f50f.md @@ -0,0 +1,112 @@ +--- +id: 6994cff2290543b3aec9f50f +title: "Challenge 210: HSL Validator" +challengeType: 28 +dashedName: challenge-210 +--- + +# --description-- + +Given a string, determine whether it is a valid CSS `hsl()` color value. + +- A valid HSL value must be in the format `"hsl(h, s%, l%)"`, where: + - `h` (hue) must be a number between 0 and 360 (inclusive). + - `s` (saturation) must be a percentage between 0% and 100%. + - `l` (lightness) must be a percentage between 0% and 100%. + +- Spaces are only allowed: + - After the opening parenthesis + - Before and/or after the commas + - Before and/or after closing parenthesis + +- Optionally, the value can end with a semi-colon (`";"`). + +For example, `"hsl(240, 50%, 50%)"` is a valid HSL value. + +# --hints-- + +`isValidHSL("hsl(240, 50%, 50%)")` should return `true`. + +```js +assert.isTrue(isValidHSL("hsl(240, 50%, 50%)")); +``` + +`isValidHSL("hsl( 200 , 50% , 75% )")` should return `true`. + +```js +assert.isTrue(isValidHSL("hsl( 200 , 50% , 75% )")); +``` + +`isValidHSL("hsl(99,60%,80%);")` should return `true`. + +```js +assert.isTrue(isValidHSL("hsl(99,60%,80%);")); +``` + +`isValidHSL("hsl(0, 0%, 0%) ;")` should return `true`. + +```js +assert.isTrue(isValidHSL("hsl(0, 0%, 0%) ;")); +``` + +`isValidHSL("hsl( 10 , 20% , 30% ) ;")` should return `true`. + +```js +assert.isTrue(isValidHSL("hsl( 10 , 20% , 30% ) ;")); +``` + +`isValidHSL("hsl(361, 50%, 80%)")` should return `false`. + +```js +assert.isFalse(isValidHSL("hsl(361, 50%, 80%)")); +``` + +`isValidHSL("hsl(300, 101%, 70%)")` should return `false`. + +```js +assert.isFalse(isValidHSL("hsl(300, 101%, 70%)")); +``` + +`isValidHSL("hsl(200, 55%, 75)")` should return `false`. + +```js +assert.isFalse(isValidHSL("hsl(200, 55%, 75)")); +``` + +`isValidHSL("hsl (80, 20%, 10%)")` should return `false`. + +```js +assert.isFalse(isValidHSL("hsl (80, 20%, 10%)")); +``` + +# --seed-- + +## --seed-contents-- + +```js +function isValidHSL(hsl) { + + return hsl; +} +``` + +# --solutions-- + +```js +function isValidHSL(hsl) { + const regex = /^hsl\(\s*(\d{1,3})\s*,\s*(\d{1,3})%\s*,\s*(\d{1,3})%\s*\)\s*;?$/; + + const match = hsl.match(regex); + if (!match) return false; + + const hue = Number(match[1]); + const sat = Number(match[2]); + const light = Number(match[3]); + + if (hue < 0 || hue > 360) return false; + if (sat < 0 || sat > 100) return false; + if (light < 0 || light > 100) return false; + + return true; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6994cff2290543b3aec9f510.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6994cff2290543b3aec9f510.md new file mode 100644 index 0000000000000000000000000000000000000000..2eb16d90f9a70b1c2fbdfe8b939fa45f0310dc96 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6994cff2290543b3aec9f510.md @@ -0,0 +1,62 @@ +--- +id: 6994cff2290543b3aec9f510 +title: "Challenge 211: Array Sum" +challengeType: 28 +dashedName: challenge-211 +--- + +# --description-- + +Given an array of numbers, return the sum of all the numbers. + +# --hints-- + +`sumArray([1, 2, 3, 4, 5])` should return `15`. + +```js +assert.equal(sumArray([1, 2, 3, 4, 5]), 15); +``` + +`sumArray([42])` should return `42`. + +```js +assert.equal(sumArray([42]), 42); +``` + +`sumArray([5, -2, 7, -3])` should return `7`. + +```js +assert.equal(sumArray([5, -2, 7, -3]), 7); +``` + +`sumArray([203, 145, -129, 6293, 523, -919, 845, 2434])` should return `9395`. + +```js +assert.equal(sumArray([203, 145, -129, 6293, 523, -919, 845, 2434]), 9395); +``` + +`sumArray([0, 0])` should return `0`. + +```js +assert.equal(sumArray([0, 0]), 0); +``` + +# --seed-- + +## --seed-contents-- + +```js +function sumArray(numbers) { + + return numbers; +} +``` + +# --solutions-- + +```js +function sumArray(numbers) { + + return numbers.reduce((a, c) => c + a, 0); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6994cff2290543b3aec9f511.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6994cff2290543b3aec9f511.md new file mode 100644 index 0000000000000000000000000000000000000000..783dd89a0d101da3006611153947eed19740660f --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6994cff2290543b3aec9f511.md @@ -0,0 +1,59 @@ +--- +id: 6994cff2290543b3aec9f511 +title: "Challenge 212: Array Insertion" +challengeType: 28 +dashedName: challenge-212 +--- + +# --description-- + +Given an array, a value to insert into the array, and an index to insert the value at, return a new array with the value inserted at the specified index. + +# --hints-- + +`insertIntoArray([2, 4, 8, 10], 6, 2)` should return `[2, 4, 6, 8, 10]`. + +```js +assert.deepEqual(insertIntoArray([2, 4, 8, 10], 6, 2), [2, 4, 6, 8, 10]); +``` + +`insertIntoArray(["the", "quick", "fox"], "brown", 2)` should return `["the", "quick", "brown", "fox"]`. + +```js +assert.deepEqual(insertIntoArray(["the", "quick", "fox"], "brown", 2), ["the", "quick", "brown", "fox"]); +``` + +`insertIntoArray([], 0, 0)` should return `[0]`. + +```js +assert.deepEqual(insertIntoArray([], 0, 0), [0]); +``` + +`insertIntoArray([0, 1, 1, 2, 3, 8, 13], 5, 5)` should return `[0, 1, 1, 2, 3, 5, 8, 13]`. + +```js +assert.deepEqual(insertIntoArray([0, 1, 1, 2, 3, 8, 13], 5, 5), [0, 1, 1, 2, 3, 5, 8, 13]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function insertIntoArray(arr, value, index) { + + return arr; +} +``` + +# --solutions-- + +```js +function insertIntoArray(arr, value, index) { + return [ + ...arr.slice(0, index), + value, + ...arr.slice(index) + ]; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322d4.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322d4.md new file mode 100644 index 0000000000000000000000000000000000000000..b62c5ae4dc88a1e40ea44cde5b08b5c21ec31543 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322d4.md @@ -0,0 +1,63 @@ +--- +id: 699c8e045ee7cb94ed2322d4 +title: "Challenge 213: Word Length Converter" +challengeType: 28 +dashedName: challenge-213 +--- + +# --description-- + +Given a string of words, return a new string where each word is replaced by its length. + +- Words in the given string will be separated by a single space +- Keep the spaces in the returned string. + +For example, given `"hello world"`, return `"5 5"`. + +# --hints-- + +`convertWords("hello world")` should return `"5 5"`. + +```js +assert.equal(convertWords("hello world"), "5 5"); +``` + +`convertWords("Thanks and happy coding")` should return `"6 3 5 6"`. + +```js +assert.equal(convertWords("Thanks and happy coding"), "6 3 5 6"); +``` + +`convertWords("The quick brown fox jumps over the lazy dog")` should return `"3 5 5 3 5 4 3 4 3"`. + +```js +assert.equal(convertWords("The quick brown fox jumps over the lazy dog"), "3 5 5 3 5 4 3 4 3"); +``` + +`convertWords("Lorem ipsum dolor sit amet consectetur adipiscing elit donec ut ligula vehicula iaculis orci vel semper nisl")` should return `"5 5 5 3 4 11 10 4 5 2 6 8 7 4 3 6 4"`. + +```js +assert.equal(convertWords("Lorem ipsum dolor sit amet consectetur adipiscing elit donec ut ligula vehicula iaculis orci vel semper nisl"), "5 5 5 3 4 11 10 4 5 2 6 8 7 4 3 6 4"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function convertWords(str) { + + return str; +} +``` + +# --solutions-- + +```js +function convertWords(str) { + return str + .split(" ") + .map(word => word.length) + .join(" "); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322d5.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322d5.md new file mode 100644 index 0000000000000000000000000000000000000000..5010da1a186c3a6743d93054d1ebdade80d8cd7d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322d5.md @@ -0,0 +1,69 @@ +--- +id: 699c8e045ee7cb94ed2322d5 +title: "Challenge 214: Domino Chain Validator" +challengeType: 28 +dashedName: challenge-214 +--- + +# --description-- + +Given a 2D array representing a sequence of dominoes, determine whether it forms a valid chain. + +- Each element in the array represents a domino and will be an array of two numbers from 1 to 6, (inclusive). +- For the chain to be valid, the second number of each domino must match the first number of the next domino. +- The first number of the first domino and the last number of the last domino don't need to match anything. + +# --hints-- + +`isValidDominoChain([[1, 3], [3, 6], [6, 5]])` should return `true`. + +```js +assert.isTrue(isValidDominoChain([[1, 3], [3, 6], [6, 5]])); +``` + +`isValidDominoChain([[6, 2], [3, 4], [4, 1]])` should return `false`. + +```js +assert.isFalse(isValidDominoChain([[6, 2], [3, 4], [4, 1]])); +``` + +`isValidDominoChain([[2, 5], [5, 6], [5, 1]])` should return `false`. + +```js +assert.isFalse(isValidDominoChain([[2, 5], [5, 6], [5, 1]])); +``` + +`isValidDominoChain([[4, 3], [3, 1], [1, 6], [6, 6], [6, 5], [5, 1], [1, 1], [1, 4], [4, 4], [4, 2]])` should return `true`. + +```js +assert.isTrue(isValidDominoChain([[4, 3], [3, 1], [1, 6], [6, 6], [6, 5], [5, 1], [1, 1], [1, 4], [4, 4], [4, 2]])); +``` + +`isValidDominoChain([[2, 3], [3, 3], [3, 6], [6, 1], [1, 4], [3, 5], [5, 5], [5, 4], [4, 2], [2, 2]])` should return `false`. + +```js +assert.isFalse(isValidDominoChain([[2, 3], [3, 3], [3, 6], [6, 1], [1, 4], [3, 5], [5, 5], [5, 4], [4, 2], [2, 2]])); +``` + +# --seed-- + +## --seed-contents-- + +```js +function isValidDominoChain(dominoes) { + + return dominoes; +} +``` + +# --solutions-- + +```js +function isValidDominoChain(dominoes) { + for (let i = 0; i < dominoes.length - 1; i++) { + if (dominoes[i][1] !== dominoes[i+1][0]) return false + } + + return true; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322d6.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322d6.md new file mode 100644 index 0000000000000000000000000000000000000000..3f02eaf3a7f45a841da999e7f777abf98aaf890d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322d6.md @@ -0,0 +1,109 @@ +--- +id: 699c8e045ee7cb94ed2322d6 +title: "Challenge 215: Parking Fee Calculator" +challengeType: 28 +dashedName: challenge-215 +--- + +# --description-- + +Given two strings representing the time you parked your car and the time you picked it up, calculate the parking fee. + +- The given strings will be in the format `"HH:MM"` using a 24-hour clock. So `"14:00"` is 2pm for example. +- The first string will be the time you parked your car, and the second will be the time you picked it up. +- If the pickup time is earlier than the entry time, it means the parking spanned past midnight into the next day. + +Fee rules: + +- Each hour parked costs $3. +- Partial hours are rounded up to the next full hour. +- If the parking spans overnight (past midnight), an additional $10 overnight fee is applied. +- There is a minimum fee of $5 (only used if the total would be less than $5). + +Return the total cost in the format `"$cost"`, `"$5"` for example. + +# --hints-- + +`calculateParkingFee("09:00", "11:00")` should return `"$6"`. + +```js +assert.equal(calculateParkingFee("09:00", "11:00"), "$6"); +``` + +`calculateParkingFee("10:00", "10:30")` should return `"$5"`. + +```js +assert.equal(calculateParkingFee("10:00", "10:30"), "$5"); +``` + +`calculateParkingFee("08:10", "10:45")` should return `"$9"`. + +```js +assert.equal(calculateParkingFee("08:10", "10:45"), "$9"); +``` + +`calculateParkingFee("14:40", "23:10")` should return `"$27"`. + +```js +assert.equal(calculateParkingFee("14:40", "23:10"), "$27"); +``` + +`calculateParkingFee("18:15", "01:30")` should return `"$34"`. + +```js +assert.equal(calculateParkingFee("18:15", "01:30"), "$34"); +``` + +`calculateParkingFee("11:11", "11:10")` should return `"$82"`. + +```js +assert.equal(calculateParkingFee("11:11", "11:10"), "$82"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function calculateParkingFee(parkTime, pickupTime) { + + return parkTime; +} +``` + +# --solutions-- + +```js +function calculateParkingFee(parkTime, pickupTime) { + function toMinutes(time) { + const [hours, minutes] = time.split(":").map(Number); + return hours * 60 + minutes; + } + + const entryMinutes = toMinutes(parkTime); + const exitMinutes = toMinutes(pickupTime); + + let totalMinutes; + let overnight = false; + + if (exitMinutes < entryMinutes) { + overnight = true; + totalMinutes = (24 * 60 - entryMinutes) + exitMinutes; + } else { + totalMinutes = exitMinutes - entryMinutes; + } + + const hours = Math.ceil(totalMinutes / 60); + let cost = hours * 3; + + if (overnight) { + cost += 10; + } + + if (cost < 5) { + cost = 5; + } + + return `$${cost}`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322d7.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322d7.md new file mode 100644 index 0000000000000000000000000000000000000000..fe10a203dbe4af16aab28743ee124811d7b023c4 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322d7.md @@ -0,0 +1,89 @@ +--- +id: 699c8e045ee7cb94ed2322d7 +title: "Challenge 216: Pi Day" +challengeType: 28 +dashedName: challenge-216 +--- + +# --description-- + +Happy pi (π) day! + +Given an integer (`n`), where `n` is between 1 and 1000 (inclusive), return the `n`th decimal of π. + +- Make sure to return a number not a string. + +π with its first five decimals is 3.14159. So given `5` for example, return `9`, the fifth decimal. + +You may have to find the first 1000 decimals of π somewhere. + +# --hints-- + +`getPiDecimal(5)` should return `9`. + +```js +assert.strictEqual(getPiDecimal(5), 9); +``` + +`getPiDecimal(10)` should return `5`. + +```js +assert.strictEqual(getPiDecimal(10), 5); +``` + +`getPiDecimal(22)` should return `6`. + +```js +assert.strictEqual(getPiDecimal(22), 6); +``` + +`getPiDecimal(39)` should return `7`. + +```js +assert.strictEqual(getPiDecimal(39), 7); +``` + +`getPiDecimal(76)` should return `2`. + +```js +assert.strictEqual(getPiDecimal(76), 2); +``` + +`getPiDecimal(384)` should return `4`. + +```js +assert.strictEqual(getPiDecimal(384), 4); +``` + +`getPiDecimal(601)` should return `0`. + +```js +assert.strictEqual(getPiDecimal(601), 0); +``` + +`getPiDecimal(1000)` should return `9`. + +```js +assert.strictEqual(getPiDecimal(1000), 9); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getPiDecimal(n) { + + return n; +} +``` + +# --solutions-- + +```js +function getPiDecimal(n) { + const pi = "31415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989" + + return Number(pi[n]); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322d8.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322d8.md new file mode 100644 index 0000000000000000000000000000000000000000..61118b838c48b942b7449bda6cdfac4c47c440d6 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322d8.md @@ -0,0 +1,98 @@ +--- +id: 699c8e045ee7cb94ed2322d8 +title: "Challenge 217: Captured Chess Pieces" +challengeType: 28 +dashedName: challenge-217 +--- + +# --description-- + +Given an array of strings representing chess pieces you still have on the board, calculate the value of the pieces your opponent has captured. + +In chess, you start with 16 pieces: + +| Piece | Abbreviation | Quantity | Value | +| ------ | -------------- | -------- | ----- | +| Pawn | `"P"` | 8 | 1 | +| Rook | `"R"` | 2 | 5 | +| Knight | `"N"` | 2 | 3 | +| Bishop | `"B"` | 2 | 3 | +| Queen | `"Q"` | 1 | 9 | +| King | `"K"` | 1 | 0 | + +- The given array will only contain the abbreviations above. +- Any of the 16 pieces not included in the given array have been captured. +- Return the total value of all captured pieces, unless... +- If the King has been captured, return `"Checkmate"`. + +# --hints-- + +`getCapturedValue(["P", "P", "P", "P", "P", "P", "R", "R", "N", "B", "Q", "K"])` should return `8`. + +```js +assert.equal(getCapturedValue(["P", "P", "P", "P", "P", "P", "R", "R", "N", "B", "Q", "K"]), 8); +``` + +`getCapturedValue(["P", "P", "P", "P", "P", "R", "B", "K"])` should return `26`. + +```js +assert.equal(getCapturedValue(["P", "P", "P", "P", "P", "R", "B", "K"]), 26); +``` + +`getCapturedValue(["K", "P", "P", "N", "P", "P", "R", "P", "B", "P", "N", "B"])` should return `16`. + +```js +assert.equal(getCapturedValue(["K", "P", "P", "N", "P", "P", "R", "P", "B", "P", "N", "B"]), 16); +``` + +`getCapturedValue(["P", "Q", "N", "P", "P", "B", "K", "P", "R", "R", "P", "P", "B", "P"])` should return `4`. + +```js +assert.equal(getCapturedValue(["P", "Q", "N", "P", "P", "B", "K", "P", "R", "R", "P", "P", "B", "P"]), 4); +``` + +`getCapturedValue(["P", "K"])` should return `38`. + +```js +assert.equal(getCapturedValue(["P", "K"]), 38); +``` + +`getCapturedValue(["N", "P", "P", "B", "K", "P", "Q", "N", "P", "P", "R", "R", "P", "P", "P", "B"])` should return `0`. + +```js +assert.equal(getCapturedValue(["N", "P", "P", "B", "K", "P", "Q", "N", "P", "P", "R", "R", "P", "P", "P", "B"]), 0); +``` + +`getCapturedValue(["N", "P", "P", "B", "P", "R", "Q", "P", "P", "P", "B"])` should return `"Checkmate"`. + +```js +assert.equal(getCapturedValue(["N", "P", "P", "B", "P", "R", "Q", "P", "P", "P", "B"]), "Checkmate"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getCapturedValue(pieces) { + + return pieces; +} +``` + +# --solutions-- + +```js +function getCapturedValue(pieces) { + if (!pieces.includes("K")) return "Checkmate"; + + const values = { P:1, R:5, N:3, B:3, Q:9, K:0 }; + let remaining = "PPPPPPPPRRNNBBQK"; + + for (const p of pieces) { + remaining = remaining.replace(p, ""); + } + + return [...remaining].reduce((sum, p) => sum + values[p], 0); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322d9.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322d9.md new file mode 100644 index 0000000000000000000000000000000000000000..f9417c3f9e2b781bbf8e6da9a73498eeb4f361f4 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322d9.md @@ -0,0 +1,67 @@ +--- +id: 699c8e045ee7cb94ed2322d9 +title: "Challenge 218: Evenly Divisible" +challengeType: 28 +dashedName: challenge-218 +--- + +# --description-- + +Given two integers, determine if you can evenly divide the first one by the second one. + +# --hints-- + +`isEvenlyDivisible(4, 2)` should return `true`. + +```js +assert.isTrue(isEvenlyDivisible(4, 2)); +``` + +`isEvenlyDivisible(7, 3)` should return `false`. + +```js +assert.isFalse(isEvenlyDivisible(7, 3)); +``` + +`isEvenlyDivisible(5, 10)` should return `false`. + +```js +assert.isFalse(isEvenlyDivisible(5, 10)); +``` + +`isEvenlyDivisible(48, 6)` should return `true`. + +```js +assert.isTrue(isEvenlyDivisible(48, 6)); +``` + +`isEvenlyDivisible(3186, 9)` should return `true`. + +```js +assert.isTrue(isEvenlyDivisible(3186, 9)); +``` + +`isEvenlyDivisible(4192, 11)` should return `false`. + +```js +assert.isFalse(isEvenlyDivisible(4192, 11)); +``` + +# --seed-- + +## --seed-contents-- + +```js +function isEvenlyDivisible(a, b) { + + return a; +} +``` + +# --solutions-- + +```js +function isEvenlyDivisible(a, b) { + return a % b === 0; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322da.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322da.md new file mode 100644 index 0000000000000000000000000000000000000000..a64177e161a4143e3f1b6da218bb041c7468d746 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322da.md @@ -0,0 +1,115 @@ +--- +id: 699c8e045ee7cb94ed2322da +title: "Challenge 219: Anniversary Milestones" +challengeType: 28 +dashedName: challenge-219 +--- + +# --description-- + +Given an integer representing the number of years a couple has been married, return their most recent anniversary milestone according to this chart: + +| Years Married | Milestone | +| ------------- | ------------ | +| 1 | `"Paper"` | +| 5 | `"Wood"` | +| 10 | `"Tin"` | +| 25 | `"Silver"` | +| 40 | `"Ruby"` | +| 50 | `"Gold"` | +| 60 | `"Diamond"` | +| 70 | `"Platinum"` | + +- If they haven't reached the first milestone, return `"Newlyweds"`. + +# --hints-- + +`getMilestone(0)` should return `"Newlyweds"`. + +```js +assert.equal(getMilestone(0), "Newlyweds"); +``` + +`getMilestone(1)` should return `"Paper"`. + +```js +assert.equal(getMilestone(1), "Paper"); +``` + +`getMilestone(8)` should return `"Wood"`. + +```js +assert.equal(getMilestone(8), "Wood"); +``` + +`getMilestone(10)` should return `"Tin"`. + +```js +assert.equal(getMilestone(10), "Tin"); +``` + +`getMilestone(26)` should return `"Silver"`. + +```js +assert.equal(getMilestone(26), "Silver"); +``` + +`getMilestone(45)` should return `"Ruby"`. + +```js +assert.equal(getMilestone(45), "Ruby"); +``` + +`getMilestone(50)` should return `"Gold"`. + +```js +assert.equal(getMilestone(50), "Gold"); +``` + +`getMilestone(64)` should return `"Diamond"`. + +```js +assert.equal(getMilestone(64), "Diamond"); +``` + +`getMilestone(71)` should return `"Platinum"`. + +```js +assert.equal(getMilestone(71), "Platinum"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getMilestone(years) { + + return years; +} +``` + +# --solutions-- + +```js +function getMilestone(years) { + if (years < 1) return "Newlyweds"; + + const milestones = [ + [1, "Paper"], + [5, "Wood"], + [10, "Tin"], + [25, "Silver"], + [40, "Ruby"], + [50, "Gold"], + [60, "Diamond"], + [70, "Platinum"] + ]; + + for (let i = milestones.length - 1; i >= 0; i--) { + if (years >= milestones[i][0]) { + return milestones[i][1]; + } + } +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322db.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322db.md new file mode 100644 index 0000000000000000000000000000000000000000..a8d059c2ea09b2a7b7e01d04dcbc0951e9f9c207 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322db.md @@ -0,0 +1,59 @@ +--- +id: 699c8e045ee7cb94ed2322db +title: "Challenge 220: Largest Number" +challengeType: 28 +dashedName: challenge-220 +--- + +# --description-- + +Given a string of numbers separated by various punctuation, return the largest number. + +- The given string will only contain numbers and separators. +- Separators can be commas (`","`), exclamation points (`"!"`), question marks (`"?"`), colons (`":"`), or semi-colons (`";"`). + +# --hints-- + +`largestNumber("1,2")` should return `2`. + +```js +assert.equal(largestNumber("1,2"), 2); +``` + +`largestNumber("4;15:60,26?52!0")` should return `60`. + +```js +assert.equal(largestNumber("4;15:60,26?52!0"), 60); +``` + +`largestNumber("-402,-1032!-569:-947;-633?-800!-1012;-402,-723?-8102!-3011")` should return `-402`. + +```js +assert.equal(largestNumber("-402,-1032!-569:-947;-633?-800!-1012;-402,-723?-8102!-3011"), -402); +``` + +`largestNumber("12;-50,99.9,49.1!-10.1?88?16")` should return `99.9`. + +```js +assert.equal(largestNumber("12;-50,99.9,49.1!-10.1?88?16"), 99.9); +``` + +# --seed-- + +## --seed-contents-- + +```js +function largestNumber(str) { + + return str; +} +``` + +# --solutions-- + +```js +function largestNumber(str) { + const numbers = str.split(/[,!?:;]/).map(Number); + return Math.max(...numbers); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322dc.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322dc.md new file mode 100644 index 0000000000000000000000000000000000000000..d55d7ee382ddc053770534d3e569bd579c580f0b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322dc.md @@ -0,0 +1,86 @@ +--- +id: 699c8e045ee7cb94ed2322dc +title: "Challenge 221: Inverted Matrix" +challengeType: 28 +dashedName: challenge-221 +--- + +# --description-- + +Given a matrix (an array of arrays) filled with two distinct values, return a new matrix where all occurrences of one value are swapped with the other. + +For example, given: + +```js +[ + ["a", "b"], + ["a", "a"] +] +``` + +Return: + +```js +[ + ["b", "a"], + ["b", "b"] +] +``` + +# --hints-- + +`invertMatrix([["a", "b"], ["a", "a"]])` should return `[["b", "a"], ["b", "b"]]`. + +```js +assert.deepEqual(invertMatrix([["a", "b"], ["a", "a"]]), [["b", "a"], ["b", "b"]]); +``` + +`invertMatrix([[1, 0, 1], [1, 1, 1], [0, 1, 0]])` should return `[[0, 1, 0], [0, 0, 0], [1, 0, 1]]`. + +```js +assert.deepEqual(invertMatrix([[1, 0, 1], [1, 1, 1], [0, 1, 0]]), [[0, 1, 0], [0, 0, 0], [1, 0, 1]]); +``` + +`invertMatrix([["apple", "banana", "banana", "apple"], ["banana", "apple", "apple", "banana"], ["banana", "banana", "banana", "apple"]])` should return `[["banana", "apple", "apple", "banana"], ["apple", "banana", "banana", "apple"], ["apple", "apple", "apple", "banana"]]`. + +```js +assert.deepEqual(invertMatrix([["apple", "banana", "banana", "apple"], ["banana", "apple", "apple", "banana"], ["banana", "banana", "banana", "apple"]]), [["banana", "apple", "apple", "banana"], ["apple", "banana", "banana", "apple"], ["apple", "apple", "apple", "banana"]]); +``` + +`invertMatrix([[6, 7, 7, 7, 6], [7, 6, 7, 6, 7], [7, 7, 6, 7, 7], [7, 6, 7, 6, 7], [6, 7, 7, 7, 6]])` should return `[[7, 6, 6, 6, 7], [6, 7, 6, 7, 6], [6, 6, 7, 6, 6], [6, 7, 6, 7, 6], [7, 6, 6, 6, 7]]`. + +```js +assert.deepEqual(invertMatrix([[6, 7, 7, 7, 6], [7, 6, 7, 6, 7], [7, 7, 6, 7, 7], [7, 6, 7, 6, 7], [6, 7, 7, 7, 6]]), [[7, 6, 6, 6, 7], [6, 7, 6, 7, 6], [6, 6, 7, 6, 6], [6, 7, 6, 7, 6], [7, 6, 6, 6, 7]]); +``` + +`invertMatrix([[1.2, 2.1, 2.1, 2.1], [2.1, 1.2, 2.1, 1.2], [1.2, 1.2, 2.1, 2.1]])` should return `[[2.1, 1.2, 1.2, 1.2], [1.2, 2.1, 1.2, 2.1], [2.1, 2.1, 1.2, 1.2]]`. + +```js +assert.deepEqual(invertMatrix([[1.2, 2.1, 2.1, 2.1], [2.1, 1.2, 2.1, 1.2], [1.2, 1.2, 2.1, 2.1]]), [[2.1, 1.2, 1.2, 1.2], [1.2, 2.1, 1.2, 2.1], [2.1, 2.1, 1.2, 1.2]]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function invertMatrix(matrix) { + + return matrix; +} +``` + +# --solutions-- + +```js +function invertMatrix(matrix) { + if (matrix.length === 0) return []; + + const values = [...new Set(matrix.flat())]; + const [val1, val2] = values; + + return matrix.map(row => + row.map(cell => (cell === val1 ? val2 : val1)) + ); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322dd.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322dd.md new file mode 100644 index 0000000000000000000000000000000000000000..69716348ed70a34a900630088d7c9b1b412237b9 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/699c8e045ee7cb94ed2322dd.md @@ -0,0 +1,115 @@ +--- +id: 699c8e045ee7cb94ed2322dd +title: "Challenge 222: Equinox Shadows" +challengeType: 28 +dashedName: challenge-222 +--- + +# --description-- + +Today is the equinox, when the sun is directly above the equator and perfectly overhead at noon. Given a time, determine the shadow cast by a 4-foot vertical pole. + +- The time will be a string in `"HH:MM"` 24-hour format (for example, `"15:00"` is 3pm). +- You will only be given a time in 30 minute increments. + +Rules: + +- The sun rises at 6am directly `"east"`, and sets at 6pm directly `"west"`. +- A shadow always points opposite the sun. +- The shadow's length (in feet) is the number of hours away from noon, cubed. +- There is no shadow before sunrise (before 6am), after sunset (6pm or later), or at noon. + +Return: + +- If a shadow exists, return `"(length)ft (direction)"`. For example, `"8ft west"`. +- Otherwise, return `"No shadow"`. + +For example, given `"10:00"`, return `"8ft west"` because 10am is 2 hours from noon, so 23 = 8 feet, and the shadow points west because the sun is in the east at 10am. + +# --hints-- + +`getShadow("10:00")` should return `"8ft west"`. + +```js +assert.equal(getShadow("10:00"), "8ft west"); +``` + +`getShadow("15:00")` should return `"27ft east"`. + +```js +assert.equal(getShadow("15:00"), "27ft east"); +``` + +`getShadow("12:00")` should return `"No shadow"`. + +```js +assert.equal(getShadow("12:00"), "No shadow"); +``` + +`getShadow("17:30")` should return `"166.375ft east"`. + +```js +assert.equal(getShadow("17:30"), "166.375ft east"); +``` + +`getShadow("05:00")` should return `"No shadow"`. + +```js +assert.equal(getShadow("05:00"), "No shadow"); +``` + +`getShadow("06:00")` should return `"216ft west"`. + +```js +assert.equal(getShadow("06:00"), "216ft west"); +``` + +`getShadow("18:00")` should return `"No shadow"`. + +```js +assert.equal(getShadow("18:00"), "No shadow"); +``` + +`getShadow("07:30")` should return `"91.125ft west"`. + +```js +assert.equal(getShadow("07:30"), "91.125ft west"); +``` + +`getShadow("00:00")` should return `"No shadow"`. + +```js +assert.equal(getShadow("00:00"), "No shadow"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getShadow(time) { + + return time; +} +``` + +# --solutions-- + +```js +function getShadow(time) { + const [hourStr, minuteStr] = time.split(":"); + const hours = Number(hourStr); + const minutes = Number(minuteStr); + const timeInHours = hours + minutes / 60; + + if (timeInHours < 6 || timeInHours >= 18 || timeInHours === 12) { + return "No shadow"; + } + + const hoursFromNoon = Math.abs(12 - timeInHours); + const length = Math.pow(hoursFromNoon, 3); + const direction = timeInHours < 12 ? "west" : "east"; + + return `${length}ft ${direction}`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69a890af247de743333bd4cc.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69a890af247de743333bd4cc.md new file mode 100644 index 0000000000000000000000000000000000000000..7b9d90ec19a38f88f4830f524899d287d60237d6 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69a890af247de743333bd4cc.md @@ -0,0 +1,145 @@ +--- +id: 69a890af247de743333bd4cc +title: "Challenge 223: QR Decoder" +challengeType: 28 +dashedName: challenge-223 +--- + +# --description-- + +Given a 6x6 matrix (array of strings), representing a QR code, return the string of binary data in the code. + +- The QR code may be given in any rotation of 90 degree increments. +- A correctly oriented code has a 2x2 group of `1`'s (orientation markers) in the bottom-left, top-left, and top-right corners. +- The three 2x2 orientation markers are not part of the binary data. +- The binary data is read left-to-right, top-to-bottom (like a book) when the QR code is correctly oriented. +- A code will always have exactly one valid orientation. + +For example, given: + +```js +[ + "110011", + "110011", + "000000", + "000000", + "110000", + "110001" +] +``` + +or given the same code with a different orientation: + +```js +[ + "110011", + "110011", + "000000", + "000000", + "000011", + "100011" +] +``` + +Return `"000000000000000000000001"`, all the binary data excluding the three 2x2 orientation markers. + +# --hints-- + +`decodeQr(["110011", "110011", "000000", "000000", "110000", "110001"])` should return `"000000000000000000000001"`. + +```js +assert.equal(decodeQr(["110011", "110011", "000000", "000000", "110000", "110001"]), "000000000000000000000001"); +``` + +`decodeQr(["100011", "000011", "000000", "000000", "110011", "110011"])` should return `"000000000000000000000001"`. + +```js +assert.equal(decodeQr(["100011", "000011", "000000", "000000", "110011", "110011"]), "000000000000000000000001"); +``` + +`decodeQr(["110011", "111111", "010000", "110000", "110011", "110100"])` should return `"001101000011000000110100"`. + +```js +assert.equal(decodeQr(["110011", "111111", "010000", "110000", "110011", "110100"]), "001101000011000000110100"); +``` + +`decodeQr(["011011", "101011", "101000", "100010", "110011", "111011"])` should return `"010001000100010101010110"`. + +```js +assert.equal(decodeQr(["011011", "101011", "101000", "100010", "110011", "111011"]), "010001000100010101010110"); +``` + +`decodeQr(["111100", "110001", "100011", "001101", "110011", "110011"])` should return `"010000100100100101001110"`. + +```js +assert.equal(decodeQr(["111100", "110001", "100011", "001101", "110011", "110011"]), "010000100100100101001110"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function decodeQr(qrCode) { + + return qrCode; +} +``` + +# --solutions-- + +```js +function isOriented(code) { + const markerIndices = [ + [0, 0], + [0, 1], + [0, 4], + [0, 5], + [1, 0], + [1, 1], + [1, 4], + [1, 5], + [4, 0], + [4, 1], + [5, 0], + [5, 1] + ]; + + for(const [row, col] of markerIndices) { + if (code[row][col] !== '1') return false; + } + + return true; +} + +function rotate(code) { + const newCode = ['', '', '', '', '', '']; + for (let i = 0; i < 6; i++) { + for (let j = 5; j >= 0; j--) { + newCode[i] += code[j][i]; + } + } + return newCode; +} + +function getData(code) { + let data = ''; + data += code[0].substring(2, 4) + data += code[1].substring(2, 4) + data += code[2] + data += code[3] + data += code[4].substring(2) + data += code[5].substring(2) + return data; +} + +function decodeQr(qrCode) { + let code = [...qrCode]; + + while(!isOriented(code)) { + code = rotate(code); + } + + return getData(code); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69a890af247de743333bd4cd.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69a890af247de743333bd4cd.md new file mode 100644 index 0000000000000000000000000000000000000000..d4f19f1f4c7290307272d66ea3ade10f6e94aec7 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69a890af247de743333bd4cd.md @@ -0,0 +1,99 @@ +--- +id: 69a890af247de743333bd4cd +title: "Challenge 224: Coffee Roast Detector" +challengeType: 28 +dashedName: challenge-224 +--- + +# --description-- + +Given a string representing the beans used to make a cup of coffee, determine the roast of the cup. + +- The given string will contain the following characters, each representing a type of bean: + + - An apostrophe (`'`) is a light roast bean worth 1 point each. + - A dash (`-`) is a medium roast bean worth 2 points each. + - A period (`.`) is a dark roast bean worth 3 points each. + +- The roast level is determined by the average of all the beans. + +Return: + +- `"Light"` if the average is less than 1.75. +- `"Medium"` if the average is 1.75 to 2.5. +- `"Dark"` if the average is greater than 2.5. + +# --hints-- + +`detectRoast("''-''''''-'-''--''''")` should return `"Light"`. + +```js +assert.equal(detectRoast("''-''''''-'-''--''''"), "Light"); +``` + +`detectRoast(".'-''-''..'''.-.-''-")` should return `"Medium"`. + +```js +assert.equal(detectRoast(".'-''-''..'''.-.-''-"), "Medium"); +``` + +`detectRoast("--.''--'-''.--..-.--")` should return `"Medium"`. + +```js +assert.equal(detectRoast("--.''--'-''.--..-.--"), "Medium"); +``` + +`detectRoast("-...'-......-..-...-")` should return `"Dark"`. + +```js +assert.equal(detectRoast("-...'-......-..-...-"), "Dark"); +``` + +`detectRoast(".--.-..-......----.'")` should return `"Medium"`. + +```js +assert.equal(detectRoast(".--.-..-......----.'"), "Medium"); +``` + +`detectRoast("..-..-..-..-....-.-.")` should return `"Dark"`. + +```js +assert.equal(detectRoast("..-..-..-..-....-.-."), "Dark"); +``` + +`detectRoast("-'-''''''..-'.''-'.'")` should return `"Light"`. + +```js +assert.equal(detectRoast("-'-''''''..-'.''-'.'"), "Light"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function detectRoast(beans) { + + return beans; +} +``` + +# --solutions-- + +```js +function detectRoast(beans) { + let total = 0; + + for (const bean of beans) { + if (bean === "'") total += 1; + else if (bean === "-") total += 2; + else if (bean === ".") total += 3; + } + + const avg = total / beans.length; + + if (avg < 1.75) return "Light"; + if (avg <= 2.5) return "Medium"; + return "Dark"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69a890af247de743333bd4ce.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69a890af247de743333bd4ce.md new file mode 100644 index 0000000000000000000000000000000000000000..c4f11150f7654078f304d67e39e5ebda36297be5 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69a890af247de743333bd4ce.md @@ -0,0 +1,74 @@ +--- +id: 69a890af247de743333bd4ce +title: "Challenge 225: No Consecutive Repeats" +challengeType: 28 +dashedName: challenge-225 +--- + +# --description-- + +Given a string, determine if it has no repeating characters. + +- A string has no repeats if it does not have the same character two or more times in a row. + +# --hints-- + +`hasNoRepeats("hi world")` should return `true`. + +```js +assert.isTrue(hasNoRepeats("hi world")); +``` + +`hasNoRepeats("hello world")` should return `false`. + +```js +assert.isFalse(hasNoRepeats("hello world")); +``` + +`hasNoRepeats("abcdefghijklmnopqrstuvwxyz")` should return `true`. + +```js +assert.isTrue(hasNoRepeats("abcdefghijklmnopqrstuvwxyz")); +``` + +`hasNoRepeats("freeCodeCamp")` should return `false`. + +```js +assert.isFalse(hasNoRepeats("freeCodeCamp")); +``` + +`hasNoRepeats("The quick brown fox jumped over the lazy dog.")` should return `true`. + +```js +assert.isTrue(hasNoRepeats("The quick brown fox jumped over the lazy dog.")); +``` + +`hasNoRepeats("Mississippi")` should return `false`. + +```js +assert.isFalse(hasNoRepeats("Mississippi")); +``` + +# --seed-- + +## --seed-contents-- + +```js +function hasNoRepeats(str) { + + return str; +} +``` + +# --solutions-- + +```js +function hasNoRepeats(str) { + for (let i = 1; i < str.length; i++) { + if (str[i] === str[i - 1]) { + return false; + } + } + return true; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69a890af247de743333bd4cf.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69a890af247de743333bd4cf.md new file mode 100644 index 0000000000000000000000000000000000000000..1afd853972d4c36c61ac5de176df39b57bf33a35 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69a890af247de743333bd4cf.md @@ -0,0 +1,69 @@ +--- +id: 69a890af247de743333bd4cf +title: "Challenge 226: Passing Exam Count" +challengeType: 28 +dashedName: challenge-226 +--- + +# --description-- + +Given an array of student exam scores and the score needed to pass it, return the number of students that passed the exam. + +# --hints-- + +`passingCount([90, 85, 75, 60, 50], 70)` should return `3`. + +```js +assert.equal(passingCount([90, 85, 75, 60, 50], 70), 3); +``` + +`passingCount([100, 80, 75, 88, 72, 74, 79, 71, 60, 92], 75)` should return `6`. + +```js +assert.equal(passingCount([100, 80, 75, 88, 72, 74, 79, 71, 60, 92], 75), 6); +``` + +`passingCount([79, 60, 88, 72, 74, 59, 75, 71, 80, 92], 60)` should return `9`. + +```js +assert.equal(passingCount([79, 60, 88, 72, 74, 59, 75, 71, 80, 92], 60), 9); +``` + +`passingCount([76, 79, 80, 70, 71, 65, 79, 78, 59, 72], 85)` should return `0`. + +```js +assert.equal(passingCount([76, 79, 80, 70, 71, 65, 79, 78, 59, 72], 85), 0); +``` + +`passingCount([84, 65, 98, 53, 58, 71, 91, 80, 92, 70, 73, 83, 86, 69, 84, 77, 72, 58, 69, 75, 66, 68, 72, 96, 90, 63, 88, 63, 80, 67], 60)` should return `27`. + +```js +assert.equal(passingCount([84, 65, 98, 53, 58, 71, 91, 80, 92, 70, 73, 83, 86, 69, 84, 77, 72, 58, 69, 75, 66, 68, 72, 96, 90, 63, 88, 63, 80, 67], 60), 27); +``` + +# --seed-- + +## --seed-contents-- + +```js +function passingCount(scores, passingScore) { + + return scores; +} +``` + +# --solutions-- + +```js +function passingCount(scores, passingScore) { + let count = 0; + + for (const score of scores) { + if (score >= passingScore) { + count++; + } + } + + return count; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69a890af247de743333bd4d0.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69a890af247de743333bd4d0.md new file mode 100644 index 0000000000000000000000000000000000000000..e47129d746f6244782f07d70abc469adeb2e5c4b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69a890af247de743333bd4d0.md @@ -0,0 +1,69 @@ +--- +id: 69a890af247de743333bd4d0 +title: "Challenge 227: Cooldown Time" +challengeType: 28 +dashedName: challenge-227 +--- + +# --description-- + +Given two timestamps, the first representing when a user finished an exam, and the second representing the current time, determine whether the user can take an exam again. + +- Both timestamps will be given the format: `"YYYY-MM-DDTHH:MM:SS"`, for example `"2026-03-25T14:00:00"`. Note that the time is 24-hour clock. +- A user must wait at least 48 hours before retaking an exam. + +# --hints-- + +`canRetake("2026-03-23T08:00:00", "2026-03-25T14:00:00")` should return `true`. + +```js +assert.isTrue(canRetake("2026-03-23T08:00:00", "2026-03-25T14:00:00")); +``` + +`canRetake("2026-03-24T14:00:00", "2026-03-25T10:00:00")` should return `false`. + +```js +assert.isFalse(canRetake("2026-03-24T14:00:00", "2026-03-25T10:00:00")); +``` + +`canRetake("2026-03-23T09:25:00", "2026-03-25T09:25:00")` should return `true`. + +```js +assert.isTrue(canRetake("2026-03-23T09:25:00", "2026-03-25T09:25:00")); +``` + +`canRetake("2026-03-23T11:50:00", "2026-03-25T11:49:59")` should return `false`. + +```js +assert.isFalse(canRetake("2026-03-23T11:50:00", "2026-03-25T11:49:59")); +``` + +# --seed-- + +## --seed-contents-- + +```js +function canRetake(finishTime, currentTime) { + + return finishTime; +} +``` + +# --solutions-- + +```js +function canRetake(finishTime, currentTime) { + function parse(ts) { + const parts = ts.split(/[-T:]/).map(Number); + const [y, m, d, h, min, s] = parts; + return Date.UTC(y, m - 1, d, h, min, s); + } + + const finishMs = parse(finishTime); + const currentMs = parse(currentTime); + + const cooldown = 48 * 60 * 60 * 1000; + + return currentMs - finishMs >= cooldown; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69a890af247de743333bd4d1.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69a890af247de743333bd4d1.md new file mode 100644 index 0000000000000000000000000000000000000000..9e484957987487c46c38182468c62a69f47a202e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69a890af247de743333bd4d1.md @@ -0,0 +1,118 @@ +--- +id: 69a890af247de743333bd4d1 +title: "Challenge 228: Movie Night" +challengeType: 28 +dashedName: challenge-228 +--- + +# --description-- + +Given a string for the day of the week, another string for a showtime, and an integer number of tickets, return the total cost of the movie tickets for that showing. + +The given day will be one of: + +- `"Monday"` +- `"Tuesday"` +- `"Wednesday"` +- `"Thursday"` +- `"Friday"` +- `"Saturday"` +- `"Sunday"` + +The showtime will be given in the format `"H:MMam"` or `"H:MMpm"`. For example `"10:00am"` or `"10:00pm"`. + +Return the total cost in the format `"$D.CC"` using these rules: + +- Weekend (Friday - Sunday): $12.00 per ticket. +- Weekday (Monday - Thursday): $10.00 per ticket. +- Matinee (before 5:00pm): subtract $2.00 per ticket (except on Tuesdays). +- Tuesdays: all tickets are $5.00 each. + +# --hints-- + +`getMovieNightCost("Saturday", "10:00pm", 1)` should return `"$12.00"`. + +```js +assert.equal(getMovieNightCost("Saturday", "10:00pm", 1), "$12.00"); +``` + +`getMovieNightCost("Sunday", "10:00am", 1)` should return `"$10.00"`. + +```js +assert.equal(getMovieNightCost("Sunday", "10:00am", 1), "$10.00"); +``` + +`getMovieNightCost("Tuesday", "7:20pm", 2)` should return `"$10.00"`. + +```js +assert.equal(getMovieNightCost("Tuesday", "7:20pm", 2), "$10.00"); +``` + +`getMovieNightCost("Wednesday", "5:40pm", 3)` should return `"$30.00"`. + +```js +assert.equal(getMovieNightCost("Wednesday", "5:40pm", 3), "$30.00"); +``` + +`getMovieNightCost("Monday", "11:50am", 4)` should return `"$32.00"`. + +```js +assert.equal(getMovieNightCost("Monday", "11:50am", 4), "$32.00"); +``` + +`getMovieNightCost("Friday", "4:30pm", 5)` should return `"$50.00"`. + +```js +assert.equal(getMovieNightCost("Friday", "4:30pm", 5), "$50.00"); +``` + +`getMovieNightCost("Tuesday", "11:30am", 1)` should return `"$5.00"`. + +```js +assert.equal(getMovieNightCost("Tuesday", "11:30am", 1), "$5.00"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getMovieNightCost(day, showtime, numberOfTickets) { + + return day; +} +``` + +# --solutions-- + +```js +function getMovieNightCost(day, showtime, numberOfTickets) { + let price; + + if (day === "Tuesday") { + price = 5; + } else { + if (["Friday", "Saturday", "Sunday"].includes(day)) { + price = 12; + } else { + price = 10; + } + + const hour = parseInt(showtime.split(":")[0]); + const period = showtime.slice(-2); + + let hour24 = hour; + + if (period === "pm" && hour !== 12) hour24 += 12; + if (period === "am" && hour === 12) hour24 = 0; + + if (hour24 < 17) { + price -= 2; + } + } + + const total = price * numberOfTickets; + + return `$${total.toFixed(2)}`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69a890af247de743333bd4d2.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69a890af247de743333bd4d2.md new file mode 100644 index 0000000000000000000000000000000000000000..5bdfd3e55648c5f17244bb07aa99c6cba31b3364 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69a890af247de743333bd4d2.md @@ -0,0 +1,119 @@ +--- +id: 69a890af247de743333bd4d2 +title: "Challenge 229: Truncate the Text 2" +challengeType: 28 +dashedName: challenge-229 +--- + +# --description-- + +Given a string, return a new string that is truncated so that the total width of the characters does not exceed 50 units. + +Each character has a specific width: + +| Letters | Width | +| - | - | +| `"ilI"` | 1 | +| `"fjrt"` | 2 | +| `"abcdeghkmnopqrstuvwxyzJL"` | 3 | +| `"ABCDEFGHKMNOPQRSTUVWXYZ"` | 4 | + +The table above includes all upper and lower case letters. Additionally: + +- Spaces (`" "`) have a width of 2 +- Periods (`"."`) have a width of 1 + +- If the given string is 50 units or less, return the string as-is, otherwise +- Truncate the string and add three periods at the end (`"..."`) so its total width, including the three periods, is as close as possible to 50 units without going over. + +# --hints-- + +`truncateText("The quick brown fox")` should return `"The quick brown f..."`. + +```js +assert.equal(truncateText("The quick brown fox"), "The quick brown f..."); +``` + +`truncateText("The silky smooth sloth")` should return `"The silky smooth s..."`. + +```js +assert.equal(truncateText("The silky smooth sloth"), "The silky smooth s..."); +``` + +`truncateText("THE LOUD BRIGHT BIRD")` should return `"THE LOUD BRIG..."`. + +```js +assert.equal(truncateText("THE LOUD BRIGHT BIRD"), "THE LOUD BRIG..."); +``` + +`truncateText("The fast striped zebra")` should return `"The fast striped z..."`. + +```js +assert.equal(truncateText("The fast striped zebra"), "The fast striped z..."); +``` + +`truncateText("The big black bear")` should return `"The big black bear"`. + +```js +assert.equal(truncateText("The big black bear"), "The big black bear"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function truncateText(str) { + + return str; +} +``` + +# --solutions-- + +```js +function truncateText(str) { + const MAX_WIDTH = 50; + const ELLIPSIS = "..."; + const ELLIPSIS_WIDTH = 3; + const TRUNCATE_LIMIT = MAX_WIDTH - ELLIPSIS_WIDTH; + + const charGroups = { + 'ilI.': 1, + 'fjrt ': 2, + 'abcdeghkmnopqrstuvwxyzJL': 3, + 'ABCDEFGHKMNOPQRSTUVWXYZ': 4 + }; + + function getCharWidth(char) { + for (const key in charGroups) { + if (key.includes(char)) return charGroups[key]; + } + return 3; + } + + function stringWidth(str) { + let totalWidth = 0; + for (const char of str) { + totalWidth += getCharWidth(char); + } + return totalWidth; + } + + if (stringWidth(str) <= MAX_WIDTH) return str; + + let result = ""; + let totalWidth = 0; + + for (const char of str) { + const charWidth = getCharWidth(char); + + if (totalWidth + charWidth > TRUNCATE_LIMIT) break; + + result += char; + totalWidth += charWidth; + } + + return result + ELLIPSIS; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b1028d6e265413d0198a29.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b1028d6e265413d0198a29.md new file mode 100644 index 0000000000000000000000000000000000000000..688e90b2d41552e49d1602fc01577ffb1f7b4bfa --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b1028d6e265413d0198a29.md @@ -0,0 +1,88 @@ +--- +id: 69b1028d6e265413d0198a29 +title: "Challenge 230: Pascal's Triangle Row" +challengeType: 28 +dashedName: challenge-230 +--- + +# --description-- + +Given an integer `n`, return the `n`th row of Pascal's triangle as an array. + +In Pascal's Triangle, each row begins and ends with 1, and each interior value is the sum of the two values directly above it. + +Here are the first 5 rows of the triangle: + +```js + 1 + 1 1 + 1 2 1 + 1 3 3 1 +1 4 6 4 1 +``` + +# --hints-- + +`pascalRow(5)` should return `[1, 4, 6, 4, 1]`. + +```js +assert.deepEqual(pascalRow(5), [1, 4, 6, 4, 1]); +``` + +`pascalRow(3)` should return `[1, 2, 1]`. + +```js +assert.deepEqual(pascalRow(3), [1, 2, 1]); +``` + +`pascalRow(1)` should return `[1]`. + +```js +assert.deepEqual(pascalRow(1), [1]); +``` + +`pascalRow(10)` should return `[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]`. + +```js +assert.deepEqual(pascalRow(10), [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]); +``` + +`pascalRow(15)` should return `[1, 14, 91, 364, 1001, 2002, 3003, 3432, 3003, 2002, 1001, 364, 91, 14, 1]`. + +```js +assert.deepEqual(pascalRow(15), [1, 14, 91, 364, 1001, 2002, 3003, 3432, 3003, 2002, 1001, 364, 91, 14, 1]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function pascalRow(n) { + + return n; +} +``` + +# --solutions-- + +```js +function pascalRow(n) { + if (n === 1) return [1]; + + let row = [1]; + + for (let i = 2; i <= n; i++) { + const next = [1]; + + for (let j = 1; j < row.length; j++) { + next.push(row[j - 1] + row[j]); + } + + next.push(1); + row = next; + } + + return row; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b1028d6e265413d0198a2a.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b1028d6e265413d0198a2a.md new file mode 100644 index 0000000000000000000000000000000000000000..4075334d501f3258aaa799541ab59363c54bdc0b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b1028d6e265413d0198a2a.md @@ -0,0 +1,96 @@ +--- +id: 69b1028d6e265413d0198a2a +title: "Challenge 231: ISBN-10 Validator" +challengeType: 28 +dashedName: challenge-231 +--- + +# --description-- + +Given a string, determine if it's a valid ISBN-10. + +An ISBN-10 consists of hyphens (`"-"`) and 10 other characters. After removing the hyphens (`"-"`): + +- The first 9 characters must be digits, and +- The final character may be a digit or the letter `"X"`, which represents the number 10. + +To validate it: + +- Multiply each digit (or value) by its position (multiply the first digit by 1, the second by 2, and so on). +- Add all the results together. +- If the total is divisible by 11, it's valid. + +# --hints-- + +`isValidIsbn10("0-306-40615-2")` should return `true`. + +```js +assert.isTrue(isValidIsbn10("0-306-40615-2")); +``` + +`isValidIsbn10("0-306-40615-1")` should return `false`. + +```js +assert.isFalse(isValidIsbn10("0-306-40615-1")); +``` + +`isValidIsbn10("0-8044-2957-X")` should return `true`. + +```js +assert.isTrue(isValidIsbn10("0-8044-2957-X")); +``` + +`isValidIsbn10("X-306-40615-2")` should return `false`. + +```js +assert.isFalse(isValidIsbn10("X-306-40615-2")); +``` + +`isValidIsbn10("0-6822-2589-4")` should return `true`. + +```js +assert.isTrue(isValidIsbn10("0-6822-2589-4")); +``` + +# --seed-- + +## --seed-contents-- + +```js +function isValidIsbn10(str) { + + return str; +} +``` + +# --solutions-- + +```js +function isValidIsbn10(str) { + const isbn = str.replace(/-/g, ""); + + if (isbn.length !== 10) return false; + + let sum = 0; + + for (let i = 0; i < 9; i++) { + const digit = Number(isbn[i]); + if (Number.isNaN(digit)) return false; + + sum += digit * (i + 1); + } + + const last = isbn[9]; + + if (last === "X") { + sum += 10 * 10; + } else { + const digit = Number(last); + if (Number.isNaN(digit)) return false; + + sum += digit * 10; + } + + return sum % 11 === 0; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b1028d6e265413d0198a2b.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b1028d6e265413d0198a2b.md new file mode 100644 index 0000000000000000000000000000000000000000..ed8e13994d39044c968f64c1b0149e60c674e71a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b1028d6e265413d0198a2b.md @@ -0,0 +1,80 @@ +--- +id: 69b1028d6e265413d0198a2b +title: "Challenge 232: Due Date" +challengeType: 28 +dashedName: challenge-232 +--- + +# --description-- + +Given a date string, return the date 9 months in the future. + +- The given and return strings have the format `"YYYY-MM-DD"`. +- If the month nine months into the future doesn't contain the original day number, return the last day of that month. + +# --hints-- + +`getDueDate("2025-03-30")` should return `"2025-12-30"`. + +```js +assert.equal(getDueDate("2025-03-30"), "2025-12-30"); +``` + +`getDueDate("2025-04-27")` should return `"2026-01-27"`. + +```js +assert.equal(getDueDate("2025-04-27"), "2026-01-27"); +``` + +`getDueDate("2025-05-29")` should return `"2026-02-28"`. + +```js +assert.equal(getDueDate("2025-05-29"), "2026-02-28"); +``` + +`getDueDate("2026-06-30")` should return `"2027-03-30"`. + +```js +assert.equal(getDueDate("2026-06-30"), "2027-03-30"); +``` + +`getDueDate("2026-10-11")` should return `"2027-07-11"`. + +```js +assert.equal(getDueDate("2026-10-11"), "2027-07-11"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getDueDate(dateStr) { + + return dateStr; +} +``` + +# --solutions-- + +```js +function getDueDate(dateStr) { + let [year, month, day] = dateStr.split("-").map(Number); + + month += 9; + + year += Math.floor((month - 1) / 12); + month = ((month - 1) % 12) + 1; + + const daysInMonth = new Date(year, month, 0).getDate(); + + if (day > daysInMonth) { + day = daysInMonth; + } + + const mm = String(month).padStart(2, "0"); + const dd = String(day).padStart(2, "0"); + + return `${year}-${mm}-${dd}`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b1028d6e265413d0198a2c.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b1028d6e265413d0198a2c.md new file mode 100644 index 0000000000000000000000000000000000000000..28b3a416a379d3b6256beefe7da5197fbb947291 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b1028d6e265413d0198a2c.md @@ -0,0 +1,92 @@ +--- +id: 69b1028d6e265413d0198a2c +title: "Challenge 233: Wake-Up Alarm" +challengeType: 28 +dashedName: challenge-233 +--- + +# --description-- + +Given a string representing the time you set your alarm and a string representing the time you actually woke up, determine if you woke up early, on time, or late. + +- Both times will be given in `"HH:MM"` 24-hour format. + +Return: + +- `"early"` if you woke up before your alarm time. +- `"on time"` if you woke up at your alarm time, or within the 10 minute snooze window after the alarm time. +- `"late"` if you woke up more than 10 minutes after your alarm time. + +Both times are on the same day. + +# --hints-- + +`alarmCheck("07:00", "06:45")` should return `"early"`. + +```js +assert.equal(alarmCheck("07:00", "06:45"), "early"); +``` + +`alarmCheck("06:30", "06:30")` should return `"on time"`. + +```js +assert.equal(alarmCheck("06:30", "06:30"), "on time"); +``` + +`alarmCheck("08:10", "08:15")` should return `"on time"`. + +```js +assert.equal(alarmCheck("08:10", "08:15"), "on time"); +``` + +`alarmCheck("09:30", "09:45")` should return `"late"`. + +```js +assert.equal(alarmCheck("09:30", "09:45"), "late"); +``` + +`alarmCheck("08:15", "08:25")` should return `"on time"`. + +```js +assert.equal(alarmCheck("08:15", "08:25"), "on time"); +``` + +`alarmCheck("05:45", "05:56")` should return `"late"`. + +```js +assert.equal(alarmCheck("05:45", "05:56"), "late"); +``` + +`alarmCheck("04:30", "04:00")` should return `"early"`. + +```js +assert.equal(alarmCheck("04:30", "04:00"), "early"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function alarmCheck(alarmTime, wakeTime) { + + return alarmTime; +} +``` + +# --solutions-- + +```js +function alarmCheck(alarmTime, wakeTime) { + const [alarmH, alarmM] = alarmTime.split(":").map(Number); + const [wakeH, wakeM] = wakeTime.split(":").map(Number); + + const alarmMinutes = alarmH * 60 + alarmM; + const wakeMinutes = wakeH * 60 + wakeM; + const diff = wakeMinutes - alarmMinutes; + + if (diff < 0) return "early"; + if (diff <= 10) return "on time"; + return "late"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b1028d6e265413d0198a2d.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b1028d6e265413d0198a2d.md new file mode 100644 index 0000000000000000000000000000000000000000..3a408f58edb40ca01d29a5bff9f42b3d08d0e978 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b1028d6e265413d0198a2d.md @@ -0,0 +1,103 @@ +--- +id: 69b1028d6e265413d0198a2d +title: "Challenge 234: Prank Number" +challengeType: 28 +dashedName: challenge-234 +--- + +# --description-- + +Given an array of numbers where all but one number follow a pattern, return a new array with the one number that doesn't follow the pattern fixed. + +The pattern will be one of: + +- The numbers increase from one to the next by a fixed amount (addition). +- The numbers decrease from one to the next by a fixed amount (subtraction). + +For example, given `[2, 4, 7, 8, 10]` return `[2, 4, 6, 8, 10]`. + +# --hints-- + +`fixPrankNumber([2, 4, 7, 8, 10])` should return `[2, 4, 6, 8, 10]`. + +```js +assert.deepEqual(fixPrankNumber([2, 4, 7, 8, 10]), [2, 4, 6, 8, 10]); +``` + +`fixPrankNumber([10, 10, 8, 7, 6])` should return `[10, 9, 8, 7, 6]`. + +```js +assert.deepEqual(fixPrankNumber([10, 10, 8, 7, 6]), [10, 9, 8, 7, 6]); +``` + +`fixPrankNumber([12, 24, 36, 48, 61, 72, 84, 96])` should return `[12, 24, 36, 48, 60, 72, 84, 96]`. + +```js +assert.deepEqual(fixPrankNumber([12, 24, 36, 48, 61, 72, 84, 96]), [12, 24, 36, 48, 60, 72, 84, 96]); +``` + +`fixPrankNumber([4, 1, -2, -5, -8, -5])` should return `[4, 1, -2, -5, -8, -11]`. + +```js +assert.deepEqual(fixPrankNumber([4, 1, -2, -5, -8, -5]), [4, 1, -2, -5, -8, -11]); +``` + +`fixPrankNumber([0, 100, 200, 300, 150, 500])` should return `[0, 100, 200, 300, 400, 500]`. + +```js +assert.deepEqual(fixPrankNumber([0, 100, 200, 300, 150, 500]), [0, 100, 200, 300, 400, 500]); +``` + +`fixPrankNumber([400, 425, 400, 375, 350, 325, 300])` should return `[450, 425, 400, 375, 350, 325, 300]`. + +```js +assert.deepEqual(fixPrankNumber([400, 425, 400, 375, 350, 325, 300]), [450, 425, 400, 375, 350, 325, 300]); +``` + +`fixPrankNumber([-5, 5, 10, 15, 20])` should return `[0, 5, 10, 15, 20]`. + +```js +assert.deepEqual(fixPrankNumber([-5, 5, 10, 15, 20]), [0, 5, 10, 15, 20]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function fixPrankNumber(arr) { + + return arr; +} +``` + +# --solutions-- + +```js +function fixPrankNumber(arr) { + const diffs = arr.slice(1).map((v, i) => v - arr[i]); + + let step = diffs[0]; + for (let i = 0; i < diffs.length - 1; i++) { + if (diffs[i] === diffs[i + 1]) { + step = diffs[i]; + break; + } + } + + const result = [...arr]; + + for (let i = 0; i < result.length - 1; i++) { + if (result[i + 1] - result[i] !== step) { + if (i === 0 && result[2] - result[1] === step) { + result[0] = result[1] - step; + } else { + result[i + 1] = result[i] + step; + } + break; + } + } + + return result; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b1028d6e265413d0198a2e.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b1028d6e265413d0198a2e.md new file mode 100644 index 0000000000000000000000000000000000000000..1efb86bc35a01861d2e7fd7c691c98c6da8b2d19 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b1028d6e265413d0198a2e.md @@ -0,0 +1,79 @@ +--- +id: 69b1028d6e265413d0198a2e +title: "Challenge 235: Capitalized Fibonacci" +challengeType: 28 +dashedName: challenge-235 +--- + +# --description-- + +Given a string, return a new string where each letter is capitalized if its index is a Fibonacci number, and lowercased otherwise. + +The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. The first 10 numbers in the sequence are `0`, `1`, `1`, `2`, `3`, `5`, `8`, `13`, `21`, `34`. + +- The first character is at index `0`. +- If the index of non-letter characters is a Fibonacci number, leave it unchanged. + +# --hints-- + +`capitalizeFibonacci("hello world")` should return `"HELLo woRld"`. + +```js +assert.equal(capitalizeFibonacci("hello world"), "HELLo woRld"); +``` + +`capitalizeFibonacci("HELLO WORLD")` should return `"HELLo woRld"`. + +```js +assert.equal(capitalizeFibonacci("HELLO WORLD"), "HELLo woRld"); +``` + +`capitalizeFibonacci("hello, world!")` should return `"HELLo, wOrld!"`. + +```js +assert.equal(capitalizeFibonacci("hello, world!"), "HELLo, wOrld!"); +``` + +`capitalizeFibonacci("The quick brown fox jumped over the lazy dog.")` should return `"THE qUicK broWn fox jUmped over thE lazy dog."`. + +```js +assert.equal(capitalizeFibonacci("The quick brown fox jumped over the lazy dog."), "THE qUicK broWn fox jUmped over thE lazy dog."); +``` + +`capitalizeFibonacci("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin pulvinar ex nibh, vel ullamcorper ligula egestas quis. Integer tincidunt fringilla accumsan. Integer et metus placerat, gravida felis at, pellentesque nisl.")` should return `"LOREm ipSum dOlor sit amet, consecTetur adipiscing elit. proin pulvinar ex nibh, vel ullaMcorper ligula egestas quis. integer tincidunt fringillA accumsan. integer et metus placerat, gravida felis at, pellentesque nisl."`. + +```js +assert.equal(capitalizeFibonacci("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin pulvinar ex nibh, vel ullamcorper ligula egestas quis. Integer tincidunt fringilla accumsan. Integer et metus placerat, gravida felis at, pellentesque nisl."), "LOREm ipSum dOlor sit amet, consecTetur adipiscing elit. proin pulvinar ex nibh, vel ullaMcorper ligula egestas quis. integer tincidunt fringillA accumsan. integer et metus placerat, gravida felis at, pellentesque nisl."); +``` + +# --seed-- + +## --seed-contents-- + +```js +function capitalizeFibonacci(str) { + + return str; +} +``` + +# --solutions-- + +```js +function capitalizeFibonacci(str) { + const fibs = new Set([0, 1]); + let a = 0, b = 1; + while (b < str.length) { + [a, b] = [b, a + b]; + fibs.add(b); + } + + return str + .split("") + .map((char, i) => { + if (!/[a-zA-Z]/.test(char)) return char; + return fibs.has(i) ? char.toUpperCase() : char.toLowerCase(); + }) + .join(""); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b1028d6e265413d0198a2f.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b1028d6e265413d0198a2f.md new file mode 100644 index 0000000000000000000000000000000000000000..54110a0529c5b54af60912e303b398c870bb78e1 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b1028d6e265413d0198a2f.md @@ -0,0 +1,90 @@ +--- +id: 69b1028d6e265413d0198a2f +title: "Challenge 236: Browser History" +challengeType: 28 +dashedName: challenge-236 +--- + +# --description-- + +Given an array of browser commands, return an array with two values: the history as an array of URLs, and the index of the current page. + +Valid commands are: + +- `"URL"` - Where URL is a web address (`"freecodecamp.org"` for example). Navigates to the given URL, adds it to the history at the next position, and discards any forward history. +- `"Back"` - moves to the previous page in history, or stays on the current page if there isn't one. +- `"Forward"` - moves to the next page in history, or stays on the current page if there isn't one. + +For example, given `["freecodecamp.org", "freecodecamp.org/learn", "Back"]`, return `[["freecodecamp.org", "freecodecamp.org/learn"], 0]`. + +# --hints-- + +`getBrowserHistory(["freecodecamp.org", "freecodecamp.org/learn", "Back"])` should return `[["freecodecamp.org", "freecodecamp.org/learn"], 0]`. + +```js +assert.deepEqual(getBrowserHistory(["freecodecamp.org", "freecodecamp.org/learn", "Back"]), [["freecodecamp.org", "freecodecamp.org/learn"], 0]); +``` + +`getBrowserHistory(["example.com", "example.com/about", "example.com/contact", "example.com/blog"])` should return `[["example.com", "example.com/about", "example.com/contact", "example.com/blog"], 3]`. + +```js +assert.deepEqual(getBrowserHistory(["example.com", "example.com/about", "example.com/contact", "example.com/blog"]), [["example.com", "example.com/about", "example.com/contact", "example.com/blog"], 3]); +``` + +`getBrowserHistory(["example.com", "example.com/about", "Back", "example.com/contact", "example.com/blog", "Back", "Back", "Forward"])` should return `[["example.com", "example.com/contact", "example.com/blog"], 1]`. + +```js +assert.deepEqual(getBrowserHistory(["example.com", "example.com/about", "Back", "example.com/contact", "example.com/blog", "Back", "Back", "Forward"]), [["example.com", "example.com/contact", "example.com/blog"], 1]); +``` + +`getBrowserHistory(["example.com", "example.com/about", "example.com/contact", "example.com/blog", "Back", "Back", "Forward", "freecodecamp.org"])` should return `[["example.com", "example.com/about", "example.com/contact", "freecodecamp.org"], 3]`. + +```js +assert.deepEqual(getBrowserHistory(["example.com", "example.com/about", "example.com/contact", "example.com/blog", "Back", "Back", "Forward", "freecodecamp.org"]), [["example.com", "example.com/about", "example.com/contact", "freecodecamp.org"], 3]); +``` + +`getBrowserHistory(["example.com", "example.com/about", "Back", "Back"])` should return `[["example.com", "example.com/about"], 0]`. + +```js +assert.deepEqual(getBrowserHistory(["example.com", "example.com/about", "Back", "Back"]), [["example.com", "example.com/about"], 0]); +``` + +`getBrowserHistory(["example.com", "example.com/about", "Forward"])` should return `[["example.com", "example.com/about"], 1]`. + +```js +assert.deepEqual(getBrowserHistory(["example.com", "example.com/about", "Forward"]), [["example.com", "example.com/about"], 1]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getBrowserHistory(commands) { + + return commands; +} +``` + +# --solutions-- + +```js +function getBrowserHistory(commands) { + const stack = []; + let index = -1; + + for (const command of commands) { + if (command === "Back") { + if (index > 0) index--; + } else if (command === "Forward") { + if (index < stack.length - 1) index++; + } else { + stack.splice(index + 1); + stack.push(command); + index++; + } + } + + return [stack, index]; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b559d2903b9e4afe9075f7.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b559d2903b9e4afe9075f7.md new file mode 100644 index 0000000000000000000000000000000000000000..c33d0efde1c6ead85a29daaa48af64829d0f8ae2 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b559d2903b9e4afe9075f7.md @@ -0,0 +1,118 @@ +--- +id: 69b559d2903b9e4afe9075f7 +title: "Challenge 237: Equation Validation" +challengeType: 28 +dashedName: challenge-237 +--- + +# --description-- + +Given a string representing a math equation, determine whether it is correct. + +- The left side may contain up to three positive integers and the operators `+`, `-`, `*`, and `/`. +- The equation will be given in the format: `"number operator number = number"` (with two or three numbers on the left). For example: `"2 + 2 = 4"` or `"2 + 3 - 1 = 4"`. +- The right side will always be a single integer. + +Follow standard order of operations: multiplication and division are evaluated before addition and subtraction, from left-to-right. + +# --hints-- + +`isValidEquation("2 + 2 = 4")` should return `true`. + +```js +assert.isTrue(isValidEquation("2 + 2 = 4")); +``` + +`isValidEquation("2 + 3 - 1 = 4")` should return `true`. + +```js +assert.isTrue(isValidEquation("2 + 3 - 1 = 4")); +``` + +`isValidEquation("8 / 2 = 4")` should return `true`. + +```js +assert.isTrue(isValidEquation("8 / 2 = 4")); +``` + +`isValidEquation("10 * 5 = 50")` should return `true`. + +```js +assert.isTrue(isValidEquation("10 * 5 = 50")); +``` + +`isValidEquation("2 - 2 = 0")` should return `true`. + +```js +assert.isTrue(isValidEquation("2 - 2 = 0")); +``` + +`isValidEquation("2 + 9 / 3 = 5")` should return `true`. + +```js +assert.isTrue(isValidEquation("2 + 9 / 3 = 5")); +``` + +`isValidEquation("20 - 2 * 3 = 14")` should return `true`. + +```js +assert.isTrue(isValidEquation("20 - 2 * 3 = 14")); +``` + +`isValidEquation("2 + 5 = 6")` should return `false`. + +```js +assert.isFalse(isValidEquation("2 + 5 = 6")); +``` + +`isValidEquation("10 - 2 * 3 = 24")` should return `false`. + +```js +assert.isFalse(isValidEquation("10 - 2 * 3 = 24")); +``` + +`isValidEquation("3 + 9 / 3 = 4")` should return `false`. + +```js +assert.isFalse(isValidEquation("3 + 9 / 3 = 4")); +``` + +# --seed-- + +## --seed-contents-- + +```js +function isValidEquation(equation) { + + return equation; +} +``` + +# --solutions-- + +```js +function isValidEquation(equation) { + const [left, right] = equation.split(" = "); + const tokens = left.split(" "); + + for (let i = 1; i < tokens.length - 1; i += 2) { + const operator = tokens[i]; + if (operator === "*" || operator === "/") { + const leftOperand = Number(tokens[i - 1]); + const rightOperand = Number(tokens[i + 1]); + const computed = operator === "*" ? leftOperand * rightOperand : leftOperand / rightOperand; + tokens.splice(i - 1, 3, String(computed)); + i -= 2; + } + } + + let result = Number(tokens[0]); + for (let i = 1; i < tokens.length - 1; i += 2) { + const operator = tokens[i]; + const operand = Number(tokens[i + 1]); + result = operator === "+" ? result + operand : result - operand; + } + + return result === Number(right); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b559d2903b9e4afe9075f8.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b559d2903b9e4afe9075f8.md new file mode 100644 index 0000000000000000000000000000000000000000..5c279dd2ff46f3e02a04be6917454ffb8282e15b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b559d2903b9e4afe9075f8.md @@ -0,0 +1,70 @@ +--- +id: 69b559d2903b9e4afe9075f8 +title: "Challenge 238: Digit Rotation Escape" +challengeType: 28 +dashedName: challenge-238 +--- + +# --description-- + +Given a positive integer, determine if it, or any of its rotations, is evenly divisible by its digit count. + +A rotation means to move the first digit to the end. For example, after 1 rotation, 123 becomes 231. + +- Check rotation `0` (the given number) first. +- Given numbers won't contain any zeros. +- Return the first rotation number if one is found, or `"none"` if not. + +# --hints-- + +`getRotation(123)` should return `0`. + +```js +assert.equal(getRotation(123), 0); +``` + +`getRotation(13579)` should return `3`. + +```js +assert.equal(getRotation(13579), 3); +``` + +`getRotation(24681)` should return `"none"`. + +```js +assert.equal(getRotation(24681), "none"); +``` + +`getRotation(84138789345)` should return `6`. + +```js +assert.equal(getRotation(84138789345), 6); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getRotation(n) { + + return n; +} +``` + +# --solutions-- + +```js +function getRotation(n) { + const str = String(n); + const digitCount = str.length; + let current = str; + + for (let i = 0; i < digitCount; i++) { + if (Number(current) % digitCount === 0) return i; + current = current.slice(1) + current[0]; + } + + return "none"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b559d2903b9e4afe9075f9.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b559d2903b9e4afe9075f9.md new file mode 100644 index 0000000000000000000000000000000000000000..734d4ff387c6efce55a18080ca086b3671380e91 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b559d2903b9e4afe9075f9.md @@ -0,0 +1,73 @@ +--- +id: 69b559d2903b9e4afe9075f9 +title: "Challenge 239: What Day Is It?" +challengeType: 28 +dashedName: challenge-239 +--- + +# --description-- + +Given a Unix timestamp in milliseconds, return the day of the week. + +Valid return days are: + +- `"Sunday"` +- `"Monday"` +- `"Tuesday"` +- `"Wednesday"` +- `"Thursday"` +- `"Friday"` +- `"Saturday"` + +Be sure to ignore time zones. + +# --hints-- + +`getDayOfWeek(1775492249000)` should return `"Monday"`. + +```js +assert.equal(getDayOfWeek(1775492249000), "Monday"); +``` + +`getDayOfWeek(1766246400000)` should return `"Saturday"`. + +```js +assert.equal(getDayOfWeek(1766246400000), "Saturday"); +``` + +`getDayOfWeek(33791256000000)` should return `"Tuesday"`. + +```js +assert.equal(getDayOfWeek(33791256000000), "Tuesday"); +``` + +`getDayOfWeek(1773576000000)` should return `"Sunday"`. + +```js +assert.equal(getDayOfWeek(1773576000000), "Sunday"); +``` + +`getDayOfWeek(0)` should return `"Thursday"`. + +```js +assert.equal(getDayOfWeek(0), "Thursday"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getDayOfWeek(timestamp) { + + return timestamp; +} +``` + +# --solutions-- + +```js +function getDayOfWeek(timestamp) { + return new Date(timestamp).toLocaleDateString("en-US", { weekday: "long", timeZone: "UTC" }); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b58ce40693f140c84c8559.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b58ce40693f140c84c8559.md new file mode 100644 index 0000000000000000000000000000000000000000..b9972ab6013e397cbe02b065129a179a1ccf8220 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b58ce40693f140c84c8559.md @@ -0,0 +1,67 @@ +--- +id: 69b58ce40693f140c84c8559 +title: "Challenge 240: Palindrome Characters" +challengeType: 28 +dashedName: challenge-240 +--- + +# --description-- + +Given a string, determine if it's a palindrome and return the middle character (if it's odd length) or middle two characters (if it's even). + +- A palindrome is a string that is the same forward and backward. +- If it's not a palindrome, return `"none"`. + +# --hints-- + +`palindromeLocator("racecar")` should return `"e"`. + +```js +assert.equal(palindromeLocator("racecar"), "e"); +``` + +`palindromeLocator("level")` should return `"v"`. + +```js +assert.equal(palindromeLocator("level"), "v"); +``` + +`palindromeLocator("freecodecamp")` should return `"none"`. + +```js +assert.equal(palindromeLocator("freecodecamp"), "none"); +``` + +`palindromeLocator("noon")` should return `"oo"`. + +```js +assert.equal(palindromeLocator("noon"), "oo"); +``` + +`palindromeLocator("11100111")` should return `"00"`. + +```js +assert.equal(palindromeLocator("11100111"), "00"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function palindromeLocator(str) { + + return str; +} +``` + +# --solutions-- + +```js +function palindromeLocator(str) { + if (str !== str.split("").reverse().join("")) return "none"; + + const mid = Math.floor(str.length / 2); + return str.length % 2 === 1 ? str[mid] : str[mid - 1] + str[mid]; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b58ce40693f140c84c855a.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b58ce40693f140c84c855a.md new file mode 100644 index 0000000000000000000000000000000000000000..a639d861aef42f20297ba04cf302ecfe250a9cbf --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b58ce40693f140c84c855a.md @@ -0,0 +1,96 @@ +--- +id: 69b58ce40693f140c84c855a +title: "Challenge 241: FizzBuzz Validator" +challengeType: 28 +dashedName: challenge-241 +--- + +# --description-- + +Given an array of sequential integers, with multiples of 3 and 5 replaced, determine if it's a valid FizzBuzz sequence. + +In a valid FizzBuzz sequence: + +- Multiples of 3 are replaced with "Fizz". +- Multiples of 5 are replaced with "Buzz". +- Multiples of both 3 and 5 are replaced with "FizzBuzz". +- All other numbers remain as integers. + +# --hints-- + +`isFizzBuzz([1, 2, "Fizz", 4, "Buzz"])` should return `true`. + +```js +assert.isTrue(isFizzBuzz([1, 2, "Fizz", 4, "Buzz"])); +``` + +`isFizzBuzz([13, 14, "FizzBuzz", 16, 17])` should return `true`. + +```js +assert.isTrue(isFizzBuzz([13, 14, "FizzBuzz", 16, 17])); +``` + +`isFizzBuzz([1, 2, "Fizz", 4, 5])` should return `false`. + +```js +assert.isFalse(isFizzBuzz([1, 2, "Fizz", 4, 5])); +``` + +`isFizzBuzz(["FizzBuzz", 16, 17, "Fizz", 19, "Buzz"])` should return `true`. + +```js +assert.isTrue(isFizzBuzz(["FizzBuzz", 16, 17, "Fizz", 19, "Buzz"])); +``` + +`isFizzBuzz([1, 2, "Fizz", "Buzz", 5])` should return `false`. + +```js +assert.isFalse(isFizzBuzz([1, 2, "Fizz", "Buzz", 5])); +``` + +`isFizzBuzz([97, 98, "Buzz", "Fizz", 101, "Fizz", 103])` should return `false`. + +```js +assert.isFalse(isFizzBuzz([97, 98, "Buzz", "Fizz", 101, "Fizz", 103])); +``` + +`isFizzBuzz(["Fizz", "Buzz", 101, "Fizz", 103, 104, "FizzBuzz"])` should return `true`. + +```js +assert.isTrue(isFizzBuzz(["Fizz", "Buzz", 101, "Fizz", 103, 104, "FizzBuzz"])); +``` + +# --seed-- + +## --seed-contents-- + +```js +function isFizzBuzz(arr) { + + return arr; +} +``` + +# --solutions-- + +```js +function isFizzBuzz(arr) { + let start = null; + for (let i = 0; i < arr.length; i++) { + if (typeof arr[i] === "number") { + start = arr[i] - i; + break; + } + } + + if (start === null) return false; + + for (let i = 0; i < arr.length; i++) { + const n = start + i; + const expected = n % 15 === 0 ? "FizzBuzz" : n % 3 === 0 ? "Fizz" : n % 5 === 0 ? "Buzz" : n; + if (arr[i] !== expected) return false; + } + + return true; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b58ce40693f140c84c855b.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b58ce40693f140c84c855b.md new file mode 100644 index 0000000000000000000000000000000000000000..e31fcfcd6c54c821ce980cbcda547abd40cdfb9e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b58ce40693f140c84c855b.md @@ -0,0 +1,80 @@ +--- +id: 69b58ce40693f140c84c855b +title: "Challenge 242: Next Bingo Number" +challengeType: 28 +dashedName: challenge-242 +--- + +# --description-- + +Given a bingo number, return the next bingo number sequentially. + +A bingo number is a single letter followed by a number in its range according to this chart: + +| Letter | Number Range | +| - | - | +| `"B"` | 1-15 | +| `"I"` | 16-30 | +| `"N"` | 31-45 | +| `"G"` | 46-60 | +| `"O"` | 61-75 | + +For example, given `"B10"`, return `"B11"`, the next bingo number. If given the last bingo number, return `"B1"`. + +# --hints-- + +`getNextBingoNumber("B10")` should return `"B11"`. + +```js +assert.equal(getNextBingoNumber("B10"), "B11"); +``` + +`getNextBingoNumber("N33")` should return `"N34"`. + +```js +assert.equal(getNextBingoNumber("N33"), "N34"); +``` + +`getNextBingoNumber("I30")` should return `"N31"`. + +```js +assert.equal(getNextBingoNumber("I30"), "N31"); +``` + +`getNextBingoNumber("G60")` should return `"O61"`. + +```js +assert.equal(getNextBingoNumber("G60"), "O61"); +``` + +`getNextBingoNumber("O75")` should return `"B1"`. + +```js +assert.equal(getNextBingoNumber("O75"), "B1"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getNextBingoNumber(n) { + + return n; +} +``` + +# --solutions-- + +```js +function getNextBingoNumber(n) { + const num = parseInt(n.slice(1)); + const next = num === 75 ? 1 : num + 1; + + if (next <= 15) return "B" + next; + if (next <= 30) return "I" + next; + if (next <= 45) return "N" + next; + if (next <= 60) return "G" + next; + return "O" + next; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b58ce40693f140c84c855c.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b58ce40693f140c84c855c.md new file mode 100644 index 0000000000000000000000000000000000000000..e5928fa58ff10b3ec049721b61655557dbcba115 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b58ce40693f140c84c855c.md @@ -0,0 +1,69 @@ +--- +id: 69b58ce40693f140c84c855c +title: "Challenge 243: Rook Attack" +challengeType: 28 +dashedName: challenge-243 +--- + +# --description-- + +Given two strings for the location of two rooks on a chess board, determine if they can attack each other. + +A standard chessboard is 8x8, with columns labeled `A` through `H` (left to right) and rows labeled `1` through `8` (bottom to top). It looks like this: + +|**A8**|**B8**|**C8**|**D8**|**E8**|**F8**|**G8**|**H8**| +|-|-|-|-|-|-|-|-| +|**A7**|**B7**|**C7**|**D7**|**E7**|**F7**|**G7**|**H7**| +|**A6**|**B6**|**C6**|**D6**|**E6**|**F6**|**G6**|**H6**| +|**A5**|**B5**|**C5**|**D5**|**E5**|**F5**|**G5**|**H5**| +|**A4**|**B4**|**C4**|**D4**|**E4**|**F4**|**G4**|**H4**| +|**A3**|**B3**|**C3**|**D3**|**E3**|**F3**|**G3**|**H3**| +|**A2**|**B2**|**C2**|**D2**|**E2**|**F2**|**G2**|**H2**| +|**A1**|**B1**|**C1**|**D1**|**E1**|**F1**|**G1**|**H1**| + +Rooks can move as many squares as they want in a horizontal or vertical direction. So if they are on the same row or column, they can attack each other. + +# --hints-- + +`rookAttack("A1", "A8")` should return `true`. + +```js +assert.isTrue(rookAttack("A1", "A8")); +``` + +`rookAttack("B4", "F4")` should return `true`. + +```js +assert.isTrue(rookAttack("B4", "F4")); +``` + +`rookAttack("E3", "D4")` should return `false`. + +```js +assert.isFalse(rookAttack("E3", "D4")); +``` + +`rookAttack("H7", "F6")` should return `false`. + +```js +assert.isFalse(rookAttack("H7", "F6")); +``` + +# --seed-- + +## --seed-contents-- + +```js +function rookAttack(rook1, rook2) { + + return rook1; +} +``` + +# --solutions-- + +```js +function rookAttack(rook1, rook2) { + return rook1[0] === rook2[0] || rook1[1] === rook2[1]; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b5b2be76ec8135a7fbe973.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b5b2be76ec8135a7fbe973.md new file mode 100644 index 0000000000000000000000000000000000000000..6e6f3ef2154572f58da0fb3aa3d3c6fbf716ec3d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b5b2be76ec8135a7fbe973.md @@ -0,0 +1,94 @@ +--- +id: 69b5b2be76ec8135a7fbe973 +title: "Challenge 244: Rook and Bishop Attack" +challengeType: 28 +dashedName: challenge-244 +--- + +# --description-- + +Given a string for the location of a rook on a chess board, and another for the location of a bishop, determine if one piece can attack another. + +A standard chessboard is 8x8, with columns labeled `A` through `H` (left to right) and rows labeled `1` through `8` (bottom to top). It looks like this: + +|**A8**|**B8**|**C8**|**D8**|**E8**|**F8**|**G8**|**H8**| +|-|-|-|-|-|-|-|-| +|**A7**|**B7**|**C7**|**D7**|**E7**|**F7**|**G7**|**H7**| +|**A6**|**B6**|**C6**|**D6**|**E6**|**F6**|**G6**|**H6**| +|**A5**|**B5**|**C5**|**D5**|**E5**|**F5**|**G5**|**H5**| +|**A4**|**B4**|**C4**|**D4**|**E4**|**F4**|**G4**|**H4**| +|**A3**|**B3**|**C3**|**D3**|**E3**|**F3**|**G3**|**H3**| +|**A2**|**B2**|**C2**|**D2**|**E2**|**F2**|**G2**|**H2**| +|**A1**|**B1**|**C1**|**D1**|**E1**|**F1**|**G1**|**H1**| + +- Rooks can move as many squares as they want in a horizontal or vertical direction. +- Bishops can move as many squares as they want in any diagonal direction. +- One piece can attack another if it can move to the location of that piece. + +Return: + +- `"rook"` if the rook can attack the bishop. +- `"bishop"` if the bishop can attack the rook. +- `"neither"` if neither piece can attack one another. + +# --hints-- + +`rookBishopAttack("A1", "A5")` should return `"rook"`. + +```js +assert.equal(rookBishopAttack("A1", "A5"), "rook"); +``` + +`rookBishopAttack("C3", "F6")` should return `"bishop"`. + +```js +assert.equal(rookBishopAttack("C3", "F6"), "bishop"); +``` + +`rookBishopAttack("D4", "D7")` should return `"rook"`. + +```js +assert.equal(rookBishopAttack("D4", "D7"), "rook"); +``` + +`rookBishopAttack("B7", "H1")` should return `"bishop"`. + +```js +assert.equal(rookBishopAttack("B7", "H1"), "bishop"); +``` + +`rookBishopAttack("B3", "C5")` should return `"neither"`. + +```js +assert.equal(rookBishopAttack("B3", "C5"), "neither"); +``` + +`rookBishopAttack("G3", "E8")` should return `"neither"`. + +```js +assert.equal(rookBishopAttack("G3", "E8"), "neither"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function rookBishopAttack(rook, bishop) { + + return rook; +} +``` + +# --solutions-- + +```js +function rookBishopAttack(rook, bishop) { + const colDiff = Math.abs(rook.charCodeAt(0) - bishop.charCodeAt(0)); + const rowDiff = Math.abs(rook[1] - bishop[1]); + + if (rook[0] === bishop[0] || rook[1] === bishop[1]) return "rook"; + if (colDiff === rowDiff) return "bishop"; + return "neither"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b5b2be76ec8135a7fbe974.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b5b2be76ec8135a7fbe974.md new file mode 100644 index 0000000000000000000000000000000000000000..9ec141e750132af4f1d65efd338a951d0835f50c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b5b2be76ec8135a7fbe974.md @@ -0,0 +1,91 @@ +--- +id: 69b5b2be76ec8135a7fbe974 +title: "Challenge 245: Spiral Matrix" +challengeType: 28 +dashedName: challenge-245 +--- + +# --description-- + +Given a 2D matrix, return a flat array with all of its values in clockwise order. + +The returned array should have the top-left value first, move right along the top row, then down the right column, then left along the bottom row, then up the left column. Repeat inward for any remaining layers. + +For example, given: + +```json +[ + [1, 2, 3], + [4, 5, 6], + [7, 8, 9] +] +``` + +Return `[1, 2, 3, 6, 9, 8, 7, 4, 5]`. + +# --hints-- + +`spiralMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])` should return `[1, 2, 3, 6, 9, 8, 7, 4, 5]`. + +```js +assert.deepEqual(spiralMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), [1, 2, 3, 6, 9, 8, 7, 4, 5]); +``` + +`spiralMatrix([["a", "b", "c", "d"], ["l", "m", "n", "e"], ["k", "p", "o", "f"], ["j", "i", "h", "g"]])` should return `["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p"]`. + +```js +assert.deepEqual(spiralMatrix([["a", "b", "c", "d"], ["l", "m", "n", "e"], ["k", "p", "o", "f"], ["j", "i", "h", "g"]]), ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p"]); +``` + +`spiralMatrix([[true, false, false], [false, true, true], [false, true, false], [true, true, false]])` should return `[true, false, false, true, false, false, true, true, false, false, true, true]`. + +```js +assert.deepEqual(spiralMatrix([[true, false, false], [false, true, true], [false, true, false], [true, true, false]]), [true, false, false, true, false, false, true, true, false, false, true, true]); +``` + +`spiralMatrix([[25, 24, 23, 22, 21], [10, 9, 8, 7, 20], [11, 2, 1, 6, 19], [12, 3, 4, 5, 18], [13, 14, 15, 16, 17]])` should return `[25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]`. + +```js +assert.deepEqual(spiralMatrix([[25, 24, 23, 22, 21], [10, 9, 8, 7, 20], [11, 2, 1, 6, 19], [12, 3, 4, 5, 18], [13, 14, 15, 16, 17]]), [25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function spiralMatrix(matrix) { + + return matrix; +} +``` + +# --solutions-- + +```js +function spiralMatrix(matrix) { + const result = []; + let top = 0, bottom = matrix.length - 1; + let left = 0, right = matrix[0].length - 1; + + while (top <= bottom && left <= right) { + for (let i = left; i <= right; i++) result.push(matrix[top][i]); + top++; + + for (let i = top; i <= bottom; i++) result.push(matrix[i][right]); + right--; + + if (top <= bottom) { + for (let i = right; i >= left; i--) result.push(matrix[bottom][i]); + bottom--; + } + + if (left <= right) { + for (let i = bottom; i >= top; i--) result.push(matrix[i][left]); + left++; + } + } + + return result; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69bc6cb30c1d112a2e110a03.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69bc6cb30c1d112a2e110a03.md new file mode 100644 index 0000000000000000000000000000000000000000..3a67318528f40cfc41b850f5cefb0cdc3b8eb3f0 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69bc6cb30c1d112a2e110a03.md @@ -0,0 +1,67 @@ +--- +id: 69bc6cb30c1d112a2e110a03 +title: "Challenge 246: Name Initials" +challengeType: 28 +dashedName: challenge-246 +--- + +# --description-- + +Given a full name as a string, return their initials. + +- Names to initialize are separated by a space. +- Initials should be made uppercase. +- Initials should be separated by dots. + +For example, `"Tommy Millwood"` returns `"T.M."`. + +# --hints-- + +`getInitials("Tommy Millwood")` should return `"T.M."`. + +```js +assert.equal(getInitials("Tommy Millwood"), "T.M."); +``` + +`getInitials("Savanna Puddlesplash")` should return `"S.P."`. + +```js +assert.equal(getInitials("Savanna Puddlesplash"), "S.P."); +``` + +`getInitials("Frances Cowell Conrad")` should return `"F.C.C."`. + +```js +assert.equal(getInitials("Frances Cowell Conrad"), "F.C.C."); +``` + +`getInitials("Dragon")` should return `"D."`. + +```js +assert.equal(getInitials("Dragon"), "D."); +``` + +`getInitials("Dorothy Vera Clump Haverstock Norris")` should return `"D.V.C.H.N."`. + +```js +assert.equal(getInitials("Dorothy Vera Clump Haverstock Norris"), "D.V.C.H.N."); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getInitials(name) { + + return name; +} +``` + +# --solutions-- + +```js +function getInitials(name) { + return name.split(' ').map(word => word[0].toUpperCase() + '.').join(''); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69bc6cb30c1d112a2e110a04.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69bc6cb30c1d112a2e110a04.md new file mode 100644 index 0000000000000000000000000000000000000000..a507718b92e7ba867a27c20f88785a118eb1020a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69bc6cb30c1d112a2e110a04.md @@ -0,0 +1,65 @@ +--- +id: 69bc6cb30c1d112a2e110a04 +title: "Challenge 247: Last Letter" +challengeType: 28 +dashedName: challenge-247 +--- + +# --description-- + +Given a string, return the letter from the string that appears last in the alphabet. + +- If two or more letters tie for the last in the alphabet, return the first one. +- Ignore all non-letter characters. + +# --hints-- + +`getLastLetter("world")` should return `"w"`. + +```js +assert.equal(getLastLetter("world"), "w"); +``` + +`getLastLetter("Hello World")` should return `"W"`. + +```js +assert.equal(getLastLetter("Hello World"), "W"); +``` + +`getLastLetter("The quick brown fox jumped over the lazy dog.")` should return `"z"`. + +```js +assert.equal(getLastLetter("The quick brown fox jumped over the lazy dog."), "z"); +``` + +`getLastLetter("HeLl0")` should return `"L"`. + +```js +assert.equal(getLastLetter("HeLl0"), "L"); +``` + +`getLastLetter("!#$ er@R asd fT.,> 2t0e9")` should return `"T"`. + +```js +assert.equal(getLastLetter("!#$ er@R asd fT.,> 2t0e9"), "T"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getLastLetter(str) { + + return str; +} +``` + +# --solutions-- + +```js +function getLastLetter(str) { + const letters = str.split('').filter(char => /[a-zA-Z]/.test(char)); + return letters.reduce((last, char) => char.toLowerCase() > last.toLowerCase() ? char : last); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69bc6cb30c1d112a2e110a05.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69bc6cb30c1d112a2e110a05.md new file mode 100644 index 0000000000000000000000000000000000000000..04945a42603e7e64a824b61d75d0a9b5f8f56cc6 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69bc6cb30c1d112a2e110a05.md @@ -0,0 +1,76 @@ +--- +id: 69bc6cb30c1d112a2e110a05 +title: "Challenge 248: Sorted Array Swap" +challengeType: 28 +dashedName: challenge-248 +--- + +# --description-- + +Given an array of integers, return a new array using the following rules: + +1. Sort the integers in ascending order +2. Then swap all values whose index is a multiple of 3 with the value before it. + +# --hints-- + +`sortAndSwap([3, 1, 2, 4, 6, 5])` should return `[1, 2, 4, 3, 5, 6]`. + +```js +assert.deepEqual(sortAndSwap([3, 1, 2, 4, 6, 5]), [1, 2, 4, 3, 5, 6]); +``` + +`sortAndSwap([9, 7, 5, 3, 1, 2, 4, 6, 8])` should return `[1, 2, 4, 3, 5, 7, 6, 8, 9]`. + +```js +assert.deepEqual(sortAndSwap([9, 7, 5, 3, 1, 2, 4, 6, 8]), [1, 2, 4, 3, 5, 7, 6, 8, 9]); +``` + +`sortAndSwap([1, 2, 3, 4, 5, 6, 7, 8, 9])` should return `[1, 2, 4, 3, 5, 7, 6, 8, 9]`. + +```js +assert.deepEqual(sortAndSwap([1, 2, 3, 4, 5, 6, 7, 8, 9]), [1, 2, 4, 3, 5, 7, 6, 8, 9]); +``` + +`sortAndSwap([12, 5, 8, 1, 3, 10, 2, 7, 6, 4, 9, 11])` should return `[1, 2, 4, 3, 5, 7, 6, 8, 10, 9, 11, 12]`. + +```js +assert.deepEqual(sortAndSwap([12, 5, 8, 1, 3, 10, 2, 7, 6, 4, 9, 11]), [1, 2, 4, 3, 5, 7, 6, 8, 10, 9, 11, 12]); +``` + +`sortAndSwap([100, -50, 0, 75, -25, 50, -75, 25])` should return `[-75, -50, 0, -25, 25, 75, 50, 100]`. + +```js +assert.deepEqual(sortAndSwap([100, -50, 0, 75, -25, 50, -75, 25]), [-75, -50, 0, -25, 25, 75, 50, 100]); +``` + +`sortAndSwap([5, 9, 13, 77, 88, 313, -10, -65, 0, 8, 99, 101, -4, 2])` should return `[-65, -10, 0, -4, 2, 8, 5, 9, 77, 13, 88, 101, 99, 313]`. + +```js +assert.deepEqual(sortAndSwap([5, 9, 13, 77, 88, 313, -10, -65, 0, 8, 99, 101, -4, 2]), [-65, -10, 0, -4, 2, 8, 5, 9, 77, 13, 88, 101, 99, 313]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function sortAndSwap(arr) { + + return arr; +} +``` + +# --solutions-- + +```js +function sortAndSwap(arr) { + const result = [...arr].sort((a, b) => a - b); + + for (let i = 3; i < result.length; i += 3) { + [result[i], result[i - 1]] = [result[i - 1], result[i]]; + } + + return result; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69bc6cb30c1d112a2e110a06.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69bc6cb30c1d112a2e110a06.md new file mode 100644 index 0000000000000000000000000000000000000000..c829d2d1df2e9e8c3a04eee9117bee77fad55534 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69bc6cb30c1d112a2e110a06.md @@ -0,0 +1,85 @@ +--- +id: 69bc6cb30c1d112a2e110a06 +title: "Challenge 249: String Math" +challengeType: 28 +dashedName: challenge-249 +--- + +# --description-- + +Given a string with numbers and other characters, perform math on the numbers based on the count of non-digit characters between the numbers. + +- If the count of characters separating two numbers is even, use addition. +- If it's odd, use subtraction. +- Consecutive digits form a single number. +- Operations are applied left to right. +- Ignore leading and trailing characters that aren't digits. + +For example, given `"3ab10c8"`, return `5`. Add 3 and 10 to get 13 because there's an even number of characters between them. Then subtract 8 from 13 because there's an odd number of characters between the result and 8. + +# --hints-- + +`doMath("3ab10c8")` should return `5`. + +```js +assert.equal(doMath("3ab10c8"), 5); +``` + +`doMath("6MINUS4")` should return `2`. + +```js +assert.equal(doMath("6MINUS4"), 2); +``` + +`doMath("9plus3")` should return `12`. + +```js +assert.equal(doMath("9plus3"), 12); +``` + +`doMath("5fkwo#10i#%.<>15P=@20!#B/25")` should return `15`. + +```js +assert.equal(doMath("5fkwo#10i#%.<>15P=@20!#B/25"), 15); +``` + +`doMath("a.67,1$lk6ldf34@#LD@]2d32d2'2l3,@l3L#@2gh35s09if=df#$t9sm49t0df3$^%[vc;:0:4mt")` should return `67`. + +```js +assert.equal(doMath("a.67,1$lk6ldf34@#LD@]2d32d2'2l3,@l3L#@2gh35s09if=df#$t9sm49t0df3$^%[vc;:0:4mt"), 67); +``` + +# --seed-- + +## --seed-contents-- + +```js +function doMath(str) { + + return str; +} +``` + +# --solutions-- + +```js +function doMath(str) { + const tokens = str.match(/(\d+)|(\D+)/g); + let result = null; + let pendingOp = null; + + for (const token of tokens) { + if (/^\d+$/.test(token)) { + if (result === null) { + result = parseInt(token); + } else { + result = pendingOp === 'add' ? result + parseInt(token) : result - parseInt(token); + } + } else { + pendingOp = token.length % 2 === 0 ? 'add' : 'subtract'; + } + } + + return result; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69bc6cb30c1d112a2e110a07.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69bc6cb30c1d112a2e110a07.md new file mode 100644 index 0000000000000000000000000000000000000000..1f17ae3df7330c1f9f6a965e290de4eb466739e2 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69bc6cb30c1d112a2e110a07.md @@ -0,0 +1,87 @@ +--- +id: 69bc6cb30c1d112a2e110a07 +title: "Challenge 250: Hidden Key" +challengeType: 28 +dashedName: challenge-250 +--- + +# --description-- + +Welcome to the 250th daily challenge! + +Given an encoded string, decode it using an encryption key and return it. + +To find the key: + +- Look at all daily challenges, from challenge number 1 up to today, whose challenge number is a multiple of 25 (including this one). +- Take the first letter from each of those challenge titles and combine them into a string. If the title starts with a non-letter, find its first letter. + +To decode the message, go over each letter in the encoded message and: + + 1. Look at the corresponding letter in the key (repeat the key if the message is longer than the key). + 2. Convert the key letter to its corresponding number: `"A"` = 1, `"B"` = 2, ..., `"Z"` = 26. + 3. Shift the encoded letter backward in the alphabet by that number. + 4. If the shift goes before `"A"`, wrap around to `"Z"`. + +For example, if the encoded message starts with `"Y"` and the first key letter is `"V"` (22), shift `"Y"` back 22 places to get `"C"`. Repeat this process for each letter to decode the full message. + +- Only letters are shifted, spaces are returned as-is. +- All given and returned letters are uppercase. + +# --hints-- + +`decode("YAVJYNXE")` should return `"CONGRATS"`. + +```js +assert.equal(decode("YAVJYNXE"), "CONGRATS"); +``` + +`decode("YALLUT PQUMJP")` should return `"CODING LEGEND"`. + +```js +assert.equal(decode("YALLUT PQUMJP"), "CODING LEGEND"); +``` + +`decode("UAC DYR EISAKYM")` should return `"YOU ARE AWESOME"`. + +```js +assert.equal(decode("UAC DYR EISAKYM"), "YOU ARE AWESOME"); +``` + +`decode("GQMS NBMZU")` should return `"KEEP GOING"`. + +```js +assert.equal(decode("GQMS NBMZU"), "KEEP GOING"); +``` + +`decode("W IQQURV UG I ZDMDTRV IVW JQDHY TMHSA QB")` should return `"A WINNER IS A DREAMER WHO NEVER GIVES UP"`. + +```js +assert.equal(decode("W IQQURV UG I ZDMDTRV IVW JQDHY TMHSA QB"), "A WINNER IS A DREAMER WHO NEVER GIVES UP"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function decode(message) { + + return message; +} +``` + +# --solutions-- + +```js +function decode(message) { + const key = "VLHCGMDLNH"; + let keyIndex = 0; + return message.split('').map(char => { + if (char === ' ') return char; + const shift = key[keyIndex % key.length].charCodeAt(0) - 64; + keyIndex++; + return String.fromCharCode(((char.charCodeAt(0) - 65 - shift + 26) % 26) + 65); + }).join(''); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69bc6cb30c1d112a2e110a08.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69bc6cb30c1d112a2e110a08.md new file mode 100644 index 0000000000000000000000000000000000000000..56c07db600f84f6b04ad03a9fcbf760650057245 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69bc6cb30c1d112a2e110a08.md @@ -0,0 +1,91 @@ +--- +id: 69bc6cb30c1d112a2e110a08 +title: "Challenge 251: Array Sum Finder" +challengeType: 28 +dashedName: challenge-251 +--- + +# --description-- + +Given an array of numbers and a target number, return the first subset of two or more numbers that adds up to the target. + +- The "first" subset is the one whose elements have the lowest possible indices, prioritizing the earliest index first. +- Each number in the array may only be used once. +- If no valid subset exists, return `"Sum not found"`. + +Return the matching numbers as an array in the order they appear in the original array. + +# --hints-- + +`findSum([1, 3, 5, 7], 6)` should return `[1, 5]`. + +```js +assert.deepEqual(findSum([1, 3, 5, 7], 6), [1, 5]); +``` + +`findSum([1, 2, 3, 4, 5], 5)` should return `[1, 4]`. + +```js +assert.deepEqual(findSum([1, 2, 3, 4, 5], 5), [1, 4]); +``` + +`findSum([1, 2, 3, 4, 5], 6)` should return `[1, 2, 3]`. + +```js +assert.deepEqual(findSum([1, 2, 3, 4, 5], 6), [1, 2, 3]); +``` + +`findSum([-1, -2, 3, 4], 1)` should return `[-1, -2, 4]`. + +```js +assert.deepEqual(findSum([-1, -2, 3, 4], 1), [-1, -2, 4]); +``` + +`findSum([3, 1, 4, 1, 5, 9, 2, 6], 10)` should return `[3, 1, 4, 2]`. + +```js +assert.deepEqual(findSum([3, 1, 4, 1, 5, 9, 2, 6], 10), [3, 1, 4, 2]); +``` + +`findSum([1, 2, 3, 4, 5, 6, 7, 8, 9], 20)` should return `[1, 2, 3, 5, 9]`. + +```js +assert.deepEqual(findSum([1, 2, 3, 4, 5, 6, 7, 8, 9], 20), [1, 2, 3, 5, 9]); +``` + +`findSum([7, 9, 4, 2, 5], 10)` should return `"Sum not found"`. + +```js +assert.equal(findSum([7, 9, 4, 2, 5], 10), "Sum not found"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function findSum(arr, target) { + + return arr; +} +``` + +# --solutions-- + +```js +function findSum(arr, target) { + function search(start, remaining, current) { + if (remaining === 0 && current.length >= 2) return current; + if (start >= arr.length) return null; + + for (let i = start; i < arr.length; i++) { + const result = search(i + 1, remaining - arr[i], [...current, arr[i]]); + if (result) return result; + } + + return null; + } + + return search(0, target, []) ?? "Sum not found"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69bc6cb30c1d112a2e110a09.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69bc6cb30c1d112a2e110a09.md new file mode 100644 index 0000000000000000000000000000000000000000..51842bfd1e2f551ed7efa3626b6f19fe4d243ec2 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69bc6cb30c1d112a2e110a09.md @@ -0,0 +1,75 @@ +--- +id: 69bc6cb30c1d112a2e110a09 +title: "Challenge 252: Unique Stair Climber" +challengeType: 28 +dashedName: challenge-252 +--- + +# --description-- + +Given a number of stairs, return how many distinct ways someone can climb them taking either 1 or 2 steps at a time. + +# --hints-- + +`getUniqueClimbs(4)` should return `5`. + +```js +assert.equal(getUniqueClimbs(4), 5); +``` + +`getUniqueClimbs(5)` should return `8`. + +```js +assert.equal(getUniqueClimbs(5), 8); +``` + +`getUniqueClimbs(10)` should return `89`. + +```js +assert.equal(getUniqueClimbs(10), 89); +``` + +`getUniqueClimbs(18)` should return `4181`. + +```js +assert.equal(getUniqueClimbs(18), 4181); +``` + +`getUniqueClimbs(29)` should return `832040`. + +```js +assert.equal(getUniqueClimbs(29), 832040); +``` + +`getUniqueClimbs(50)` should return `20365011074`. + +```js +assert.equal(getUniqueClimbs(50), 20365011074); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getUniqueClimbs(steps) { + + return steps; +} +``` + +# --solutions-- + +```js +function getUniqueClimbs(steps) { + if (steps <= 0) return 0; + if (steps === 1) return 1; + if (steps === 2) return 2; + + let prev2 = 1, prev1 = 2; + for (let i = 3; i <= steps; i++) { + [prev2, prev1] = [prev1, prev2 + prev1]; + } + return prev1; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c5f3d787b1725d5f00c8b7.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c5f3d787b1725d5f00c8b7.md new file mode 100644 index 0000000000000000000000000000000000000000..09dd5bb584026b9b970c43d0464d700d55891723 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c5f3d787b1725d5f00c8b7.md @@ -0,0 +1,96 @@ +--- +id: 69c5f3d787b1725d5f00c8b7 +title: "Challenge 253: Acronym Finder" +challengeType: 28 +dashedName: challenge-253 +--- + +# --description-- + +Given a string representing an acronym, return the full name of the organization it belongs to from the list below: + +- `"National Avocado Storage Authority"` +- `"Cats Infiltration Agency"` +- `"Fluffy Beanbag Inspectors"` +- `"Department Of Jelly"` +- `"Wild Honey Organization"` +- `"Eating Pancakes Administration"` + +Each letter in the given acronym should match the first letter of each word in the organization it belongs to, in the same order. + +# --hints-- + +`findOrg("NASA")` should return `"National Avocado Storage Authority"`. + +```js +assert.equal(findOrg("NASA"), "National Avocado Storage Authority"); +``` + +`findOrg("CIA")` should return `"Cats Infiltration Agency"`. + +```js +assert.equal(findOrg("CIA"), "Cats Infiltration Agency"); +``` + +`findOrg("FBI")` should return `"Fluffy Beanbag Inspectors"`. + +```js +assert.equal(findOrg("FBI"), "Fluffy Beanbag Inspectors"); +``` + +`findOrg("DOJ")` should return `"Department Of Jelly"`. + +```js +assert.equal(findOrg("DOJ"), "Department Of Jelly"); +``` + +`findOrg("WHO")` should return `"Wild Honey Organization"`. + +```js +assert.equal(findOrg("WHO"), "Wild Honey Organization"); +``` + +`findOrg("EPA")` should return `"Eating Pancakes Administration"`. + +```js +assert.equal(findOrg("EPA"), "Eating Pancakes Administration"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function findOrg(acronym) { + + return acronym; +} +``` + +# --solutions-- + +```js +function findOrg(acronym) { + const orgs = [ + "National Avocado Storage Authority", + "Cats Infiltration Agency", + "Fluffy Beanbag Inspectors", + "Department Of Jelly", + "Wild Honey Organization", + "Eating Pancakes Administration" + ]; + + for (let org of orgs) { + const initials = org + .split(" ") + .map(word => word[0]) + .join(""); + + if (initials.toUpperCase() === acronym.toUpperCase()) { + return org; + } + } + + return "not found"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c5f3d787b1725d5f00c8b8.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c5f3d787b1725d5f00c8b8.md new file mode 100644 index 0000000000000000000000000000000000000000..f838cb86f6df2ce6d964c4e7a959065975433971 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c5f3d787b1725d5f00c8b8.md @@ -0,0 +1,61 @@ +--- +id: 69c5f3d787b1725d5f00c8b8 +title: "Challenge 254: Odd Words" +challengeType: 28 +dashedName: challenge-254 +--- + +# --description-- + +Given a string of words, return only the words with an odd number of letters. + +- Words in the given string will be separated by a single space. +- Return the words separated by a single space. + +# --hints-- + +`getOddWords("This is a super good test")` should return `"a super"`. + +```js +assert.equal(getOddWords("This is a super good test"), "a super"); +``` + +`getOddWords("one two three four")` should return `"one two three"`. + +```js +assert.equal(getOddWords("one two three four"), "one two three"); +``` + +`getOddWords("banana split sundae with rainbow sprinkles on top")` should return `"split rainbow sprinkles top"`. + +```js +assert.equal(getOddWords("banana split sundae with rainbow sprinkles on top"), "split rainbow sprinkles top"); +``` + +`getOddWords("The quick brown fox jumped over the lazy river")` should return `"The quick brown fox the river"`. + +```js +assert.equal(getOddWords("The quick brown fox jumped over the lazy river"), "The quick brown fox the river"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getOddWords(str) { + + return str; +} +``` + +# --solutions-- + +```js +function getOddWords(str) { + return str + .split(" ") + .filter(word => word.length % 2 === 1) + .join(" "); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c5f3d787b1725d5f00c8b9.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c5f3d787b1725d5f00c8b9.md new file mode 100644 index 0000000000000000000000000000000000000000..9ad96ac7cdb959e75883b1ac222068caeeaa8bf0 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c5f3d787b1725d5f00c8b9.md @@ -0,0 +1,135 @@ +--- +id: 69c5f3d787b1725d5f00c8b9 +title: "Challenge 255: Earth Day Cleanup Crew" +challengeType: 28 +dashedName: challenge-255 +--- + +# --description-- + +Today is Earth Day. Given an array of items you cleaned up, return your total cleanup score based on the rules below. + +Given items will be one of: + +| Item | Base Value | +| - | - | +| `"bottle"` | 10 | +| `"can"` | 6 | +| `"bag"` | 8 | +| `"tire"` | 35 | +| `"straw"` | 4 | +| `"cardboard"` | 3 | +| `"newspaper"` | 3 | +| `"shoe"` | 12 | +| `"electronics"` | 25 | +| `"battery"` | 18 | +| `"mattress"` | 38 | + +A Rare item is represented as `["rare", value]`. For example, `["rare", 80]`. Rare items do not get a streak bonus. + +- Streak bonus: If the same item appears consecutively, it gets increasing bonus points. + - First consecutive occurrence: base value + - Second: base value + 1 + - Third: base value + 2 + - etc. +- Fifth Item Multiplier: Every fifth item collected gets a multiplier. + - Fifth item: *2 + - Tenth item: *3 + - etc. + +- Apply the multiplier after calculating any bonuses. + +# --hints-- + +`getCleanupScore(["bottle", "straw", "shoe", "battery"])` should return `44`. + +```js +assert.equal(getCleanupScore(["bottle", "straw", "shoe", "battery"]), 44); +``` + +`getCleanupScore(["electronics", "straw", "newspaper", "bottle", "bag"])` should return `58`. + +```js +assert.equal(getCleanupScore(["electronics", "straw", "newspaper", "bottle", "bag"]), 58); +``` + +`getCleanupScore(["shoe", "can", "can", "can", "bottle", "bottle", "straw", "straw", "straw"])` should return `79`. + +```js +assert.equal(getCleanupScore(["shoe", "can", "can", "can", "bottle", "bottle", "straw", "straw", "straw"]), 79); +``` + +`getCleanupScore(["mattress", ["rare", 80], "tire", "tire", "tire", ["rare", 95]])` should return `358`. + +```js +assert.equal(getCleanupScore(["mattress", ["rare", 80], "tire", "tire", "tire", ["rare", 95]]), 358); +``` + +`getCleanupScore(["bottle", "can", "can", "shoe", "shoe", ["rare", 56], "bottle", "bottle", "can", "can", "electronics", "bottle", ["rare", 48], "bottle", "can", "can", "can", "can", "can", "can", "can"])` should return `383`. + +```js +assert.equal(getCleanupScore(["bottle", "can", "can", "shoe", "shoe", ["rare", 56], "bottle", "bottle", "can", "can", "electronics", "bottle", ["rare", 48], "bottle", "can", "can", "can", "can", "can", "can", "can"]), 383); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getCleanupScore(items) { + + return items; +} +``` + +# --solutions-- + +```js +function getCleanupScore(items) { + const values = { + bottle: 10, + can: 6, + bag: 8, + tire: 35, + straw: 4, + cardboard: 3, + newspaper: 3, + shoe: 12, + electronics: 25, + battery: 18, + mattress: 38 + }; + + let total = 0; + let prevItem = null; + let streak = 0; + + for (let i = 0; i < items.length; i++) { + let item = items[i]; + let base; + let isRare = Array.isArray(item) && item[0] === "rare"; + + if (isRare) { + base = item[1]; + prevItem = null; + streak = 0; + } else { + base = values[item]; + streak = item === prevItem ? streak + 1 : 0; + prevItem = item; + } + + let points = base; + if (!isRare) points += streak; + + if ((i + 1) % 5 === 0) { + const multiplier = (i + 1) / 5 + 1; + points *= multiplier; + } + + total += points; + } + + return total; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c5f3d787b1725d5f00c8ba.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c5f3d787b1725d5f00c8ba.md new file mode 100644 index 0000000000000000000000000000000000000000..78337563a95f66fd7c173c5749378eb2cb2d5d67 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c5f3d787b1725d5f00c8ba.md @@ -0,0 +1,89 @@ +--- +id: 69c5f3d787b1725d5f00c8ba +title: "Challenge 256: Closest Time Direction" +challengeType: 28 +dashedName: challenge-256 +--- + +# --description-- + +Given two times, determine whether you can get from the first to the second faster by moving forward or backward. + +- Times are given in 24-hour format (`"HH:MM"`) +- The clock wraps around (23:59 goes to 00:00 when moving forward, and 00:00 goes to 23:59 when moving backwards) + +Return: + +- `"forward"` if moving forward is shorter +- `"backward"` if moving backward is shorter +- `"equal"` if both directions take the same amount of time + +# --hints-- + +`getDirection("10:00", "12:00")` should return `"forward"`. + +```js +assert.equal(getDirection("10:00", "12:00"), "forward"); +``` + +`getDirection("11:00", "05:00")` should return `"backward"`. + +```js +assert.equal(getDirection("11:00", "05:00"), "backward"); +``` + +`getDirection("00:00", "12:00")` should return `"equal"`. + +```js +assert.equal(getDirection("00:00", "12:00"), "equal"); +``` + +`getDirection("15:45", "01:10")` should return `"forward"`. + +```js +assert.equal(getDirection("15:45", "01:10"), "forward"); +``` + +`getDirection("03:30", "19:50")` should return `"backward"`. + +```js +assert.equal(getDirection("03:30", "19:50"), "backward"); +``` + +`getDirection("06:30", "18:30")` should return `"equal"`. + +```js +assert.equal(getDirection("06:30", "18:30"), "equal"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getDirection(time1, time2) { + + return time1; +} +``` + +# --solutions-- + +```js +function getDirection(time1, time2) { + function toMinutes(t) { + const [h, m] = t.split(":").map(Number); + return h * 60 + m; + } + + const start = toMinutes(time1); + const end = toMinutes(time2); + + const forward = (end - start + 1440) % 1440; + const backward = (start - end + 1440) % 1440; + + if (forward < backward) return "forward"; + if (backward < forward) return "backward"; + return "equal"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c5f3d787b1725d5f00c8bb.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c5f3d787b1725d5f00c8bb.md new file mode 100644 index 0000000000000000000000000000000000000000..c4e2c962f765aa775d1e648428c4a4f5ac3e4835 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c5f3d787b1725d5f00c8bb.md @@ -0,0 +1,76 @@ +--- +id: 69c5f3d787b1725d5f00c8bb +title: "Challenge 257: Word Compressor" +challengeType: 28 +dashedName: challenge-257 +--- + +# --description-- + +Given a string, return a compressed version of the string using the following rules: + +- The first occurrence of a word remains unchanged. +- Subsequent occurrences are replaced with the position of the first occurrence, where the first word is at position 1. +- Words are separated by a single space. + +For example, given `"practice makes perfect and perfect practice makes perfect"`, return `"practice makes perfect and 3 1 2 3"`. + +# --hints-- + +`compress("practice makes perfect and perfect practice makes perfect")` should return `"practice makes perfect and 3 1 2 3"`. + +```js +assert.equal(compress("practice makes perfect and perfect practice makes perfect"), "practice makes perfect and 3 1 2 3"); +``` + +`compress("hello hello hello")` should return `"hello 1 1"`. + +```js +assert.equal(compress("hello hello hello"), "hello 1 1"); +``` + +`compress("the cat sat on the mat on which the cat sat")` should return `"the cat sat on 1 mat 4 which 1 2 3"`. + +```js +assert.equal(compress("the cat sat on the mat on which the cat sat"), "the cat sat on 1 mat 4 which 1 2 3"); +``` + +`compress("the more you know the more you realize you don't know")` should return `"the more you know 1 2 3 realize 3 don't 4"`. + +```js +assert.equal(compress("the more you know the more you realize you don't know"), "the more you know 1 2 3 realize 3 don't 4"); +``` + +`compress("lorem ipsum dolor sit per elit donec sit nostra libero per donec ligula sit gravida at elit vitae a elit sodales donec en donec at dolor nam ligula dignissim risus at ligula per nam ipsum ipsum gravida en elit per ipsum ligula en gravida per sodales sit at nam lorem sit per libero en ipsum elit sit sodales sit risus elit risus ipsum elit at gravida vitae en dignissim nam sit vitae sollicitudin per nostra per sit libero")` should return `"lorem ipsum dolor sit per elit donec 4 nostra libero 5 7 ligula 4 gravida at 6 vitae a 6 sodales 7 en 7 16 3 nam 13 dignissim risus 16 13 5 27 2 2 15 23 6 5 2 13 23 15 5 21 4 16 27 1 4 5 10 23 2 6 4 21 4 30 6 30 2 6 16 15 18 23 29 27 4 18 sollicitudin 5 9 5 4 10"`. + +```js +assert.equal(compress("lorem ipsum dolor sit per elit donec sit nostra libero per donec ligula sit gravida at elit vitae a elit sodales donec en donec at dolor nam ligula dignissim risus at ligula per nam ipsum ipsum gravida en elit per ipsum ligula en gravida per sodales sit at nam lorem sit per libero en ipsum elit sit sodales sit risus elit risus ipsum elit at gravida vitae en dignissim nam sit vitae sollicitudin per nostra per sit libero"), "lorem ipsum dolor sit per elit donec 4 nostra libero 5 7 ligula 4 gravida at 6 vitae a 6 sodales 7 en 7 16 3 nam 13 dignissim risus 16 13 5 27 2 2 15 23 6 5 2 13 23 15 5 21 4 16 27 1 4 5 10 23 2 6 4 21 4 30 6 30 2 6 16 15 18 23 29 27 4 18 sollicitudin 5 9 5 4 10"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function compress(str) { + + return str; +} +``` + +# --solutions-- + +```js +function compress(str) { + const words = str.split(" "); + const seen = {}; + + return words.map((word, i) => { + if (seen[word] !== undefined) { + return seen[word]; + } + seen[word] = i + 1; + return word; + }).join(" "); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c5f3d787b1725d5f00c8bc.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c5f3d787b1725d5f00c8bc.md new file mode 100644 index 0000000000000000000000000000000000000000..ba5078a355a15688c0e82f51c64b7a987e43a507 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c5f3d787b1725d5f00c8bc.md @@ -0,0 +1,78 @@ +--- +id: 69c5f3d787b1725d5f00c8bc +title: "Challenge 258: Word Decompressor" +challengeType: 28 +dashedName: challenge-258 +--- + +# --description-- + +Given a compressed string, return the decompressed version using the following rules: + +- The given string is made up of words and numbers separated by spaces. +- Leave the words unchanged. +- Replace numbers with the word at that position, where the first word is at position 1. + +For example, given `"practice makes perfect and 3 1 2 3"`, return `"practice makes perfect and perfect practice makes perfect"`. + +# --hints-- + +`decompress("practice makes perfect and 3 1 2 3")` should return `"practice makes perfect and perfect practice makes perfect"`. + +```js +assert.equal(decompress("practice makes perfect and 3 1 2 3"), "practice makes perfect and perfect practice makes perfect"); +``` + +`decompress("hello 1 1")` should return `"hello hello hello"`. + +```js +assert.equal(decompress("hello 1 1"), "hello hello hello"); +``` + +`decompress("the cat sat on 1 mat 4 which 1 2 3")` should return `"the cat sat on the mat on which the cat sat"`. + +```js +assert.equal(decompress("the cat sat on 1 mat 4 which 1 2 3"), "the cat sat on the mat on which the cat sat"); +``` + +`decompress("the more you know 1 2 3 realize 3 don't 4")` should return `"the more you know the more you realize you don't know"`. + +```js +assert.equal(decompress("the more you know 1 2 3 realize 3 don't 4"), "the more you know the more you realize you don't know"); +``` + +`decompress("lorem ipsum dolor sit per elit donec 4 nostra libero 5 7 ligula 4 gravida at 6 vitae a 6 sodales 7 en 7 16 3 nam 13 dignissim risus 16 13 5 27 2 2 15 23 6 5 2 13 23 15 5 21 4 16 27 1 4 5 10 23 2 6 4 21 4 30 6 30 2 6 16 15 18 23 29 27 4 18 sollicitudin 5 9 5 4 10")` should return `"lorem ipsum dolor sit per elit donec sit nostra libero per donec ligula sit gravida at elit vitae a elit sodales donec en donec at dolor nam ligula dignissim risus at ligula per nam ipsum ipsum gravida en elit per ipsum ligula en gravida per sodales sit at nam lorem sit per libero en ipsum elit sit sodales sit risus elit risus ipsum elit at gravida vitae en dignissim nam sit vitae sollicitudin per nostra per sit libero"`. + +```js +assert.equal(decompress("lorem ipsum dolor sit per elit donec 4 nostra libero 5 7 ligula 4 gravida at 6 vitae a 6 sodales 7 en 7 16 3 nam 13 dignissim risus 16 13 5 27 2 2 15 23 6 5 2 13 23 15 5 21 4 16 27 1 4 5 10 23 2 6 4 21 4 30 6 30 2 6 16 15 18 23 29 27 4 18 sollicitudin 5 9 5 4 10"), "lorem ipsum dolor sit per elit donec sit nostra libero per donec ligula sit gravida at elit vitae a elit sodales donec en donec at dolor nam ligula dignissim risus at ligula per nam ipsum ipsum gravida en elit per ipsum ligula en gravida per sodales sit at nam lorem sit per libero en ipsum elit sit sodales sit risus elit risus ipsum elit at gravida vitae en dignissim nam sit vitae sollicitudin per nostra per sit libero"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function decompress(str) { + + return str; +} +``` + +# --solutions-- + +```js +function decompress(str) { + const tokens = str.split(" "); + const words = []; + + for (const token of tokens) { + if (isNaN(parseInt(token))) { + words.push(token) + } else { + words.push(tokens[token - 1]) + } + } + + return words.join(" ") +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c5f3d787b1725d5f00c8bd.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c5f3d787b1725d5f00c8bd.md new file mode 100644 index 0000000000000000000000000000000000000000..1a306d972cb7ef7bcec81813a6ca774cdbd47b8d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c5f3d787b1725d5f00c8bd.md @@ -0,0 +1,103 @@ +--- +id: 69c5f3d787b1725d5f00c8bd +title: "Challenge 259: FizzBuzz Explosion" +challengeType: 28 +dashedName: challenge-259 +--- + +# --description-- + +Given an integer, return the number of steps it takes to turn the word `"fizzbuzz"` into a string with at least the given number of `"z"`'s using the following rules: + +- Start with the string `"fizzbuzz"`. +- Each step, apply the standard FizzBuzz rules using the letter position in the string (the first `"f"` is position 1). + - If the letter position is divisible by 3, replace the letter with `"fizz"` + - If it's divisible by 5, replace the letter with `"buzz"` + - If it's divisible by 3 and 5, replace the letter with `"fizzbuzz"` + +So after 1 step, `"fizzbuzz"` turns into `"fifizzzbuzzfizzzz"`, which has 9 `"z"`'s. + +# --hints-- + +`explodeFizzbuzz(9)` should return `1`. + +```js +assert.equal(explodeFizzbuzz(9), 1); +``` + +`explodeFizzbuzz(15)` should return `2`. + +```js +assert.equal(explodeFizzbuzz(15), 2); +``` + +`explodeFizzbuzz(51)` should return `3`. + +```js +assert.equal(explodeFizzbuzz(51), 3); +``` + +`explodeFizzbuzz(52)` should return `4`. + +```js +assert.equal(explodeFizzbuzz(52), 4); +``` + +`explodeFizzbuzz(359)` should return `5`. + +```js +assert.equal(explodeFizzbuzz(359), 5); +``` + +`explodeFizzbuzz(789)` should return `6`. + +```js +assert.equal(explodeFizzbuzz(789), 6); +``` + +`explodeFizzbuzz(54482)` should return `11`. + +```js +assert.equal(explodeFizzbuzz(54482), 11); +``` + +`explodeFizzbuzz(1000000)` should return `14`. + +```js +assert.equal(explodeFizzbuzz(1000000), 14); +``` + +# --seed-- + +## --seed-contents-- + +```js +function explodeFizzbuzz(targetZCount) { + + return targetZCount; +} +``` + +# --solutions-- + +```js +function explodeFizzbuzz(targetZCount) { + let str = "fizzbuzz"; + let steps = 0; + + while ((str.match(/z/g) || []).length < targetZCount) { + let next = ""; + for (let i = 0; i < str.length; i++) { + const pos = i + 1; + if (pos % 15 === 0) next += "fizzbuzz"; + else if (pos % 3 === 0) next += "fizz"; + else if (pos % 5 === 0) next += "buzz"; + else next += str[i]; + } + str = next; + steps++; + } + + return steps; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c6ff713a52713463aa7926.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c6ff713a52713463aa7926.md new file mode 100644 index 0000000000000000000000000000000000000000..dbe60a28025a7fc43a94f97645db9f5a6674cb07 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c6ff713a52713463aa7926.md @@ -0,0 +1,66 @@ +--- +id: 69c6ff713a52713463aa7926 +title: "Challenge 260: Word Score" +challengeType: 28 +dashedName: challenge-260 +--- + +# --description-- + +Given a word, return its score using a standard letter-value table: + +| Letter | Value | +| --- | --- | +| A | 1 | +| B | 2 | +| ... | ... | +| Z | 26 | + +- Upper and lowercase letters have the same value. + +# --hints-- + +`getWordScore("hi")` should return `17`. + +```js +assert.equal(getWordScore("hi"), 17); +``` + +`getWordScore("hello")` should return `52`. + +```js +assert.equal(getWordScore("hello"), 52); +``` + +`getWordScore("hippopotamus")` should return `169`. + +```js +assert.equal(getWordScore("hippopotamus"), 169); +``` + +`getWordScore("freeCodeCamp")` should return `94`. + +```js +assert.equal(getWordScore("freeCodeCamp"), 94); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getWordScore(word) { + + return word; +} +``` + +# --solutions-- + +```js +function getWordScore(word) { + return word.toLowerCase().split('').reduce((sum, char) => { + return sum + (char.charCodeAt(0) - 96); + }, 0); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c6ff713a52713463aa7927.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c6ff713a52713463aa7927.md new file mode 100644 index 0000000000000000000000000000000000000000..44288f40595a42642bfce94bdc8dbcc2917575df --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c6ff713a52713463aa7927.md @@ -0,0 +1,103 @@ +--- +id: 69c6ff713a52713463aa7927 +title: "Challenge 261: Number Words" +challengeType: 28 +dashedName: challenge-261 +--- + +# --description-- + +Given an integer from 0 to 99, return its English word representation. + +- `0` returns `"zero"`. +- Numbers 1-19 have unique names (`"one"`, `"two"`, ..., `"ten"`, `"eleven"`, ..., `"eighteen"`, `"nineteen"`). +- Multiples of 10 from 20-90 have their own names (`"twenty"`, `"thirty"`, ..., `"eighty"`, `"ninety"`). +- Numbers 21-99 that are not multiples of 10 are written as two words joined by a hyphen. For example `"forty-two"` and `"fifty-three"`. + +# --hints-- + +`getNumberWords(0)` should return `"zero"`. + +```js +assert.equal(getNumberWords(0), "zero"); +``` + +`getNumberWords(10)` should return `"ten"`. + +```js +assert.equal(getNumberWords(10), "ten"); +``` + +`getNumberWords(19)` should return `"nineteen"`. + +```js +assert.equal(getNumberWords(19), "nineteen"); +``` + +`getNumberWords(30)` should return `"thirty"`. + +```js +assert.equal(getNumberWords(30), "thirty"); +``` + +`getNumberWords(53)` should return `"fifty-three"`. + +```js +assert.equal(getNumberWords(53), "fifty-three"); +``` + +`getNumberWords(7)` should return `"seven"`. + +```js +assert.equal(getNumberWords(7), "seven"); +``` + +`getNumberWords(12)` should return `"twelve"`. + +```js +assert.equal(getNumberWords(12), "twelve"); +``` + +`getNumberWords(60)` should return `"sixty"`. + +```js +assert.equal(getNumberWords(60), "sixty"); +``` + +`getNumberWords(67)` should return `"sixty-seven"`. + +```js +assert.equal(getNumberWords(67), "sixty-seven"); +``` + +`getNumberWords(98)` should return `"ninety-eight"`. + +```js +assert.equal(getNumberWords(98), "ninety-eight"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getNumberWords(n) { + + return n; +} +``` + +# --solutions-- + +```js +function getNumberWords(n) { + const ones = ["zero","one","two","three","four","five","six","seven","eight","nine", + "ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen", + "seventeen","eighteen","nineteen"]; + const tens = ["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"]; + + if (n < 20) return ones[n]; + if (n % 10 === 0) return tens[Math.floor(n / 10)]; + return tens[Math.floor(n / 10)] + "-" + ones[n % 10]; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c6ff713a52713463aa7928.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c6ff713a52713463aa7928.md new file mode 100644 index 0000000000000000000000000000000000000000..25048dce2a0bb6ca267b5cd0b61f40906f07543b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c6ff713a52713463aa7928.md @@ -0,0 +1,73 @@ +--- +id: 69c6ff713a52713463aa7928 +title: "Challenge 262: URL Query Parser" +challengeType: 28 +dashedName: challenge-262 +--- + +# --description-- + +Given a URL that contains a query string, parse the query string into an object (or dictionary) of key-value pairs. + +- The query string begins after the `"?"`, +- each parameter is separated by `"&"`, +- each key/value pair is separated by `"="` + +For example, given `"https://example.com/search?name=Alice&age=30"`, return: + +```json +{ + "name": "Alice", + "age": "30" +} +``` + +All values should be returned as strings. + +# --hints-- + +`parseUrlQuery("https://example.com/search?name=Alice&age=30")` should return `{"name": "Alice", "age": "30"}` + +```js +assert.deepEqual(parseUrlQuery("https://example.com/search?name=Alice&age=30"), {"name": "Alice", "age": "30"}); +``` + +`parseUrlQuery("https://freecodecamp.org/learn?skill=programming&language=python")` should return `{"skill": "programming", "language": "python"}` + +```js +assert.deepEqual(parseUrlQuery("https://freecodecamp.org/learn?skill=programming&language=python"), {"skill": "programming", "language": "python"}); +``` + +`parseUrlQuery("https://freecodecamp.org/items?category=books&sort=asc&page=2")` should return `{"category": "books", "sort": "asc", "page": "2"}` + +```js +assert.deepEqual(parseUrlQuery("https://freecodecamp.org/items?category=books&sort=asc&page=2"), {"category": "books", "sort": "asc", "page": "2"}); +``` + +`parseUrlQuery("https://example.com?redirect=freecodecamp.org/learn&when=now")` should return `{"redirect": "freecodecamp.org/learn", "when": "now"}` + +```js +assert.deepEqual(parseUrlQuery("https://example.com?redirect=freecodecamp.org/learn&when=now"), {"redirect": "freecodecamp.org/learn", "when": "now"}); +``` + +# --seed-- + +## --seed-contents-- + +```js +function parseUrlQuery(url) { + + return url; +} +``` + +# --solutions-- + +```js +function parseUrlQuery(url) { + const queryString = url.split('?')[1]; + return Object.fromEntries( + queryString.split('&').map(param => param.split('=')) + ); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c6ff713a52713463aa7929.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c6ff713a52713463aa7929.md new file mode 100644 index 0000000000000000000000000000000000000000..a8034ebf61522c104d4121671e7f0e659df5d478 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69c6ff713a52713463aa7929.md @@ -0,0 +1,106 @@ +--- +id: 69c6ff713a52713463aa7929 +title: "Challenge 263: Binary Crossword" +challengeType: 28 +dashedName: challenge-263 +--- + +# --description-- + +Given a character, determine if its 8-bit binary representation can be found in the following grid, horizontally or vertically in either direction: + +```js +0 1 0 0 0 0 0 1 +0 1 1 0 1 1 1 1 +0 1 0 0 0 1 0 0 +0 1 1 0 0 1 0 1 +0 1 0 1 0 0 1 0 +0 1 0 1 0 1 0 0 +0 1 1 0 1 0 0 0 +1 0 1 0 1 1 1 0 +``` + +For example, `"A"` has the binary representation `01000001`, which appears in the first row from left to right. + +# --hints-- + +`isInCrossword("I")` should return `true`. + +```js +assert.isTrue(isInCrossword("I")); +``` + +`isInCrossword("D")` should return `true`. + +```js +assert.isTrue(isInCrossword("D")); +``` + +`isInCrossword("0")` should return `true`. + +```js +assert.isTrue(isInCrossword("0")); +``` + +`isInCrossword("u")` should return `true`. + +```js +assert.isTrue(isInCrossword("u")); +``` + +`isInCrossword("Y")` should return `false`. + +```js +assert.isFalse(isInCrossword("Y")); +``` + +`isInCrossword("p")` should return `false`. + +```js +assert.isFalse(isInCrossword("p")); +``` + +`isInCrossword("1")` should return `false`. + +```js +assert.isFalse(isInCrossword("1")); +``` + +`isInCrossword("Q")` should return `false`. + +```js +assert.isFalse(isInCrossword("Q")); +``` + +# --seed-- + +## --seed-contents-- + +```js +function isInCrossword(char) { + + return char; +} +``` + +# --solutions-- + +```js +function isInCrossword(char) { + const grid = [ + "01000001", + "01101111", + "01000100", + "01100101", + "01010010", + "01010100", + "01101000", + "10101110", + ]; + + const target = char.charCodeAt(0).toString(2).padStart(8, '0'); + const cols = Array.from({length: 8}, (_, c) => grid.map(r => r[c]).join('')); + + return [...grid, ...cols].some(seq => seq.includes(target) || seq.split('').reverse().join('').includes(target)); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69cfca90e8a0a6d4d6871c4e.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69cfca90e8a0a6d4d6871c4e.md new file mode 100644 index 0000000000000000000000000000000000000000..5275b40f7968703310f6ec27c796e049a20541dd --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69cfca90e8a0a6d4d6871c4e.md @@ -0,0 +1,76 @@ +--- +id: 69cfca90e8a0a6d4d6871c4e +title: "Challenge 264: Anagram Groups" +challengeType: 28 +dashedName: challenge-264 +--- + +# --description-- + +Given an array of words, return a 2d array of the words grouped into anagrams. + +- Words are anagrams if they contain the same letters in any order. +- Each word belongs to exactly one group. +- Return order doesn't matter. + +For example, given `["listen", "silent", "hello", "enlist", "world"]`, return `[["listen", "silent", "enlist"], ["hello"], ["world"]]`. + +# --hints-- + +`groupAnagrams(["listen", "silent", "hello", "enlist", "world"])` should return `[["listen", "silent", "enlist"], ["hello"], ["world"]]`. + +```js +const groups = groupAnagrams(["listen", "silent", "hello", "enlist", "world"]); +const sorted = groups.map(g => g.sort()).sort((a, b) => a[0].localeCompare(b[0])); +assert.deepEqual(sorted, [["enlist", "listen", "silent"], ["hello"], ["world"]]); +``` + +`groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"])` should return `[["ate", "eat", "tea"], ["bat"], ["nat", "tan"]]`. + +```js +const groups = groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]); +const sorted = groups.map(g => g.sort()).sort((a, b) => a[0].localeCompare(b[0])); +assert.deepEqual(sorted, [["ate", "eat", "tea"], ["bat"], ["nat", "tan"]]); +``` + +`groupAnagrams(["care", "race", "acre", "pots", "stop", "tops", "opts", "post", "spot", "evil", "vile", "live", "veil"])` should return `[["acre", "care", "race"], ["evil", "live", "veil", "vile"], ["opts", "post", "pots", "spot", "stop", "tops"]]`. + +```js +const groups = groupAnagrams(["care", "race", "acre", "pots", "stop", "tops", "opts", "post", "spot", "evil", "vile", "live", "veil"]); +const sorted = groups.map(g => g.sort()).sort((a, b) => a[0].localeCompare(b[0])); +assert.deepEqual(sorted, [["acre", "care", "race"], ["evil", "live", "veil", "vile"], ["opts", "post", "pots", "spot", "stop", "tops"]]); + +``` + +`groupAnagrams(["algorithms", "logarithms", "education", "cautioned", "auctioned", "triangle", "integral", "alerting", "relating"])` should return `[["alerting", "integral", "relating", "triangle"], ["algorithms", "logarithms"], ["auctioned", "cautioned", "education"]]`. + +```js +const groups = groupAnagrams(["algorithms", "logarithms", "education", "cautioned", "auctioned", "triangle", "integral", "alerting", "relating"]); +const sorted = groups.map(g => g.sort()).sort((a, b) => a[0].localeCompare(b[0])); +assert.deepEqual(sorted, [["alerting", "integral", "relating", "triangle"], ["algorithms", "logarithms"], ["auctioned", "cautioned", "education"]]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function groupAnagrams(words) { + + return words; +} +``` + +# --solutions-- + +```js +function groupAnagrams(words) { + const map = {}; + for (const word of words) { + const key = word.split('').sort().join(''); + if (!map[key]) map[key] = []; + map[key].push(word); + } + return Object.values(map); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69cfca90e8a0a6d4d6871c4f.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69cfca90e8a0a6d4d6871c4f.md new file mode 100644 index 0000000000000000000000000000000000000000..6b7b5249f1f27f893d965eaa1852c3ca40852d8a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69cfca90e8a0a6d4d6871c4f.md @@ -0,0 +1,83 @@ +--- +id: 69cfca90e8a0a6d4d6871c4f +title: "Challenge 265: Deepest Brackets" +challengeType: 28 +dashedName: challenge-265 +--- + +# --description-- + +Given a string containing balanced brackets, return the content of the deepest nested brackets. + +- Brackets can be any of the three types: `()`, `[]`, and `{}`. +- The input will always have a single deepest group. + +For example, given `"(hello (world))"`, return `"world"`. + +# --hints-- + +`getDeepestBrackets("(hello (world))")` should return `"world"`. + +```js +assert.equal(getDeepestBrackets("(hello (world))"), "world"); +``` + +`getDeepestBrackets("[outer [inner] outer]")` should return `"inner"`. + +```js +assert.equal(getDeepestBrackets("[outer [inner] outer]"), "inner"); +``` + +`getDeepestBrackets("{a{b}c{d{e}f}g}")` should return `"e"`. + +```js +assert.equal(getDeepestBrackets("{a{b}c{d{e}f}g}"), "e"); +``` + +`getDeepestBrackets("[the {quick (brown [fox] jumped) over (the) lazy} dog]")` should return `"fox"`. + +```js +assert.equal(getDeepestBrackets("[the {quick (brown [fox] jumped) over (the) lazy} dog]"), "fox"); +``` + +`getDeepestBrackets("f[(r)e{e}C{o[(d){e(C)}a]m}]p")` should return `"C"`. + +```js +assert.equal(getDeepestBrackets("f[(r)e{e}C{o[(d){e(C)}a]m}]p"), "C"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getDeepestBrackets(str) { + + return str; +} +``` + +# --solutions-- + +```js +function getDeepestBrackets(str) { + let maxDepth = 0, depth = 0, content = ''; + let start = 0; + + for (let i = 0; i < str.length; i++) { + if ('([{'.includes(str[i])) { + depth++; + if (depth > maxDepth) { + maxDepth = depth; + start = i + 1; + } + } else if (')]}'.includes(str[i])) { + if (depth === maxDepth) { + content = str.slice(start, i); + } + depth--; + } + } + return content; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69cfca90e8a0a6d4d6871c50.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69cfca90e8a0a6d4d6871c50.md new file mode 100644 index 0000000000000000000000000000000000000000..5a7cfc23ca4059c52e0a69f88b8214a4242f6878 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69cfca90e8a0a6d4d6871c50.md @@ -0,0 +1,72 @@ +--- +id: 69cfca90e8a0a6d4d6871c50 +title: "Challenge 266: Good Day" +challengeType: 28 +dashedName: challenge-266 +--- + +# --description-- + +Given a time string in `"HH:MM"` format (24-hour clock), return: + +- `"Good morning"` for times `05:00` to `11:59` +- `"Good afternoon"` for times `12:00` to `17:59` +- `"Good evening"` for times `18:00` to `21:59` +- `"Good night"` for times `22:00` to `04:59` + +# --hints-- + +`getGreeting("06:30")` should return `"Good morning"`. + +```js +assert.equal(getGreeting("06:30"), "Good morning"); +``` + +`getGreeting("12:00")` should return `"Good afternoon"`. + +```js +assert.equal(getGreeting("12:00"), "Good afternoon"); +``` + +`getGreeting("21:59")` should return `"Good evening"`. + +```js +assert.equal(getGreeting("21:59"), "Good evening"); +``` + +`getGreeting("00:01")` should return `"Good night"`. + +```js +assert.equal(getGreeting("00:01"), "Good night"); +``` + +`getGreeting("11:30")` should return `"Good morning"`. + +```js +assert.equal(getGreeting("11:30"), "Good morning"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getGreeting(time) { + + return time; +} +``` + +# --solutions-- + +```js +function getGreeting(time) { + const [hours, minutes] = time.split(':').map(Number); + const total = hours * 60 + minutes; + + if (total >= 300 && total < 720) return 'Good morning'; + if (total >= 720 && total < 1080) return 'Good afternoon'; + if (total >= 1080 && total < 1320) return 'Good evening'; + return 'Good night'; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69cfca90e8a0a6d4d6871c51.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69cfca90e8a0a6d4d6871c51.md new file mode 100644 index 0000000000000000000000000000000000000000..a6fbfc286b4f81749e8471da7e4298119f0c1ad7 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69cfca90e8a0a6d4d6871c51.md @@ -0,0 +1,82 @@ +--- +id: 69cfca90e8a0a6d4d6871c51 +title: "Challenge 267: Parsec Converter" +challengeType: 28 +dashedName: challenge-267 +--- + +# --description-- + +In a distant galaxy, parsecs are used to measure both time and distance. Given an integer number of parsecs, return its equivalent in time or distance. + +- If the given integer is odd, it represents time. If it's even, it represents distance. + +Use these conversion rates: + +| Parsecs | Time/Distance | +| - | - | +| 1 | 2 hours | +| 2 | 6 light years | + +Return the converted value as an integer. + +# --hints-- + +`convertParsecs(1)` should return `2`. + +```js +assert.equal(convertParsecs(1), 2); +``` + +`convertParsecs(2)` should return `6`. + +```js +assert.equal(convertParsecs(2), 6); +``` + +`convertParsecs(31)` should return `62`. + +```js +assert.equal(convertParsecs(31), 62); +``` + +`convertParsecs(88)` should return `264`. + +```js +assert.equal(convertParsecs(88), 264); +``` + +`convertParsecs(17)` should return `34`. + +```js +assert.equal(convertParsecs(17), 34); +``` + +`convertParsecs(14)` should return `42`. + +```js +assert.equal(convertParsecs(14), 42); +``` + +# --seed-- + +## --seed-contents-- + +```js +function convertParsecs(parsecs) { + + return parsecs; +} +``` + +# --solutions-- + +```js +function convertParsecs(parsecs) { + if (parsecs % 2 !== 0) { + return parsecs * 2; + } else { + return parsecs * 3; + } +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69cfca90e8a0a6d4d6871c52.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69cfca90e8a0a6d4d6871c52.md new file mode 100644 index 0000000000000000000000000000000000000000..f80e52ab5e45aeb88e855e5fd9851f0f383b88e0 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69cfca90e8a0a6d4d6871c52.md @@ -0,0 +1,86 @@ +--- +id: 69cfca90e8a0a6d4d6871c52 +title: "Challenge 268: Narcissistic Number" +challengeType: 28 +dashedName: challenge-268 +--- + +# --description-- + +Given a positive integer, determine whether it is a narcissistic number. + +- A number is narcissistic if the sum of each of its digits raised to the power of the total number of digits equals the number itself. + +For example, 153 has 3 digits, and 13 + 53 + 33 = 153, so it is narcissistic. + +# --hints-- + +`isNarcissistic(153)` should return `true`. + +```js +assert.isTrue(isNarcissistic(153)); +``` + +`isNarcissistic(154)` should return `false`. + +```js +assert.isFalse(isNarcissistic(154)); +``` + +`isNarcissistic(371)` should return `true`. + +```js +assert.isTrue(isNarcissistic(371)); +``` + +`isNarcissistic(512)` should return `false`. + +```js +assert.isFalse(isNarcissistic(512)); +``` + +`isNarcissistic(9)` should return `true`. + +```js +assert.isTrue(isNarcissistic(9)); +``` + +`isNarcissistic(11)` should return `false`. + +```js +assert.isFalse(isNarcissistic(11)); +``` + +`isNarcissistic(9474)` should return `true`. + +```js +assert.isTrue(isNarcissistic(9474)); +``` + +`isNarcissistic(6549)` should return `false`. + +```js +assert.isFalse(isNarcissistic(6549)); +``` + +# --seed-- + +## --seed-contents-- + +```js +function isNarcissistic(n) { + + return n; +} +``` + +# --solutions-- + +```js +function isNarcissistic(n) { + const digits = String(n).split(''); + const power = digits.length; + const sum = digits.reduce((acc, d) => acc + Math.pow(Number(d), power), 0); + return sum === n; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69cfca90e8a0a6d4d6871c53.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69cfca90e8a0a6d4d6871c53.md new file mode 100644 index 0000000000000000000000000000000000000000..0dff189426170ebaf43cb5af0efdfc35f2a166e8 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69cfca90e8a0a6d4d6871c53.md @@ -0,0 +1,63 @@ +--- +id: 69cfca90e8a0a6d4d6871c53 +title: "Challenge 269: Allergen Friendly Meals" +challengeType: 28 +dashedName: challenge-269 +--- + +# --description-- + +Given an array of meals and an array of allergens to avoid, return the names of all the meals that contain none of the given allergens. + +- Each meal is in the format `[meal, allergens]`, where `meal` is the name of the meal, and `allergens` is an array of the allergens the meal contains. For example, `["pasta", ["wheat", "milk"]]`. +- Allergens to avoid will be an array of strings. + +Return safe meal names in the same order given. If no meal is safe, return an empty array. + +# --hints-- + +`getAllergenFriendlyMeals([["pasta", ["wheat", "milk"]], ["salad", ["nuts"]]], ["milk"])` should return `["salad"]`. + +```js +assert.deepEqual(getAllergenFriendlyMeals([["pasta", ["wheat", "milk"]], ["salad", ["nuts"]]], ["milk"]), ["salad"]); +``` + +`getAllergenFriendlyMeals([["steak", ["soy"]], ["fried rice", []], ["fish tacos", ["fish", "wheat"]], ["chicken parmesan", ["wheat", "milk"]]], ["soy", "fish"])` should return `["fried rice", "chicken parmesan"]`. + +```js +assert.deepEqual(getAllergenFriendlyMeals([["steak", ["soy"]], ["fried rice", []], ["fish tacos", ["fish", "wheat"]], ["chicken parmesan", ["wheat", "milk"]]], ["soy", "fish"]), ["fried rice", "chicken parmesan"]); +``` + +`getAllergenFriendlyMeals([["oatmeal", ["nuts"]], ["pancakes", ["wheat", "milk"]], ["granola", []], ["yogurt", ["milk"]], ["eggs", ["eggs", "milk"]], ["toast", ["wheat"]]], ["eggs", "milk"])` should return `["oatmeal", "granola", "toast"]`. + +```js +assert.deepEqual(getAllergenFriendlyMeals([["oatmeal", ["nuts"]], ["pancakes", ["wheat", "milk"]], ["granola", []], ["yogurt", ["milk"]], ["eggs", ["eggs", "milk"]], ["toast", ["wheat"]]], ["eggs", "milk"]), ["oatmeal", "granola", "toast"]); +``` + +`getAllergenFriendlyMeals([["oatmeal", ["nuts"]], ["pancakes", ["wheat", "milk"]], ["granola", []], ["yogurt", ["milk"]], ["eggs", ["eggs", "milk"]], ["toast", ["wheat"]]], ["wheat", "nuts"])` should return `["granola", "yogurt", "eggs"]`. + +```js +assert.deepEqual(getAllergenFriendlyMeals([["oatmeal", ["nuts"]], ["pancakes", ["wheat", "milk"]], ["granola", []], ["yogurt", ["milk"]], ["eggs", ["eggs", "milk"]], ["toast", ["wheat"]]], ["wheat", "nuts"]), ["granola", "yogurt", "eggs"]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getAllergenFriendlyMeals(meals, allergens) { + + return meals; +} +``` + +# --solutions-- + +```js +function getAllergenFriendlyMeals(meals, allergens) { + return meals + .filter(([name, mealAllergens]) => + !allergens.some(a => mealAllergens.includes(a))) + .map(([name]) => name); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69cfca90e8a0a6d4d6871c54.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69cfca90e8a0a6d4d6871c54.md new file mode 100644 index 0000000000000000000000000000000000000000..09d0014e6cdd19ff27d118c0bb13f60f390afc16 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69cfca90e8a0a6d4d6871c54.md @@ -0,0 +1,74 @@ +--- +id: 69cfca90e8a0a6d4d6871c54 +title: "Challenge 270: Longest Common Substring" +challengeType: 28 +dashedName: challenge-270 +--- + +# --description-- + +Given a string, return the longest substring that appears more than once. + +- The substrings can overlap. + +# --hints-- + +`getLongestSubstring("abracadabra")` should return `"abra"`. + +```js +assert.equal(getLongestSubstring("abracadabra"), "abra"); +``` + +`getLongestSubstring("hello world hello")` should return `"hello"`. + +```js +assert.equal(getLongestSubstring("hello world hello"), "hello"); +``` + +`getLongestSubstring("mississippi")` should return `"issi"`. + +```js +assert.equal(getLongestSubstring("mississippi"), "issi"); +``` + +`getLongestSubstring("ha ha ha ha ha ha ha")` should return `"ha ha ha ha ha ha"`. + +```js +assert.equal(getLongestSubstring("ha ha ha ha ha ha ha"), "ha ha ha ha ha ha"); +``` + +`getLongestSubstring("the quick brown fox jumped over the lazy dog that the quick brown fox jumped over")` should return `"the quick brown fox jumped over"`. + +```js +assert.equal(getLongestSubstring("the quick brown fox jumped over the lazy dog that the quick brown fox jumped over"), "the quick brown fox jumped over"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getLongestSubstring(str) { + + return str; +} +``` + +# --solutions-- + +```js +function getLongestSubstring(str) { + let longest = ''; + + for (let len = str.length - 1; len >= 1; len--) { + for (let i = 0; i <= str.length - len; i++) { + const sub = str.slice(i, i + len); + if (str.indexOf(sub) !== str.lastIndexOf(sub)) { + return sub; + } + } + } + + return longest; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69d03e549613fbdbe21d11e0.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69d03e549613fbdbe21d11e0.md new file mode 100644 index 0000000000000000000000000000000000000000..997fd5b1077f9107c20ac8fc3b6eb5e85c8ff9d3 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69d03e549613fbdbe21d11e0.md @@ -0,0 +1,118 @@ +--- +id: 69d03e549613fbdbe21d11e0 +title: "Challenge 271: Medication Reminder" +challengeType: 28 +dashedName: challenge-271 +--- + +# --description-- + +Given an array of medications and a string representing the current time, return the next medication you need to take and how long until you need to take it. + +- Each medication is in the format `[name, lastTaken]`, where `name` is the name of the medication and `lastTaken` is the time it was last taken. +- All given times will be in `"HH:MM"` (24-hour) format. + +Use the following medication schedule: + +| Name | Schedule | +| - | - | +| Deployxitrin | 08:00, 16:00 | +| Debuggamanizole | 07:00, 13:00, 21:00 | +| Mergeflictamine | every 4 hours | + +Return a string in the format `"{name} in Hh Mm"`. For example, `"Debuggamanizole in 2h 0m"` or `"Deployxitrin in 1h 5m"`. + +# --hints-- + +`medicationReminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "07:00"], ["Mergeflictamine", "10:00"]], "11:00")` should return `"Debuggamanizole in 2h 0m"`. + +```js +assert.equal(medicationReminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "07:00"], ["Mergeflictamine", "10:00"]], "11:00"), "Debuggamanizole in 2h 0m"); +``` + +`medicationReminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "13:00"], ["Mergeflictamine", "14:00"]], "14:55")` should return `"Deployxitrin in 1h 5m"`. + +```js +assert.equal(medicationReminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "13:00"], ["Mergeflictamine", "14:00"]], "14:55"), "Deployxitrin in 1h 5m"); +``` + +`medicationReminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "13:00"], ["Mergeflictamine", "14:00"]], "17:15")` should return `"Mergeflictamine in 0h 45m"`. + +```js +assert.equal(medicationReminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "13:00"], ["Mergeflictamine", "14:00"]], "17:15"), "Mergeflictamine in 0h 45m"); +``` + +`medicationReminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "07:00"], ["Mergeflictamine", "09:00"]], "12:59")` should return `"Debuggamanizole in 0h 1m"`. + +```js +assert.equal(medicationReminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "07:00"], ["Mergeflictamine", "09:00"]], "12:59"), "Debuggamanizole in 0h 1m"); +``` + +`medicationReminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "21:00"], ["Mergeflictamine", "03:00"]], "06:55")` should return `"Debuggamanizole in 0h 5m"`. + +```js +assert.equal(medicationReminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "21:00"], ["Mergeflictamine", "03:00"]], "06:55"), "Debuggamanizole in 0h 5m"); +``` + +`medicationReminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "07:00"], ["Mergeflictamine", "07:30"]], "08:00")` should return `"Mergeflictamine in 3h 30m"`. + +```js +assert.equal(medicationReminder([["Deployxitrin", "08:00"], ["Debuggamanizole", "07:00"], ["Mergeflictamine", "07:30"]], "08:00"), "Mergeflictamine in 3h 30m"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function medicationReminder(medications, currentTime) { + + return medications; +} +``` + +# --solutions-- + +```js +function medicationReminder(medications, currentTime) { + const schedule = { + Deployxitrin: { type: 'fixed', times: ['08:00', '16:00'] }, + Debuggamanizole: { type: 'fixed', times: ['07:00', '13:00', '21:00'] }, + Mergeflictamine: { type: 'interval', hours: 4 } + }; + + const toMinutes = t => { + const [h, m] = t.split(':').map(Number); + return h * 60 + m; + }; + + const current = toMinutes(currentTime); + let earliest = Infinity; + let nextMed = ''; + + for (const [name, lastTaken] of medications) { + const med = schedule[name]; + let nextDue; + + if (med.type === 'fixed') { + const futureTimes = med.times + .map(toMinutes) + .filter(t => t > current); + if (futureTimes.length === 0) continue; + nextDue = Math.min(...futureTimes); + } else { + nextDue = toMinutes(lastTaken) + med.hours * 60; + } + + const diff = nextDue - current; + if (diff > 0 && diff < earliest) { + earliest = diff; + nextMed = name; + } + } + + const h = Math.floor(earliest / 60); + const m = earliest % 60; + return `${nextMed} in ${h}h ${m}m`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69e2383af7832c8032603b8e.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69e2383af7832c8032603b8e.md new file mode 100644 index 0000000000000000000000000000000000000000..ec03b5035699bc780a96f074f11a0f0f72bebf5c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69e2383af7832c8032603b8e.md @@ -0,0 +1,83 @@ +--- +id: 69e2383af7832c8032603b8e +title: "Challenge 272: Transposed Matrix" +challengeType: 28 +dashedName: challenge-272 +--- + +# --description-- + +Given a matrix (an array of arrays), return the transposed version of it. + +To transpose the matrix, swap the rows and columns. E.g: a value at index `[0, 1]` should move to index `[1, 0]`. + +For example, given: + +```json +[ + [1, 2, 3], + [4, 5, 6] +] +``` + +Return: + +```json +[ + [1, 4], + [2, 5], + [3, 6] +] +``` + +# --hints-- + +`transpose([[1, 2, 3], [4, 5, 6]])` should return `[[1, 4], [2, 5], [3, 6]]`. + +```js +assert.deepEqual(transpose([[1, 2, 3], [4, 5, 6]]), [[1, 4], [2, 5], [3, 6]]); +``` + +`transpose([[1, 2], [3, 4], [5, 6]])` should return `[[1, 3, 5], [2, 4, 6]]`. + +```js +assert.deepEqual(transpose([[1, 2], [3, 4], [5, 6]]), [[1, 3, 5], [2, 4, 6]]); +``` + +`transpose([[1, 2], [3, 4], [5, 6], [7, 8]])` should return `[[1, 3, 5, 7], [2, 4, 6, 8]]`. + +```js +assert.deepEqual(transpose([[1, 2], [3, 4], [5, 6], [7, 8]]), [[1, 3, 5, 7], [2, 4, 6, 8]]); +``` + +`transpose([["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"], ["j", "k", "l"]])` should return `[["a", "d", "g", "j"], ["b", "e", "h", "k"], ["c", "f", "i", "l"]]`. + +```js +assert.deepEqual(transpose([["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"], ["j", "k", "l"]]), [["a", "d", "g", "j"], ["b", "e", "h", "k"], ["c", "f", "i", "l"]]); +``` + +`transpose([[true, false, true, false], [false, true, false, true], [true, true, false, false], [false, false, true, true], [true, false, false, true]])` should return `[[true, false, true, false, true], [false, true, true, false, false], [true, false, false, true, false], [false, true, false, true, true]]`. + +```js +assert.deepEqual(transpose([[true, false, true, false], [false, true, false, true], [true, true, false, false], [false, false, true, true], [true, false, false, true]]), [[true, false, true, false, true], [false, true, true, false, false], [true, false, false, true, false], [false, true, false, true, true]]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function transpose(matrix) { + + return matrix; +} +``` + +# --solutions-- + +```js +function transpose(matrix) { + + return matrix[0].map((_, i) => matrix.map(row => row[i])); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69e2383af7832c8032603b8f.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69e2383af7832c8032603b8f.md new file mode 100644 index 0000000000000000000000000000000000000000..2b0237683950d2f59df21cad93f150f0eca940f4 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69e2383af7832c8032603b8f.md @@ -0,0 +1,72 @@ +--- +id: 69e2383af7832c8032603b8f +title: "Challenge 273: ISBN-13 Validator" +challengeType: 28 +dashedName: challenge-273 +--- + +# --description-- + +Given a string, determine if it is a valid ISBN-13 number. + +A valid ISBN-13: + +- Contains only digits and hyphens +- Has exactly 13 digits after removing hyphens +- Passes the following check: + 1. Multiply each digit by 1 or 3, alternating (multiply the first digit by 1, the second by 3, the third by 1, and so on). + 2. The sum of the results must be divisible by 10. + +# --hints-- + +`isValidIsbn13("9780306406157")` should return `true`. + +```js +assert.isTrue(isValidIsbn13("9780306406157")); +``` + +`isValidIsbn13("97803064061570")` should return `false`. + +```js +assert.isFalse(isValidIsbn13("97803064061570")); +``` + +`isValidIsbn13("978-0-13-595705-9")` should return `true`. + +```js +assert.isTrue(isValidIsbn13("978-0-13-595705-9")); +``` + +`isValidIsbn13("978-030-64061A-4")` should return `false`. + +```js +assert.isFalse(isValidIsbn13("978-030-64061A-4")); +``` + +`isValidIsbn13("9-7-8-0-1-3-4-7-5-7-5-9-9")` should return `true`. + +```js +assert.isTrue(isValidIsbn13("9-7-8-0-1-3-4-7-5-7-5-9-9")); +``` + +# --seed-- + +## --seed-contents-- + +```js +function isValidIsbn13(str) { + + return str; +} +``` + +# --solutions-- + +```js +function isValidIsbn13(str) { + const digits = str.replace(/-/g, ''); + if (!/^\d{13}$/.test(digits)) return false; + const sum = digits.split('').reduce((acc, d, i) => acc + d * (i % 2 === 0 ? 1 : 3), 0); + return sum % 10 === 0; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69e2383af7832c8032603b90.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69e2383af7832c8032603b90.md new file mode 100644 index 0000000000000000000000000000000000000000..1409a4cebb44963fc2147e9cb638d9d166157bf7 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69e2383af7832c8032603b90.md @@ -0,0 +1,58 @@ +--- +id: 69e2383af7832c8032603b90 +title: "Challenge 274: Oldest Person" +challengeType: 28 +dashedName: challenge-274 +--- + +# --description-- + +Given an array of objects, each with a `"name"` and `"age"` property, return an array containing the name of the oldest person. + +If multiple people share the oldest age, return all of their names in the order they appear in the input. + +# --hints-- + +`getOldest([{ name: "Brenda", age: 40 }])` should return `["Brenda"]`. + +```js +assert.deepEqual(getOldest([{ name: "Brenda", age: 40 }]), ["Brenda"]); +``` + +`getOldest([{ name: "Alice", age: 30 }, { name: "Bob", age: 25 }])` should return `["Alice"]`. + +```js +assert.deepEqual(getOldest([{ name: "Alice", age: 30 }, { name: "Bob", age: 25 }]), ["Alice"]); +``` + +`getOldest([{ name: "Allison", age: 25 }, { name: "Bill", age: 30 }, { name: "Carol", age: 30 }])` should return `["Bill", "Carol"]`. + +```js +assert.deepEqual(getOldest([{ name: "Allison", age: 25 }, { name: "Bill", age: 30 }, { name: "Carol", age: 30 }]), ["Bill", "Carol"]); +``` + +`getOldest([{ name: "George", age: 50 }, { name: "Shirley", age: 42 }, { name: "Beth", age: 48 }, { name: "Holly", age: 50 }, { name: "Kevin", age: 44 }, { name: "Frank", age: 47 }, { name: "Zach", age: 50 }, { name: "Jennifer", age: 43 }])` should return `["George", "Holly", "Zach"]`. + +```js +assert.deepEqual(getOldest([{ name: "George", age: 50 }, { name: "Shirley", age: 42 }, { name: "Beth", age: 48 }, { name: "Holly", age: 50 }, { name: "Kevin", age: 44 }, { name: "Frank", age: 47 }, { name: "Zach", age: 50 }, { name: "Jennifer", age: 43 }]), ["George", "Holly", "Zach"]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getOldest(people) { + + return people; +} +``` + +# --solutions-- + +```js +function getOldest(people) { + const maxAge = Math.max(...people.map(p => p.age)); + return people.filter(p => p.age === maxAge).map(p => p.name); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69e2383af7832c8032603b91.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69e2383af7832c8032603b91.md new file mode 100644 index 0000000000000000000000000000000000000000..ce4eb7fc39c71eab68da24adae0b763db29e76e0 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69e2383af7832c8032603b91.md @@ -0,0 +1,64 @@ +--- +id: 69e2383af7832c8032603b91 +title: "Challenge 275: Character Frequency" +challengeType: 28 +dashedName: challenge-275 +--- + +# --description-- + +Given a string, return an object (JavaScript) or dictionary (Python) mapping each character to the number of times it appears. + +# --hints-- + +`getFrequency("test")` should return `{t: 2, e: 1, s: 1}`. + +```js +assert.deepEqual(getFrequency("test"), {t: 2, e: 1, s: 1}); +``` + +`getFrequency("mississippi")` should return `{m: 1, i: 4, s: 4, p: 2}`. + +```js +assert.deepEqual(getFrequency("mississippi"), {m: 1, i: 4, s: 4, p: 2}); +``` + +`getFrequency("hello world")` should return `{h: 1, e: 1, l: 3, o: 2, " ": 1, w: 1, r: 1, d: 1}`. + +```js +assert.deepEqual(getFrequency("hello world"), {h: 1, e: 1, l: 3, o: 2, " ": 1, w: 1, r: 1, d: 1}); +``` + +`getFrequency("She sells seashells by the seashore.")` should return `{S: 1, h: 4, e: 7, " ": 5, s: 7, l: 4, a: 2, b: 1, y: 1, t: 1, o: 1, r: 1, ".": 1}`. + +```js +assert.deepEqual(getFrequency("She sells seashells by the seashore."), {S: 1, h: 4, e: 7, " ": 5, s: 7, l: 4, a: 2, b: 1, y: 1, t: 1, o: 1, r: 1, ".": 1}); +``` + +`getFrequency("The quick brown fox jumps over the lazy dog.")` should return `{T: 1, h: 2, e: 3, " ": 8, q: 1, u: 2, i: 1, c: 1, k: 1, b: 1, r: 2, o: 4, w: 1, n: 1, f: 1, x: 1, j: 1, m: 1, p: 1, s: 1, v: 1, t: 1, l: 1, a: 1, z: 1, y: 1, d: 1, g: 1, ".": 1}`. + +```js +assert.deepEqual(getFrequency("The quick brown fox jumps over the lazy dog."), {T: 1, h: 2, e: 3, " ": 8, q: 1, u: 2, i: 1, c: 1, k: 1, b: 1, r: 2, o: 4, w: 1, n: 1, f: 1, x: 1, j: 1, m: 1, p: 1, s: 1, v: 1, t: 1, l: 1, a: 1, z: 1, y: 1, d: 1, g: 1, ".": 1}); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getFrequency(str) { + + return str; +} +``` + +# --solutions-- + +```js +function getFrequency(str) { + return str.split('').reduce((acc, char) => { + acc[char] = (acc[char] || 0) + 1; + return acc; + }, {}); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69e2383af7832c8032603b92.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69e2383af7832c8032603b92.md new file mode 100644 index 0000000000000000000000000000000000000000..45d430454b03d88cf994ded44dd13b621fb9c4b5 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69e2383af7832c8032603b92.md @@ -0,0 +1,66 @@ +--- +id: 69e2383af7832c8032603b92 +title: "Challenge 276: Offending Element" +challengeType: 28 +dashedName: challenge-276 +--- + +# --description-- + +Given an array of integers that is sorted in ascending order except for one out-of-place element, return the index of that element. + +- If more than one element could be considered out of place, return the index of the first one. + +# --hints-- + +`findOffender([1, 6, 2, 3, 4, 5])` should return `1`. + +```js +assert.equal(findOffender([1, 6, 2, 3, 4, 5]), 1); +``` + +`findOffender([1, 2, 3, 5, 4, 5])` should return `3`. + +```js +assert.equal(findOffender([1, 2, 3, 5, 4, 5]), 3); +``` + +`findOffender([2, 1])` should return `0`. + +```js +assert.equal(findOffender([2, 1]), 0); +``` + +`findOffender([2, 4, 1, 6, 8])` should return `2`. + +```js +assert.equal(findOffender([2, 4, 1, 6, 8]), 2); +``` + +`findOffender([5, 18, 24, 33, 40, 55, 15, 68, 84, 91])` should return `6`. + +```js +assert.equal(findOffender([5, 18, 24, 33, 40, 55, 15, 68, 84, 91]), 6); +``` + +# --seed-- + +## --seed-contents-- + +```js +function findOffender(arr) { + + return arr; +} +``` + +# --solutions-- + +```js +function findOffender(arr) { + for (let i = 0; i < arr.length; i++) { + const without = [...arr.slice(0, i), ...arr.slice(i + 1)]; + if (without.every((n, j) => j === 0 || without[j - 1] <= n)) return i; + } +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69e2383af7832c8032603b93.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69e2383af7832c8032603b93.md new file mode 100644 index 0000000000000000000000000000000000000000..c8113ca5cbdf96661a51660e3de25b27177cf013 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69e2383af7832c8032603b93.md @@ -0,0 +1,110 @@ +--- +id: 69e2383af7832c8032603b93 +title: "Challenge 277: Mirror Image" +challengeType: 28 +dashedName: challenge-277 +--- + +# --description-- + +Given two strings, determine if the second string is a mirror image of the first. + +A mirror image is formed by reversing the string and replacing each character with its mirror equivalent. + +- Symmetric characters look like themselves in a mirror: + +`W`, `T`, `Y`, `U`, `I`, `O`, `H`, `A`, `X`, `V`, `M`, `w`, `o`, `x`, `v`, `0`, `8`, `=`, `+`, `:`, `|`, `-`, `_`, `*`, `^`, `!`, `.`, and the space (` `). + +- Mirrored pairs swap with each other in a mirror: + +| Character | Swaps with | +| - | - | +| `[` | `]` | +| `{` | `}` | +| `<` | `>` | +| `b` | `d` | +| `p` | `q` | +| `(` | `)` | + +If either string includes a character not in the lists above, it doesn't have mirror image that can be created from the characters. + +For example, the mirrored image of `"[HOW]"` is `"[WOH]"`. + +# --hints-- + +`isMirrorImage("[HOW]", "[WOH]")` should return `true`. + +```js +assert.isTrue(isMirrorImage("[HOW]", "[WOH]")); +``` + +`isMirrorImage("MOM", "MOM")` should return `true`. + +```js +assert.isTrue(isMirrorImage("MOM", "MOM")); +``` + +`isMirrorImage("vow", "wov")` should return `true`. + +```js +assert.isTrue(isMirrorImage("vow", "wov")); +``` + +`isMirrorImage("TIM", "TIM")` should return `false`. + +```js +assert.isFalse(isMirrorImage("TIM", "TIM")); +``` + +`isMirrorImage("{WOW}", "}WOW{")` should return `false`. + +```js +assert.isFalse(isMirrorImage("{WOW}", "}WOW{")); +``` + +`isMirrorImage("XXVII", "IIV%X")` should return `false`. + +```js +assert.isFalse(isMirrorImage("XXVII", "IIV%X")); +``` + +`isMirrorImage("><(((*>", "<*)))><")` should return `true`. + +```js +assert.isTrue(isMirrorImage("><(((*>", "<*)))><")); +``` + +`isMirrorImage("WTYUIOHAXVMwoxv08=+:|-_*^!.[]{}<>bdpq()", "()pqbd<>{}[].!^*_-|:+=80vxowMVXAHOIUYTW")` should return `true`. + +```js +assert.isTrue(isMirrorImage("WTYUIOHAXVMwoxv08=+:|-_*^!.[]{}<>bdpq()", "()pqbd<>{}[].!^*_-|:+=80vxowMVXAHOIUYTW")); +``` + +# --seed-- + +## --seed-contents-- + +```js +function isMirrorImage(str1, str2) { + + return str1; +} +``` + +# --solutions-- + +```js +function isMirrorImage(str1, str2) { + const symmetric = new Set('WTYUIOHA XVMwoxv08=+:|-_*^!.'); + const pairs = { '[': ']', ']': '[', '{': '}', '}': '{', '<': '>', '>': '<', 'b': 'd', 'd': 'b', 'p': 'q', 'q': 'p', '(': ')', ')': '(' }; + + const mirrored = str1.split('').reverse().map(c => { + if (symmetric.has(c)) return c; + if (pairs[c]) return pairs[c]; + return null; + }); + + if (mirrored.includes(null)) return false; + return mirrored.join('') === str2; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69e2383af7832c8032603b94.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69e2383af7832c8032603b94.md new file mode 100644 index 0000000000000000000000000000000000000000..86f699ec73bfa5f7147405285adcf0bdabeae501 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69e2383af7832c8032603b94.md @@ -0,0 +1,95 @@ +--- +id: 69e2383af7832c8032603b94 +title: "Challenge 278: Coffee Order Parser" +challengeType: 28 +dashedName: challenge-278 +--- + +# --description-- + +Given a string for a coffee order, identify any menu items and return a formatted order. + +Use the following menu items and prices: + +| Item | Price | +| - | - | +| `"cold brew"` | $4.50 | +| `"oat latte"` | $5.00 | +| `"cappuccino"` | $4.75 | +| `"espresso"` | $3.00 | +| `"vanilla syrup"` | $0.75 | +| `"caramel drizzle"` | $0.60 | +| `"extra shot"` | $0.50 | +| `"oat milk"` | $0.75 | +| `"cream"` | $0.75 | + +Return a string with the matched items joined by `" + "`, followed by a colon and space (`": "`), and the total price. + +For example, given `"I'd like an oat latte with vanilla syrup and an extra shot please."`, return `"oat latte + vanilla syrup + extra shot: $6.25"` + +Items should appear in the order they appear in the menu and the total price should always have two decimal places. + +# --hints-- + +`formatCoffeeOrder("I'd like an oat latte with vanilla syrup and an extra shot please.")` should return `"oat latte + vanilla syrup + extra shot: $6.25"`. + +```js +assert.equal(formatCoffeeOrder("I'd like an oat latte with vanilla syrup and an extra shot please."), "oat latte + vanilla syrup + extra shot: $6.25"); +``` + +`formatCoffeeOrder("Give me a cappuccino with caramel drizzle, vanilla syrup, and some oat milk.")` should return `"cappuccino + vanilla syrup + caramel drizzle + oat milk: $6.85"`. + +```js +assert.equal(formatCoffeeOrder("Give me a cappuccino with caramel drizzle, vanilla syrup, and some oat milk."), "cappuccino + vanilla syrup + caramel drizzle + oat milk: $6.85"); +``` + +`formatCoffeeOrder("Can I get a cold brew with some cream and an extra shot.")` should return `"cold brew + extra shot + cream: $5.75"`. + +```js +assert.equal(formatCoffeeOrder("Can I get a cold brew with some cream and an extra shot."), "cold brew + extra shot + cream: $5.75"); +``` + +`formatCoffeeOrder("Just an espresso please.")` should return `"espresso: $3.00"`. + +```js +assert.equal(formatCoffeeOrder("Just an espresso please."), "espresso: $3.00"); +``` + +`formatCoffeeOrder("I'll take an oat latte with cream and an extra shot, and some vanilla syrup and caramel drizzle.")` should return `"oat latte + vanilla syrup + caramel drizzle + extra shot + cream: $7.60"`. + +```js +assert.equal(formatCoffeeOrder("I'll take an oat latte with cream and an extra shot, and some vanilla syrup and caramel drizzle."), "oat latte + vanilla syrup + caramel drizzle + extra shot + cream: $7.60"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function formatCoffeeOrder(order) { + + return order; +} +``` + +# --solutions-- + +```js +function formatCoffeeOrder(order) { + const menu = [ + { name: "cold brew", price: 4.50 }, + { name: "oat latte", price: 5.00 }, + { name: "cappuccino", price: 4.75 }, + { name: "espresso", price: 3.00 }, + { name: "vanilla syrup", price: 0.75 }, + { name: "caramel drizzle", price: 0.60 }, + { name: "extra shot", price: 0.50 }, + { name: "oat milk", price: 0.75 }, + { name: "cream", price: 0.75 }, + ]; + + const found = menu.filter(item => order.toLowerCase().includes(item.name)); + const total = found.reduce((sum, item) => sum + item.price, 0); + return `${found.map(item => item.name).join(" + ")}: $${total.toFixed(2)}`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f35a5bb823ed620fcb7cb8.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f35a5bb823ed620fcb7cb8.md new file mode 100644 index 0000000000000000000000000000000000000000..326254cdd2d4bd90487065edf825d454946d1d6d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f35a5bb823ed620fcb7cb8.md @@ -0,0 +1,117 @@ +--- +id: 69f35a5bb823ed620fcb7cb8 +title: "Challenge 279: Longest Domino Chain" +challengeType: 28 +dashedName: challenge-279 +--- + +# --description-- + +Given a 2D array representing a set of dominoes, return the longest valid chain. + +- Each domino is a pair of numbers from 0–6, e.g. `[3, 2]`. +- A chain is valid when the second number of each domino matches the first number of the next. +- The first number of the first domino and the second number of the last one don't need to match anything. +- Any domino can be flipped, so `[3, 2]` can be played as `[2, 3]`. +- There is always exactly one longest valid chain. + +For example, given `[[1, 2], [4, 5], [2, 3]]`, return `[[1, 2], [2, 3]]`. + +# --hints-- + +`getLongestChain([[1, 2], [4, 5], [2, 3]])` should return `[[1, 2], [2, 3]]`. + +```js +const chain = JSON.stringify(getLongestChain([[1, 2], [4, 5], [2, 3]])); +const result1 = JSON.stringify([[1, 2], [2, 3]]); +const result2 = JSON.stringify([[3, 2], [2, 1]]); +assert.isTrue(chain === result1 || chain === result2); +``` + +`getLongestChain([[2, 1], [4, 3], [5, 3]])` should return `[[4, 3], [3, 5]]`. + +```js +const chain = JSON.stringify(getLongestChain([[2, 1], [4, 3], [5, 3]])); +const result1 = JSON.stringify([[4, 3], [3, 5]]); +const result2 = JSON.stringify([[5, 3], [3, 4]]); +assert.isTrue(chain === result1 || chain === result2); +``` + +`getLongestChain([[1, 2], [3, 4], [2, 3], [4, 0]])` should return `[[1, 2], [2, 3], [3, 4], [4, 0]]`. + +```js +const chain = JSON.stringify(getLongestChain([[1, 2], [3, 4], [2, 3], [4, 0]])); +const result1 = JSON.stringify([[1, 2], [2, 3], [3, 4], [4, 0]]); +const result2 = JSON.stringify([[0, 4], [4, 3], [3, 2], [2, 1]]); +assert.isTrue(chain === result1 || chain === result2); +``` + +`getLongestChain([[6, 6], [6, 1], [1, 1], [0, 3], [2, 3], [4, 1], [5, 6]])` should return `[[4, 1], [1, 1], [1, 6], [6, 6], [6, 5]]`. + +```js +const chain = JSON.stringify(getLongestChain([[6, 6], [6, 1], [1, 1], [0, 3], [2, 3], [4, 1], [5, 6]])); +const result1 = JSON.stringify([[4, 1], [1, 1], [1, 6], [6, 6], [6, 5]]); +const result2 = JSON.stringify([[5, 6], [6, 6], [6, 1], [1, 1], [1, 4]]); +assert.isTrue(chain === result1 || chain === result2); +``` + +`getLongestChain([[0, 4], [3, 3], [0, 3], [5, 6], [4, 5], [4, 2], [5, 5], [1, 2], [4, 4]])` should return `[[3, 3], [3, 0], [0, 4], [4, 4], [4, 5], [5, 5], [5, 6]]`. + +```js +const chain = JSON.stringify(getLongestChain([[0, 4], [3, 3], [0, 3], [5, 6], [4, 5], [4, 2], [5, 5], [1, 2], [4, 4]])); +const result1 = JSON.stringify([[3, 3], [3, 0], [0, 4], [4, 4], [4, 5], [5, 5], [5, 6]]); +const result2 = JSON.stringify([[6, 5], [5, 5], [5, 4], [4, 4], [4, 0], [0, 3], [3, 3]]); +assert.isTrue(chain === result1 || chain === result2); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getLongestChain(dominoes) { + + return dominoes; +} +``` + +# --solutions-- + +```js +function getLongestChain(dominoes) { + function search(chain, remaining) { + let best = chain; + const last = chain[chain.length - 1][1]; + + for (let i = 0; i < remaining.length; i++) { + const [a, b] = remaining[i]; + const rest = remaining.filter((_, j) => j !== i); + + if (a === last) { + const result = search([...chain, [a, b]], rest); + if (result.length > best.length) best = result; + } + if (b === last && a !== b) { + const result = search([...chain, [b, a]], rest); + if (result.length > best.length) best = result; + } + } + return best; + } + + let best = []; + for (let i = 0; i < dominoes.length; i++) { + const [a, b] = dominoes[i]; + const rest = dominoes.filter((_, j) => j !== i); + + const r1 = search([[a, b]], rest); + if (r1.length > best.length) best = r1; + + if (a !== b) { + const r2 = search([[b, a]], rest); + if (r2.length > best.length) best = r2; + } + } + return best; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f35a5bb823ed620fcb7cb9.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f35a5bb823ed620fcb7cb9.md new file mode 100644 index 0000000000000000000000000000000000000000..c51cfaf69c9d8a041fc7695bf207c0f41a2e18b3 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f35a5bb823ed620fcb7cb9.md @@ -0,0 +1,66 @@ +--- +id: 69f35a5bb823ed620fcb7cb9 +title: "Challenge 280: Mongo ID Date" +challengeType: 28 +dashedName: challenge-280 +--- + +# --description-- + +Given a MongoDB ID string, return its creation time as an ISO 8601 string. + +- A MongoDB ID is a 24-character hex string. The first 8 characters represent a Unix timestamp (in seconds) encoded as a base-16 integer. + +For example, `"6a094b50bcf86cd799439011"` has a timestamp of `"6a094b50"` in hex, which is `1778994000` in decimal, representing a creation time of `"2026-05-17T05:00:00.000Z"`. + +# --hints-- + +`mongoIdToDate("6a094b50bcf86cd799439011")` should return `"2026-05-17T05:00:00.000Z"`. + +```js +assert.equal(mongoIdToDate("6a094b50bcf86cd799439011"), "2026-05-17T05:00:00.000Z"); +``` + +`mongoIdToDate("695344eb1f4a4c1123042128")` should return `"2025-12-30T03:20:11.000Z"`. + +```js +assert.equal(mongoIdToDate("695344eb1f4a4c1123042128"), "2025-12-30T03:20:11.000Z"); +``` + +`mongoIdToDate("386da62df34123ac54617e56")` should return `"2000-01-01T07:01:01.000Z"`. + +```js +assert.equal(mongoIdToDate("386da62df34123ac54617e56"), "2000-01-01T07:01:01.000Z"); +``` + +`mongoIdToDate("69f571c3d7711807afd3dd55")` should return `"2026-05-02T03:38:43.000Z"`. + +```js +assert.equal(mongoIdToDate("69f571c3d7711807afd3dd55"), "2026-05-02T03:38:43.000Z"); +``` + +`mongoIdToDate("68adce01c0e1144d0a90295a")` should return `"2025-08-26T15:08:49.000Z"`. + +```js +assert.equal(mongoIdToDate("68adce01c0e1144d0a90295a"), "2025-08-26T15:08:49.000Z"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function mongoIdToDate(id) { + + return id; +} +``` + +# --solutions-- + +```js +function mongoIdToDate(id) { + const timestamp = parseInt(id.slice(0, 8), 16); + return new Date(timestamp * 1000).toISOString(); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f35a5bb823ed620fcb7cba.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f35a5bb823ed620fcb7cba.md new file mode 100644 index 0000000000000000000000000000000000000000..11a1b4abad2b04560527c5d9cbba49c9c0669f16 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f35a5bb823ed620fcb7cba.md @@ -0,0 +1,73 @@ +--- +id: 69f35a5bb823ed620fcb7cba +title: "Challenge 281: Bingo Range" +challengeType: 28 +dashedName: challenge-281 +--- + +# --description-- + +Given a bingo letter, return the number range associated with that letter. + +| Letter | Number Range | +| - | - | +| `"B"` | 1-15 | +| `"I"` | 16-30 | +| `"N"` | 31-45 | +| `"G"` | 46-60 | +| `"O"` | 61-75 | + +Return an array with all numbers in the range from smallest to largest. + +# --hints-- + +`getBingoRange("B")` should return `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]`. + +```js +assert.deepEqual(getBingoRange("B"), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]); +``` + +`getBingoRange("I")` should return `[16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]`. + +```js +assert.deepEqual(getBingoRange("I"), [16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]); +``` + +`getBingoRange("N")` should return `[31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45]`. + +```js +assert.deepEqual(getBingoRange("N"), [31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45]); +``` + +`getBingoRange("G")` should return `[46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60]`. + +```js +assert.deepEqual(getBingoRange("G"), [46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60]); +``` + +`getBingoRange("O")` should return `[61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75]`. + +```js +assert.deepEqual(getBingoRange("O"), [61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getBingoRange(letter) { + + return letter; +} +``` + +# --solutions-- + +```js +function getBingoRange(letter) { + const ranges = { B: [1, 15], I: [16, 30], N: [31, 45], G: [46, 60], O: [61, 75] }; + const [start, end] = ranges[letter]; + return Array.from({ length: end - start + 1 }, (_, i) => start + i); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f35a5bb823ed620fcb7cbb.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f35a5bb823ed620fcb7cbb.md new file mode 100644 index 0000000000000000000000000000000000000000..18667c87af81859d311a5fcc01b4c7728eb0c15b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f35a5bb823ed620fcb7cbb.md @@ -0,0 +1,65 @@ +--- +id: 69f35a5bb823ed620fcb7cbb +title: "Challenge 282: Sleep Debt" +challengeType: 28 +dashedName: challenge-282 +--- + +# --description-- + +Given an array of hours slept each night leading up to today, and a target number of hours per night, return how many hours of sleep you need tonight to eliminate your sleep debt. + +- Include tonight's hours in the total time needed to catch up. +- If you've slept enough to cover tonight's target or more, return `0`. + +# --hints-- + +`sleepDebt([6, 6, 6, 6, 6, 6], 8)` should return `20`. + +```js +assert.equal(sleepDebt([6, 6, 6, 6, 6, 6], 8), 20); +``` + +`sleepDebt([6, 7, 8, 4, 8, 6], 7)` should return `10`. + +```js +assert.equal(sleepDebt([6, 7, 8, 4, 8, 6], 7), 10); +``` + +`sleepDebt([10, 10, 9, 10, 9, 11], 9)` should return `4`. + +```js +assert.equal(sleepDebt([10, 10, 9, 10, 9, 11], 9), 4); +``` + +`sleepDebt([8, 7, 6, 7, 6, 8], 6)` should return `0`. + +```js +assert.equal(sleepDebt([8, 7, 6, 7, 6, 8], 6), 0); +``` + +`sleepDebt([8, 9, 10, 9, 10, 7], 7)` should return `0`. + +```js +assert.equal(sleepDebt([8, 9, 10, 9, 10, 7], 7), 0); +``` + +# --seed-- + +## --seed-contents-- + +```js +function sleepDebt(hoursSlept, targetHours) { + + return hoursSlept; +} +``` + +# --solutions-- + +```js +function sleepDebt(hoursSlept, targetHours) { + const debt = (hoursSlept.length + 1) * targetHours - hoursSlept.reduce((sum, h) => sum + h, 0); + return Math.max(0, debt); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f35a5bb823ed620fcb7cbc.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f35a5bb823ed620fcb7cbc.md new file mode 100644 index 0000000000000000000000000000000000000000..bd6e2dbdbf39fdce92e95b3909012b63e8b7c71b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f35a5bb823ed620fcb7cbc.md @@ -0,0 +1,69 @@ +--- +id: 69f35a5bb823ed620fcb7cbc +title: "Challenge 283: String Zipper" +challengeType: 28 +dashedName: challenge-283 +--- + +# --description-- + +Given two strings, return a new string that interleaves their characters one at a time. If one string is longer, append the remaining characters at the end. + +Begin with the first character of the first string. + +# --hints-- + +`zipStrings("abc", "123")` should return `"a1b2c3"`. + +```js +assert.equal(zipStrings("abc", "123"), "a1b2c3"); +``` + +`zipStrings("acegikmoqsuwy", "bdfhjlnprtvxz")` should return `"abcdefghijklmnopqrstuvwxyz"`. + +```js +assert.equal(zipStrings("acegikmoqsuwy", "bdfhjlnprtvxz"), "abcdefghijklmnopqrstuvwxyz"); +``` + +`zipStrings("day", "night")` should return `"dnaiyght"`. + +```js +assert.equal(zipStrings("day", "night"), "dnaiyght"); +``` + +`zipStrings("python", "javascript")` should return `"pjyatvhaosncript"`. + +```js +assert.equal(zipStrings("python", "javascript"), "pjyatvhaosncript"); +``` + +`zipStrings("feCdCm", "reoeap")` should return `"freeCodeCamp"`. + +```js +assert.equal(zipStrings("feCdCm", "reoeap"), "freeCodeCamp"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function zipStrings(a, b) { + + return a; +} +``` + +# --solutions-- + +```js +function zipStrings(a, b) { + let result = ''; + const len = Math.max(a.length, b.length); + for (let i = 0; i < len; i++) { + if (i < a.length) result += a[i]; + if (i < b.length) result += b[i]; + } + return result; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f35a5bb823ed620fcb7cbd.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f35a5bb823ed620fcb7cbd.md new file mode 100644 index 0000000000000000000000000000000000000000..fd251e6638b7229860c09e4c5df6a3369043993f --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f35a5bb823ed620fcb7cbd.md @@ -0,0 +1,69 @@ +--- +id: 69f35a5bb823ed620fcb7cbd +title: "Challenge 284: I Before E" +challengeType: 28 +dashedName: challenge-284 +--- + +# --description-- + +Given a word or sentence, return a corrected version where every word follows the "I before E except after C" rule. + +- If a word contains `"ei"` not preceded by `"c"`, replace it with `"ie"`. +- If a word contains `"ie"` preceded by `"c"`, replace it with `"ei"`. +- All other words are left unchanged. + +# --hints-- + +`iBeforeE("beleive")` should return `"believe"`. + +```js +assert.equal(iBeforeE("beleive"), "believe"); +``` + +`iBeforeE("recieve")` should return `"receive"`. + +```js +assert.equal(iBeforeE("recieve"), "receive"); +``` + +`iBeforeE("we recieved a breif")` should return `"we received a brief"`. + +```js +assert.equal(iBeforeE("we recieved a breif"), "we received a brief"); +``` + +`iBeforeE("she beleived the friendly niece could percieve the greif")` should return `"she believed the friendly niece could perceive the grief"`. + +```js +assert.equal(iBeforeE("she beleived the friendly niece could percieve the greif"), "she believed the friendly niece could perceive the grief"); +``` + +`iBeforeE("we recieved relief after the theif gave us a breif piece of feirce deceit")` should return `"we received relief after the thief gave us a brief piece of fierce deceit"`. + +```js +assert.equal(iBeforeE("we recieved relief after the theif gave us a breif piece of feirce deceit"), "we received relief after the thief gave us a brief piece of fierce deceit"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function iBeforeE(sentence) { + + return sentence; +} +``` + +# --solutions-- + +```js +function iBeforeE(sentence) { + return sentence.split(' ').map(word => { + word = word.replace(/([^c])ei/g, '$1ie'); + word = word.replace(/cie/g, 'cei'); + return word; + }).join(' '); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f35a5bb823ed620fcb7cbe.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f35a5bb823ed620fcb7cbe.md new file mode 100644 index 0000000000000000000000000000000000000000..80e261a26563f948c32d50b64a620c516e314adc --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f35a5bb823ed620fcb7cbe.md @@ -0,0 +1,80 @@ +--- +id: 69f35a5bb823ed620fcb7cbe +title: "Challenge 285: Meeting Time" +challengeType: 28 +dashedName: challenge-285 +--- + +# --description-- + +Given a 3D array representing availability windows for multiple people, return the earliest time where everyone has one hour free. If no such time exists, return `"None"`. + +- Each person's availability is an array of `[start, end]` integer pairs in 24-hour time. For example, `[10, 12]` would mean the person is available from 10 to 12. Start times range from 0-23, and end times range from 1-24. + +For example, given: + +```json +[ + [[10, 12], [15, 16]], // person 1 + [[11, 14], [15, 16]] // person 2 +] +``` + +Return `11`, the start of their first shared free hour. + +# --hints-- + +`getMeetingTime([[[10, 12], [15, 16]], [[11, 14], [15, 16]]])` should return `11`. + +```js +assert.equal(getMeetingTime([[[10, 12], [15, 16]], [[11, 14], [15, 16]]]), 11); +``` + +`getMeetingTime([[[9, 10], [12, 15]], [[10, 11], [13, 14]], [[9, 11], [10, 14]]])` should return `13`. + +```js +assert.equal(getMeetingTime([[[9, 10], [12, 15]], [[10, 11], [13, 14]], [[9, 11], [10, 14]]]), 13); +``` + +`getMeetingTime([[[7, 8], [9, 11], [12, 14], [15, 16]], [[8, 11], [12, 13], [14, 15]]])` should return `9`. + +```js +assert.equal(getMeetingTime([[[7, 8], [9, 11], [12, 14], [15, 16]], [[8, 11], [12, 13], [14, 15]]]), 9); +``` + +`getMeetingTime([[[7, 8], [10, 12], [13, 15]], [[8, 11], [12, 13], [14, 15]], [[6, 7], [8, 9], [12, 13]]])` should return `None`. + +```js +assert.equal(getMeetingTime([[[7, 8], [10, 12], [13, 15]], [[8, 11], [12, 13], [14, 15]], [[6, 7], [8, 9], [12, 13]]]), "None"); +``` + +`getMeetingTime([[[1, 3], [4, 6], [8, 10], [20, 23]], [[15, 16], [17, 18], [19, 22], [23, 24]], [[14, 16], [17, 23]], [[2, 4], [5, 6], [18, 19], [21, 22], [23, 24]]])` should return `21`. + +```js +assert.equal(getMeetingTime([[[1, 3], [4, 6], [8, 10], [20, 23]], [[15, 16], [17, 18], [19, 22], [23, 24]], [[14, 16], [17, 23]], [[2, 4], [5, 6], [18, 19], [21, 22], [23, 24]]]), 21); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getMeetingTime(availability) { + + return availability; +} +``` + +# --solutions-- + +```js +function getMeetingTime(availability) { + for (let hour = 0; hour < 24; hour++) { + const allFree = availability.every(person => + person.some(([start, end]) => start <= hour && hour + 1 <= end) + ); + if (allFree) return hour; + } + return "None"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f8c998d78ad3171a0713b9.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f8c998d78ad3171a0713b9.md new file mode 100644 index 0000000000000000000000000000000000000000..dbb468abe5e9af9062a7475991eacf6d3b5fa2e6 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f8c998d78ad3171a0713b9.md @@ -0,0 +1,85 @@ +--- +id: 69f8c998d78ad3171a0713b9 +title: "Challenge 286: Open Issues" +challengeType: 28 +dashedName: challenge-286 +--- + +# --description-- + +Given an array of issue numbers and another array of pull request (PR) numbers, return an array of issues that remain open after all PRs have been merged. + +- A PR closes an issue if their digits are a rotation of each other. For example, issue 123 would be closed by PR 231 or 312. +- A PR does not close an issue with the exact same number. For example, PR 123 does not close issue 123. So an issue with all the same number can't get closed. +- Either number may have leading zeros stripped. For example, PR 201 would close issue 12 (012, a rotation of 201). Similarily, issue 201 would be closed by PR 12. + +Return the remaining open issues in the order they were given. + +# --hints-- + +`getOpenIssues([123, 234], [231])` should return `[234]`. + +```js +assert.deepEqual(getOpenIssues([123, 234], [231]), [234]); +``` + +`getOpenIssues([123, 345, 16], [345, 231])` should return `[345, 16]`. + +```js +assert.deepEqual(getOpenIssues([123, 345, 16], [345, 231]), [345, 16]); +``` + +`getOpenIssues([456, 332, 12, 15], [201, 945, 180])` should return `[456, 332, 15]`. + +```js +assert.deepEqual(getOpenIssues([456, 332, 12, 15], [201, 945, 180]), [456, 332, 15]); +``` + +`getOpenIssues([12, 115, 296, 170, 24], [17, 18, 19, 20, 21])` should return `[115, 296, 24]`. + +```js +assert.deepEqual(getOpenIssues([12, 115, 296, 170, 24], [17, 18, 19, 20, 21]), [115, 296, 24]); +``` + +`getOpenIssues([19, 95, 422, 395, 754, 102, 296, 709, 237, 4400, 1802], [395, 440, 9001, 95, 242, 21, 287, 169, 14])` should return `[95, 395, 754, 296, 709, 237, 1802]`. + +```js +assert.deepEqual(getOpenIssues([19, 95, 422, 395, 754, 102, 296, 709, 237, 4400, 1802], [395, 440, 9001, 95, 242, 21, 287, 169, 14]), [95, 395, 754, 296, 709, 237, 1802]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getOpenIssues(issues, prs) { + + return issues; +} +``` + +# --solutions-- + +```js +function getOpenIssues(issues, prs) { + function getRotations(n) { + const s = String(n); + const rotations = new Set(); + for (let i = 0; i < s.length; i++) { + const rotated = s.slice(i) + s.slice(0, i); + rotations.add(Number(rotated)); + } + return rotations; + } + + function areRotations(a, b) { + if (a === b) return false; + const rotations = getRotations(a); + return rotations.has(b); + } + + return issues.filter(issue => + !prs.some(pr => areRotations(pr, issue) || areRotations(issue, pr)) + ); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f8c998d78ad3171a0713ba.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f8c998d78ad3171a0713ba.md new file mode 100644 index 0000000000000000000000000000000000000000..a743e4235e682cf0d9385a3f50017b96237cb501 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f8c998d78ad3171a0713ba.md @@ -0,0 +1,97 @@ +--- +id: 69f8c998d78ad3171a0713ba +title: "Challenge 287: Roman Numeral Fixer" +challengeType: 28 +dashedName: challenge-287 +--- + +# --description-- + +Given a string of malformed Roman numerals, return the value in standard Roman numeral notation. + +The input will only use additive notation, so each symbol adds its value to the total. As a reminder, here are the symbols and values: + +| Symbol | Value | +| ------ | ----- | +| `"I"` | 1 | +| `"V"` | 5 | +| `"X"` | 10 | +| `"L"` | 50 | +| `"C"` | 100 | +| `"D"` | 500 | +| `"M"` | 1000 | + +When re-encoding, use the largest possible symbol at each step, using subtractive pairs (`"IV"`, `"IX"`, `"XL"`, `"XC"`, `"CD"`, `"CM"`) where needed. + +# --hints-- + +`fixNumerals("XIIIII")` should return `"XV"`. + +```js +assert.equal(fixNumerals("XIIIII"), "XV"); +``` + +`fixNumerals("IIIILX")` should return `"LXIV"`. + +```js +assert.equal(fixNumerals("IIIILX"), "LXIV"); +``` + +`fixNumerals("XXVVVIIIII")` should return `"XL"`. + +```js +assert.equal(fixNumerals("XXVVVIIIII"), "XL"); +``` + +`fixNumerals("MDCCLXXXXVIIII")` should return `"MDCCXCIX"`. + +```js +assert.equal(fixNumerals("MDCCLXXXXVIIII"), "MDCCXCIX"); +``` + +`fixNumerals("IIIIVVVVXXXXLLLLCCDD")` should return `"MCDLXIV"`. + +```js +assert.equal(fixNumerals("IIIIVVVVXXXXLLLLCCDD"), "MCDLXIV"); +``` + +`fixNumerals("ILCDMIVDIIXLCVCXDL")` should return `"MMCMLXXXIV"`. + +```js +assert.equal(fixNumerals("ILCDMIVDIIXLCVCXDL"), "MMCMLXXXIV"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function fixNumerals(str) { + + return str; +} +``` + +# --solutions-- + +```js +function fixNumerals(str) { + const values = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 }; + const encoding = [ + [1000, "M"], [900, "CM"], [500, "D"], [400, "CD"], + [100, "C"], [90, "XC"], [50, "L"], [40, "XL"], + [10, "X"], [9, "IX"], [5, "V"], [4, "IV"], [1, "I"] + ]; + + let total = [...str].reduce((sum, c) => sum + values[c], 0); + + let result = ""; + for (const [value, symbol] of encoding) { + while (total >= value) { + result += symbol; + total -= value; + } + } + return result; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f8c998d78ad3171a0713bb.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f8c998d78ad3171a0713bb.md new file mode 100644 index 0000000000000000000000000000000000000000..81432597a13f22ad6acda926e26e6f67b3663a08 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f8c998d78ad3171a0713bb.md @@ -0,0 +1,74 @@ +--- +id: 69f8c998d78ad3171a0713bb +title: "Challenge 288: Secret Number" +challengeType: 28 +dashedName: challenge-288 +--- + +# --description-- + +Given a secret number and a guess, determine if the guess is correct. + +Return: + +- `"higher"` if the secret number is higher than the guess. +- `"lower"` if the secret number is lower than the guess. +- `"you got it!"` if the guess is correct. + +# --hints-- + +`guessNumber(50, 30)` should return `"higher"`. + +```js +assert.equal(guessNumber(50, 30), "higher"); +``` + +`guessNumber(85, 99)` should return `"lower"`. + +```js +assert.equal(guessNumber(85, 99), "lower"); +``` + +`guessNumber(2026, 2026)` should return `"you got it!"`. + +```js +assert.equal(guessNumber(2026, 2026), "you got it!"); +``` + +`guessNumber(92904, 11283)` should return `"higher"`. + +```js +assert.equal(guessNumber(92904, 11283), "higher"); +``` + +`guessNumber(230495, 423920)` should return `"lower"`. + +```js +assert.equal(guessNumber(230495, 423920), "lower"); +``` + +`guessNumber(120349, 120349)` should return `"you got it!"`. + +```js +assert.equal(guessNumber(120349, 120349), "you got it!"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function guessNumber(secret, guess) { + + return secret; +} +``` + +# --solutions-- + +```js +function guessNumber(secret, guess) { + if (guess === secret) return "you got it!"; + return guess < secret ? "higher" : "lower"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f8c998d78ad3171a0713bc.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f8c998d78ad3171a0713bc.md new file mode 100644 index 0000000000000000000000000000000000000000..cc70c00a24e6b88778a1c5e979965338910750d8 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f8c998d78ad3171a0713bc.md @@ -0,0 +1,57 @@ +--- +id: 69f8c998d78ad3171a0713bc +title: "Challenge 289: Sum of Differences" +challengeType: 28 +dashedName: challenge-289 +--- + +# --description-- + +Given an array of numbers, return the sum of the differences between each number and the one that follows it. + +For example, given `[1, 3, 4]`, return `3` (2 + 1). + +# --hints-- + +`sumOfDifferences([1, 3, 4])` should return `3`. + +```js +assert.equal(sumOfDifferences([1, 3, 4]), 3); +``` + +`sumOfDifferences([5, -3, 3, 9, 10])` should return `5`. + +```js +assert.equal(sumOfDifferences([5, -3, 3, 9, 10]), 5); +``` + +`sumOfDifferences([9, 6, 15, -20, 33, 14, 25, 16, -7])` should return `-16`. + +```js +assert.equal(sumOfDifferences([9, 6, 15, -20, 33, 14, 25, 16, -7]), -16); +``` + +`sumOfDifferences([50, 102, -46, 82, -49, 29, 71, 902, -237, 111, -61, 75])` should return `25`. + +```js +assert.equal(sumOfDifferences([50, 102, -46, 82, -49, 29, 71, 902, -237, 111, -61, 75]), 25); +``` + +# --seed-- + +## --seed-contents-- + +```js +function sumOfDifferences(arr) { + + return arr; +} +``` + +# --solutions-- + +```js +function sumOfDifferences(arr) { + return arr.slice(0, -1).reduce((sum, n, i) => sum + (arr[i + 1] - n), 0); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f8c998d78ad3171a0713bd.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f8c998d78ad3171a0713bd.md new file mode 100644 index 0000000000000000000000000000000000000000..f25e68266f26bbdfa2888f6c5021d8152ce15acb --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f8c998d78ad3171a0713bd.md @@ -0,0 +1,76 @@ +--- +id: 69f8c998d78ad3171a0713bd +title: "Challenge 290: Pizza Party" +challengeType: 28 +dashedName: challenge-290 +--- + +# --description-- + +Given an array of hours worked today per person, return the number of pizzas to order for a pizza party. + +- Divide each person's hours worked by 3 to get their slice count. +- You can't eat a partial slice, so round each person's slice count up to the nearest whole number. +- Each person gets a minimum of two slices. +- Each pizza has 8 slices. Round the total number of pizzas up to the nearest whole pizza. + +# --hints-- + +`getPizzasToOrder([8, 8, 8])` should return `2`. + +```js +assert.equal(getPizzasToOrder([8, 8, 8]), 2); +``` + +`getPizzasToOrder([10, 9, 8, 2, 2, 6, 10])` should return `3`. + +```js +assert.equal(getPizzasToOrder([10, 9, 8, 2, 2, 6, 10]), 3); +``` + +`getPizzasToOrder([1, 2, 3, 4, 5])` should return `2`. + +```js +assert.equal(getPizzasToOrder([1, 2, 3, 4, 5]), 2); +``` + +`getPizzasToOrder([8, 8, 8, 8, 8, 8, 8, 8])` should return `3`. + +```js +assert.equal(getPizzasToOrder([8, 8, 8, 8, 8, 8, 8, 8]), 3); +``` + +`getPizzasToOrder([9, 9, 6])` should return `1`. + +```js +assert.equal(getPizzasToOrder([9, 9, 6]), 1); +``` + +`getPizzasToOrder([10, 12, 16, 9, 8, 11, 15, 8, 0])` should return `5`. + +```js +assert.equal(getPizzasToOrder([10, 12, 16, 9, 8, 11, 15, 8, 0]), 5); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getPizzasToOrder(hoursWorked) { + + return hoursWorked; +} +``` + +# --solutions-- + +```js +function getPizzasToOrder(hoursWorked) { + const totalSlices = hoursWorked.reduce((sum, hours) => { + return sum + Math.max(Math.ceil(hours / 3), 2); + }, 0); + + return Math.ceil(totalSlices / 8); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f8c998d78ad3171a0713be.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f8c998d78ad3171a0713be.md new file mode 100644 index 0000000000000000000000000000000000000000..c1fd9d1a2082f9ee24942b58854ad8ff7865dde7 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f8c998d78ad3171a0713be.md @@ -0,0 +1,74 @@ +--- +id: 69f8c998d78ad3171a0713be +title: "Challenge 291: FizzBuzz Count" +challengeType: 28 +dashedName: challenge-291 +--- + +# --description-- + +Given a start and end number, count the number of fizz and buzz appearances in the range (inclusive). + +- Numbers divisible by 3 count as a fizz. +- Numbers divisible by 5 count as a buzz. +- Numbers divisible by both 3 and 5 count as both a fizz and a buzz. + +Return an object or dictionary with the counts in the format: `{ fizz, buzz }`. + +# --hints-- + +`fizzBuzzCount(1, 11)` should return `{fizz: 3, buzz: 2}`. + +```js +assert.deepEqual(fizzBuzzCount(1, 11), {fizz: 3, buzz: 2}); +``` + +`fizzBuzzCount(14, 41)` should return `{fizz: 9, buzz: 6}`. + +```js +assert.deepEqual(fizzBuzzCount(14, 41), {fizz: 9, buzz: 6}); +``` + +`fizzBuzzCount(24, 100)` should return `{fizz: 26, buzz: 16}`. + +```js +assert.deepEqual(fizzBuzzCount(24, 100), {fizz: 26, buzz: 16}); +``` + +`fizzBuzzCount(-635, -14)` should return `{fizz: 207, buzz: 125}`. + +```js +assert.deepEqual(fizzBuzzCount(-635, -14), {fizz: 207, buzz: 125}); +``` + +`fizzBuzzCount(-5432, 6789)` should return `{fizz: 4074, buzz: 2444}`. + +```js +assert.deepEqual(fizzBuzzCount(-5432, 6789), {fizz: 4074, buzz: 2444}); +``` + +# --seed-- + +## --seed-contents-- + +```js +function fizzBuzzCount(start, end) { + + return start; +} +``` + +# --solutions-- + +```js +function fizzBuzzCount(start, end) { + let fizz = 0, buzz = 0; + + for (let i = start; i <= end; i++) { + if (i % 3 === 0) fizz++; + if (i % 5 === 0) buzz++; + } + + return { fizz, buzz }; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f8c998d78ad3171a0713bf.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f8c998d78ad3171a0713bf.md new file mode 100644 index 0000000000000000000000000000000000000000..858418ecafb59374b0871073d8ab00f3e93398b1 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f8c998d78ad3171a0713bf.md @@ -0,0 +1,84 @@ +--- +id: 69f8c998d78ad3171a0713bf +title: "Challenge 292: Wider Aspect Ratio" +challengeType: 28 +dashedName: challenge-292 +--- + +# --description-- + +Given two strings for different image dimensions, return the aspect ratio of the image with a greater width-to-height ratio. + +- The given strings will be in the format `"WxH"`, for example, `"1920x1080"`. +- The aspect ratio is the ratio of width to height, reduced to the lowest whole numbers. For example, `"1920x1080"` reduces to `"16:9"`. +- Return a string in format `"W:H"`, for example, `"16:9"`. + +# --hints-- + +`getWiderAspectRatio("1920x1080", "800x600")` should return `"16:9"`. + +```js +assert.equal(getWiderAspectRatio("1920x1080", "800x600"), "16:9"); +``` + +`getWiderAspectRatio("1080x1350", "2048x1536")` should return `"4:3"`. + +```js +assert.equal(getWiderAspectRatio("1080x1350", "2048x1536"), "4:3"); +``` + +`getWiderAspectRatio("640x480", "2440x1220")` should return `"2:1"`. + +```js +assert.equal(getWiderAspectRatio("640x480", "2440x1220"), "2:1"); +``` + +`getWiderAspectRatio("360x640", "1080x1920")` should return `"9:16"`. + +```js +assert.equal(getWiderAspectRatio("360x640", "1080x1920"), "9:16"); +``` + +`getWiderAspectRatio("3440x1440", "2048x858")` should return `"43:18"`. + +```js +assert.equal(getWiderAspectRatio("3440x1440", "2048x858"), "43:18"); +``` + +`getWiderAspectRatio("12345x61234", "12534x51234")` should return `"2089:8539"`. + +```js +assert.equal(getWiderAspectRatio("12345x61234", "12534x51234"), "2089:8539"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getWiderAspectRatio(a, b) { + + return a; +} +``` + +# --solutions-- + +```js +function getWiderAspectRatio(a, b) { + function gcd(x, y) { + return y === 0 ? x : gcd(y, x % y); + } + + function parse(str) { + const [w, h] = str.split("x").map(Number); + const g = gcd(w, h); + return { ratio: w / h, simplified: `${w / g}:${h / g}` }; + } + + const imageA = parse(a); + const imageB = parse(b); + + return imageA.ratio >= imageB.ratio ? imageA.simplified : imageB.simplified; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f90c1329a94b37e2a2086c.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f90c1329a94b37e2a2086c.md new file mode 100644 index 0000000000000000000000000000000000000000..cb72511040321c80900b7544129ef3e5ce53d3e0 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f90c1329a94b37e2a2086c.md @@ -0,0 +1,143 @@ +--- +id: 69f90c1329a94b37e2a2086c +title: "Challenge 293: Best Hand" +challengeType: 28 +dashedName: challenge-293 +--- + +# --description-- + +Given an array of five strings representing playing cards, return the name of the best hand. + +- Each card is represented as a two-character string: the rank followed by the suit, `"2h"` for example. + - Ranks, from low to high, are: `"2"`, `"3"`, `"4"`, `"5"`, `"6"`, `"7"`, `"8"`, `"9"`, `"T"`, `"J"`, `"Q"`, `"K"`, and `"A"`. + - Suits are: `"h"`, `"d"`, `"c"`, and `"s"`. +- Aces (`"A"`) can be used as high or low in a straight. + +The hands, in order from worst to best, are: + +| Name | Description | +| - | - | +| `"High Card"` | No pair or better | +| `"Pair"` | Two of one rank | +| `"Two Pair"` | Two of one rank and two of another | +| `"Three of a Kind"` | Three of one rank | +| `"Straight"` | Five ranks in a row | +| `"Flush"` | Five of the same suit | +| `"Full House"` | Three of one rank, and two of another | +| `"Four of a Kind"` | Four of one rank | +| `"Straight Flush"` | Five ranks in a row of the same suit | +| `"Royal Flush"` | `"A"`, `"K"`, `"Q"`, `"J"`, `"T"` of the same suit | + +Return the name of the best hand. + +# --hints-- + +`getBestHand(["7s", "7h", "7d", "2c", "5h"])` should return `"Three of a Kind"`. + +```js +assert.equal(getBestHand(["7s", "7h", "7d", "2c", "5h"]), "Three of a Kind"); +``` + +`getBestHand(["Ks", "Kh", "Kd", "4s", "4h"])` should return `"Full House"`. + +```js +assert.equal(getBestHand(["Ks", "Kh", "Kd", "4s", "4h"]), "Full House"); +``` + +`getBestHand(["2h", "5h", "7h", "9h", "Jh"])` should return `"Flush"`. + +```js +assert.equal(getBestHand(["2h", "5h", "7h", "9h", "Jh"]), "Flush"); +``` + +`getBestHand(["As", "Ah", "Ad", "Ac", "Kh"])` should return `"Four of a Kind"`. + +```js +assert.equal(getBestHand(["As", "Ah", "Ad", "Ac", "Kh"]), "Four of a Kind"); +``` + +`getBestHand(["Ts", "Th", "9d", "9c", "8h"])` should return `"Two Pair"`. + +```js +assert.equal(getBestHand(["Ts", "Th", "9d", "9c", "8h"]), "Two Pair"); +``` + +`getBestHand(["9c", "8c", "7c", "6c", "5c"])` should return `"Straight Flush"`. + +```js +assert.equal(getBestHand(["9c", "8c", "7c", "6c", "5c"]), "Straight Flush"); +``` + +`getBestHand(["As", "Kh", "Jd", "8c", "5h"])` should return `"High Card"`. + +```js +assert.equal(getBestHand(["As", "Kh", "Jd", "8c", "5h"]), "High Card"); +``` + +`getBestHand(["As", "2h", "3d", "4c", "5h"])` should return `"Straight"`. + +```js +assert.equal(getBestHand(["As", "2h", "3d", "4c", "5h"]), "Straight"); +``` + +`getBestHand(["Ts", "Th", "7c", "6d", "5h"])` should return `"Pair"`. + +```js +assert.equal(getBestHand(["Ts", "Th", "7c", "6d", "5h"]), "Pair"); +``` + +`getBestHand(["As", "Ks", "Qs", "Js", "Ts"])` should return `"Royal Flush"`. + +```js +assert.equal(getBestHand(["As", "Ks", "Qs", "Js", "Ts"]), "Royal Flush"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getBestHand(cards) { + + return cards; +} +``` + +# --solutions-- + +```js +function getBestHand(cards) { + const rankOrder = "23456789TJQKA"; + + const ranks = cards.map(c => c[0]); + const suits = cards.map(c => c[1]); + + const isFlush = suits.every(s => s === suits[0]); + + const rankIndices = ranks.map(r => rankOrder.indexOf(r)).sort((a, b) => a - b); + + function isStraight(indices) { + const isRegular = indices.every((r, i) => i === 0 || r === indices[i - 1] + 1); + const isLowAce = JSON.stringify(indices) === JSON.stringify([0, 1, 2, 3, 12]); + return isRegular || isLowAce; + } + + const straight = isStraight(rankIndices); + + const counts = {}; + ranks.forEach(r => counts[r] = (counts[r] || 0) + 1); + const freq = Object.values(counts).sort((a, b) => b - a); + + if (isFlush && JSON.stringify(rankIndices) === JSON.stringify([8, 9, 10, 11, 12])) return "Royal Flush"; + if (isFlush && straight) return "Straight Flush"; + if (freq[0] === 4) return "Four of a Kind"; + if (freq[0] === 3 && freq[1] === 2) return "Full House"; + if (isFlush) return "Flush"; + if (straight) return "Straight"; + if (freq[0] === 3) return "Three of a Kind"; + if (freq[0] === 2 && freq[1] === 2) return "Two Pair"; + if (freq[0] === 2) return "Pair"; + return "High Card"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f90c1329a94b37e2a2086d.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f90c1329a94b37e2a2086d.md new file mode 100644 index 0000000000000000000000000000000000000000..847aa2d6430ee26eb86b0d25d263c537de35b983 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f90c1329a94b37e2a2086d.md @@ -0,0 +1,82 @@ +--- +id: 69f90c1329a94b37e2a2086d +title: "Challenge 294: Parentheses Combinations" +challengeType: 28 +dashedName: challenge-294 +--- + +# --description-- + +Given an integer, `n`, return the number of valid combinations of `n` pairs of parentheses. + +- A valid combination is a string where every opening parentheses has a corresponding closing parentheses, and no closing parentheses appears before its matching opening parentheses. + +For example, given `2`, there are 2 valid combinations: + +```json +(()) +()() +``` + +# --hints-- + +`getCombinations(2)` should return `2`. + +```js +assert.equal(getCombinations(2), 2); +``` + +`getCombinations(3)` should return `5`. + +```js +assert.equal(getCombinations(3), 5); +``` + +`getCombinations(5)` should return `42`. + +```js +assert.equal(getCombinations(5), 42); +``` + +`getCombinations(8)` should return `1430`. + +```js +assert.equal(getCombinations(8), 1430); +``` + +`getCombinations(13)` should return `742900`. + +```js +assert.equal(getCombinations(13), 742900); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getCombinations(n) { + + return n; +} +``` + +# --solutions-- + +```js +function getCombinations(n) { + let count = 0; + + function generate(open, close) { + if (open === 0 && close === 0) { + count++; + return; + } + if (open > 0) generate(open - 1, close); + if (close > open) generate(open, close - 1); + } + + generate(n, n); + return count; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcc730cb92a616f86f0bf.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcc730cb92a616f86f0bf.md new file mode 100644 index 0000000000000000000000000000000000000000..623fa9c45194ef4372b219c3995868cf64688b84 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcc730cb92a616f86f0bf.md @@ -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'; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcc730cb92a616f86f0c0.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcc730cb92a616f86f0c0.md new file mode 100644 index 0000000000000000000000000000000000000000..4a9ae6957e335fb5c5da9549d9d2383e20ef07ab --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcc730cb92a616f86f0c0.md @@ -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' + ); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcc730cb92a616f86f0c1.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcc730cb92a616f86f0c1.md new file mode 100644 index 0000000000000000000000000000000000000000..1e365de20660980fe176ec47a57ae05465fd14af --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcc730cb92a616f86f0c1.md @@ -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) + ); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcc730cb92a616f86f0c2.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcc730cb92a616f86f0c2.md new file mode 100644 index 0000000000000000000000000000000000000000..eabbc35539a8977d6e2808aa0752b95bdef6cf42 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcc730cb92a616f86f0c2.md @@ -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') + ); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcc730cb92a616f86f0c3.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcc730cb92a616f86f0c3.md new file mode 100644 index 0000000000000000000000000000000000000000..4722ed4db33219db462653d21ccbbb8164fbf552 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcc730cb92a616f86f0c3.md @@ -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') + ); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcc730cb92a616f86f0c4.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcc730cb92a616f86f0c4.md new file mode 100644 index 0000000000000000000000000000000000000000..c4a028528e35b01c0bdfeb5d6c2b7622e615fa18 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcc730cb92a616f86f0c4.md @@ -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); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcc730cb92a616f86f0c5.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcc730cb92a616f86f0c5.md new file mode 100644 index 0000000000000000000000000000000000000000..1cc9cb318016e86baf61972247fedbd71570d53b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcc730cb92a616f86f0c5.md @@ -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); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcd03ee4e68698080ef66.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcd03ee4e68698080ef66.md new file mode 100644 index 0000000000000000000000000000000000000000..55b4b9c35ed8e55ebb8d01a8bf58de6f3a1ebe35 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcd03ee4e68698080ef66.md @@ -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; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcd03ee4e68698080ef67.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcd03ee4e68698080ef67.md new file mode 100644 index 0000000000000000000000000000000000000000..e628a54b30afd391fd68a5530aef6063433f0f75 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcd03ee4e68698080ef67.md @@ -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; + }); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcd03ee4e68698080ef68.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcd03ee4e68698080ef68.md new file mode 100644 index 0000000000000000000000000000000000000000..67cca2e91713490df8f6a8e89cd6afdd290bf64a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcd03ee4e68698080ef68.md @@ -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; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcd03ee4e68698080ef69.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcd03ee4e68698080ef69.md new file mode 100644 index 0000000000000000000000000000000000000000..bd28b699cb806fab8cef5e8bd728700d4c00ac4d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcd03ee4e68698080ef69.md @@ -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); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcd03ee4e68698080ef6a.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcd03ee4e68698080ef6a.md new file mode 100644 index 0000000000000000000000000000000000000000..96796960de0faff786040d8044f7c27265590a14 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcd03ee4e68698080ef6a.md @@ -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('

    hello world

    ')` should return `"hello world"`. + +```js +assert.equal(extractContent('

    hello world

    '), "hello world"); +``` + +`extractContent('

    hello world

    ')` should return `"hello world"`. + +```js +assert.equal(extractContent('

    hello world

    '), "hello world"); +``` + +`extractContent('Click me')` should return `"Click me"`. + +```js +assert.equal(extractContent('Click me'), "Click me"); +``` + +`extractContent('

    to code
    for free
    on freecodecamp.org')` should return `"Learn to code for free on freecodecamp.org"`. + +```js +assert.equal(extractContent('

    to code
    for free
    on freecodecamp.org'), "Learn to code for free on freecodecamp.org"); +``` + +`extractContent('

    Welcome to My Website.

    This is a link to something really important.

    • Item one
    • Item two
    • Item three
    A picture
    ')` 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('

    Welcome to My Website.

    This is a link to something really important.

    • Item one
    • Item two
    • Item three
    A picture
    '), "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(); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcd03ee4e68698080ef6b.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcd03ee4e68698080ef6b.md new file mode 100644 index 0000000000000000000000000000000000000000..3d4b7b9153db5f068e77603670398d618ffb05e0 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcd03ee4e68698080ef6b.md @@ -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; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcd03ee4e68698080ef6c.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcd03ee4e68698080ef6c.md new file mode 100644 index 0000000000000000000000000000000000000000..cd81e97e9f33505acd133aa6ad74e1c40016e7df --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcd03ee4e68698080ef6c.md @@ -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; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcd03ee4e68698080ef6d.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcd03ee4e68698080ef6d.md new file mode 100644 index 0000000000000000000000000000000000000000..08aa0e4df83c3f3d6277e4c08f69e23debb9bc21 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a0dcd03ee4e68698080ef6d.md @@ -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); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a151d32d772271dd2448c2c.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a151d32d772271dd2448c2c.md new file mode 100644 index 0000000000000000000000000000000000000000..9ea6643be0130466e438645b390375b536a180f8 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a151d32d772271dd2448c2c.md @@ -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; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a151d32d772271dd2448c2d.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a151d32d772271dd2448c2d.md new file mode 100644 index 0000000000000000000000000000000000000000..de76c1b7bc8c7df02be07426bbb63493bafb724c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a151d32d772271dd2448c2d.md @@ -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; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a2649556.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a2649556.md new file mode 100644 index 0000000000000000000000000000000000000000..9e4c61670bfe08ab35cd92067bf9bc00b360f463 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a2649556.md @@ -0,0 +1,100 @@ +--- +id: 6a15cadf5f240d05a2649556 +title: "Challenge 312: Streaming Cost" +challengeType: 28 +dashedName: challenge-312 +--- + +# --description-- + +Given an array representing movies in the cart of your streaming service, and a string for your subscription tier, return the total cost of the movies. + +Each item in the cart is an object with a `"format"` (`"HD"` or `"4K"`) and a `"type"` (`"rent"` or `"buy"`). Their costs are: + +| | `"rent"` | `"buy"` | +| - | - | - | +| `"HD"` | $3.99 | $12.99 | +| `"4K"` | $5.99 | $19.99 | + +Apply the following subscription tier discounts: + +- `"none"`: full price +- `"basic"`: 10% off +- `"premium"`: 25% off + +Return the total cost rounded to two decimal places in the format `"$D.CC"`. + +# --hints-- + +`getStreamingBill([{ format: "HD", type: "rent" }], "none")` should return `"$3.99"`. + +```js +assert.equal(getStreamingBill([{ format: "HD", type: "rent" }], "none"), "$3.99"); +``` + +`getStreamingBill([{ format: "HD", type: "buy" }], "premium")` should return `"$9.74"`. + +```js +assert.equal(getStreamingBill([{ format: "HD", type: "buy" }], "premium"), "$9.74"); +``` + +`getStreamingBill([{ format: "HD", type: "rent" }, { format: "HD", type: "rent" }, { format: "HD", type: "buy" }], "basic")` should return `"$18.87"`. + +```js +assert.equal(getStreamingBill([{ format: "HD", type: "rent" }, { format: "HD", type: "rent" }, { format: "HD", type: "buy" }], "basic"), "$18.87"); +``` + +`getStreamingBill([{ format: "4K", type: "buy" }, { format: "4K", type: "buy" }, { format: "4K", type: "buy" }], "premium")` should return `"$44.98"`. + +```js +assert.equal(getStreamingBill([{ format: "4K", type: "buy" }, { format: "4K", type: "buy" }, { format: "4K", type: "buy" }], "premium"), "$44.98"); +``` + +`getStreamingBill([{ format: "HD", type: "rent" }, { format: "4K", type: "rent" }, { format: "HD", type: "buy" }, { format: "4K", type: "buy" }], "none")` should return `"$42.96"`. + +```js +assert.equal(getStreamingBill([{ format: "HD", type: "rent" }, { format: "4K", type: "rent" }, { format: "HD", type: "buy" }, { format: "4K", type: "buy" }], "none"), "$42.96"); +``` + +`getStreamingBill([{ format: "HD", type: "rent" }, { format: "4K", type: "rent" }, { format: "HD", type: "buy" }, { format: "4K", type: "buy" }], "basic")` should return `"$38.66"`. + +```js +assert.equal(getStreamingBill([{ format: "HD", type: "rent" }, { format: "4K", type: "rent" }, { format: "HD", type: "buy" }, { format: "4K", type: "buy" }], "basic"), "$38.66"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getStreamingBill(cart, subscription) { + + return cart; +} +``` + +# --solutions-- + +```js +function getStreamingBill(cart, subscription) { + const pricing = { + HD: { rent: 3.99, buy: 12.99 }, + "4K": { rent: 5.99, buy: 19.99 }, + }; + + const discounts = { + none: 1, + basic: 0.9, + premium: 0.75, + }; + + const multiplier = discounts[subscription]; + + const total = cart.reduce((sum, item) => { + const price = pricing[item.format][item.type]; + return sum + price * multiplier; + }, 0); + + return `$${total.toFixed(2)}`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a2649557.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a2649557.md new file mode 100644 index 0000000000000000000000000000000000000000..d0c1598045372ff9467b828bb0cdae1abae78c41 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a2649557.md @@ -0,0 +1,103 @@ +--- +id: 6a15cadf5f240d05a2649557 +title: "Challenge 313: Rental Cost" +challengeType: 28 +dashedName: challenge-313 +--- + +# --description-- + +Given a rental timestamp, a return timestamp, and a rental tier, return the total cost of the rental including any late fees. + +- Given timestamps are UTC ISO strings, for example: `"2026-06-18T18:30:00Z"`. +- The rental tier is the number of days before the rental is due back: `1`, `3`, or `7`. +- Rentals are due back by 12:00 PM UTC or earlier on the last day of the rental period. For example, a 1-day rental checked out at any time on March 15 is due back by 12:00 PM UTC on March 16. +- Each day past the due date and time incurs a late fee. + +Pricing is as follows: + +| Tier | Base cost | Late fee per day | +| - | - | - | +| 1 day | $4.99 | $3.99 | +| 3 days | $3.99 | $2.99 | +| 7 days | $2.99 | $0.99 | + +Return the total cost rounded to two decimal places in the format `"$D.CC"`. + +# --hints-- + +`getRentalCost("2026-06-18T18:30:00Z", "2026-06-19T10:30:00Z", 1)` should return `"$4.99"`. + +```js +assert.equal(getRentalCost("2026-06-18T18:30:00Z", "2026-06-19T10:30:00Z", 1), "$4.99"); +``` + +`getRentalCost("2026-06-18T14:30:00Z", "2026-06-20T12:30:00Z", 1)` should return `"$12.97"`. + +```js +assert.equal(getRentalCost("2026-06-18T14:30:00Z", "2026-06-20T12:30:00Z", 1), "$12.97"); +``` + +`getRentalCost("2026-06-18T10:15:00Z", "2026-06-18T19:45:00Z", 3)` should return `"$3.99"`. + +```js +assert.equal(getRentalCost("2026-06-18T10:15:00Z", "2026-06-18T19:45:00Z", 3), "$3.99"); +``` + +`getRentalCost("2026-06-18T15:20:00Z", "2026-06-23T08:10:00Z", 3)` should return `"$9.97"`. + +```js +assert.equal(getRentalCost("2026-06-18T15:20:00Z", "2026-06-23T08:10:00Z", 3), "$9.97"); +``` + +`getRentalCost("2026-06-18T12:00:00Z", "2026-06-25T12:00:00Z", 7)` should return `"$2.99"`. + +```js +assert.equal(getRentalCost("2026-06-18T12:00:00Z", "2026-06-25T12:00:00Z", 7), "$2.99"); +``` + +`getRentalCost("2026-06-18T08:00:00Z", "2027-06-18T14:00:00Z", 7)` should return `"$358.40"`. + +```js +assert.equal(getRentalCost("2026-06-18T08:00:00Z", "2027-06-18T14:00:00Z", 7), "$358.40"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getRentalCost(rented, returned, tier) { + + return rented; +} +``` + +# --solutions-- + +```js +function getRentalCost(rented, returned, tier) { + const pricing = { + 1: { base: 4.99, late: 3.99 }, + 3: { base: 3.99, late: 2.99 }, + 7: { base: 2.99, late: 0.99 }, + }; + + const rentedDate = new Date(rented); + const returnDate = new Date(returned); + const due = new Date(rentedDate); + due.setUTCDate(due.getUTCDate() + tier); + due.setUTCHours(12, 0, 0, 0); + const { base, late } = pricing[tier]; + + if (returnDate <= due) { + return `$${base.toFixed(2)}`; + } + + const msPerDay = 1000 * 60 * 60 * 24; + const daysLate = Math.ceil((returnDate - due) / msPerDay); + const total = base + daysLate * late; + + return `$${total.toFixed(2)}`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a2649558.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a2649558.md new file mode 100644 index 0000000000000000000000000000000000000000..3b6eed3d0eb6514618e155c0dc4725419b42868e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a2649558.md @@ -0,0 +1,90 @@ +--- +id: 6a15cadf5f240d05a2649558 +title: "Challenge 314: Prime Factorization" +challengeType: 28 +dashedName: challenge-314 +--- + +# --description-- + +Given an integer greater than 1, return its prime factorization as an array of numbers in ascending order. + +A prime factorization is the set of prime numbers that multiply together to produce the given integer. Each number has exactly one set. For example, the prime factorization of 20 is `[2, 2, 5]` because 2 * 2 * 5 = 20. + +If the given integer is itself prime, return it in a single-element array. + +# --hints-- + +`primeFactorization(20)` should return `[2, 2, 5]`. + +```js +assert.deepEqual(primeFactorization(20), [2, 2, 5]); +``` + +`primeFactorization(17)` should return `[17]`. + +```js +assert.deepEqual(primeFactorization(17), [17]); +``` + +`primeFactorization(15)` should return `[3, 5]`. + +```js +assert.deepEqual(primeFactorization(15), [3, 5]); +``` + +`primeFactorization(35)` should return `[5, 7]`. + +```js +assert.deepEqual(primeFactorization(35), [5, 7]); +``` + +`primeFactorization(999)` should return `[3, 3, 3, 37]`. + +```js +assert.deepEqual(primeFactorization(999), [3, 3, 3, 37]); +``` + +`primeFactorization(360)` should return `[2, 2, 2, 3, 3, 5]`. + +```js +assert.deepEqual(primeFactorization(360), [2, 2, 2, 3, 3, 5]); +``` + +`primeFactorization(510510)` should return `[2, 3, 5, 7, 11, 13, 17]`. + +```js +assert.deepEqual(primeFactorization(510510), [2, 3, 5, 7, 11, 13, 17]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function primeFactorization(n) { + + return n; +} +``` + +# --solutions-- + +```js +function primeFactorization(n) { + const factors = []; + let divisor = 2; + + while (divisor * divisor <= n) { + while (n % divisor === 0) { + factors.push(divisor); + n /= divisor; + } + divisor++; + } + + if (n > 1) factors.push(n); + + return factors; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a2649559.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a2649559.md new file mode 100644 index 0000000000000000000000000000000000000000..af2a82f65e2927d3ef3c47140b10bfb70bc57ac6 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a2649559.md @@ -0,0 +1,93 @@ +--- +id: 6a15cadf5f240d05a2649559 +title: "Challenge 315: Summer Solstice" +challengeType: 28 +dashedName: challenge-315 +--- + +# --description-- + +Today is the summer solstice, the longest day of the year in the Northern Hemisphere and the shortest in the Southern. Given a latitude, return a string representing daytime and nighttime hours. + +- The latitude will be between 90 (north pole) and -90 (south pole), inclusive +- The number of daytime hours = 12 + (latitude / 90) * 12 +- Round the daytime hours to the nearest even number + +Return a 24-character string using `"☀️"` for daytime hours and `"🌑"` for nighttime hours, where: + +- Each character represents one hour, starting at midnight (hour 0) +- Sunrise and sunset fall symmetrically around noon + +For example, a latitude of `0` (the equator) has 12 hours of daylight, so sunrise is at 6:00 AM and sunset is at 6:00 PM. Return: `"🌑🌑🌑🌑🌑🌑☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️🌑🌑🌑🌑🌑🌑"`. + +# --hints-- + +`getDaytimeHours(0)` should return `"🌑🌑🌑🌑🌑🌑☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️🌑🌑🌑🌑🌑🌑"`. + +```js +assert.equal(getDaytimeHours(0), "🌑🌑🌑🌑🌑🌑☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️🌑🌑🌑🌑🌑🌑"); +``` + +`getDaytimeHours(90)` should return `"☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️"`. + +```js +assert.equal(getDaytimeHours(90), "☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️"); +``` + +`getDaytimeHours(-90)` should return `"🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑"`. + +```js +assert.equal(getDaytimeHours(-90), "🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑🌑"); +``` + +`getDaytimeHours(-33)` should return `"🌑🌑🌑🌑🌑🌑🌑🌑☀️☀️☀️☀️☀️☀️☀️☀️🌑🌑🌑🌑🌑🌑🌑🌑"`. + +```js +assert.equal(getDaytimeHours(-33), "🌑🌑🌑🌑🌑🌑🌑🌑☀️☀️☀️☀️☀️☀️☀️☀️🌑🌑🌑🌑🌑🌑🌑🌑"); +``` + +`getDaytimeHours(66.5)` should return `"🌑🌑☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️🌑🌑"`. + +```js +assert.equal(getDaytimeHours(66.5), "🌑🌑☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️🌑🌑"); +``` + +`getDaytimeHours(40)` should return `"🌑🌑🌑☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️🌑🌑🌑"`. + +```js +assert.equal(getDaytimeHours(40), "🌑🌑🌑☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️☀️🌑🌑🌑"); +``` + +`getDaytimeHours(-50)` should return `"🌑🌑🌑🌑🌑🌑🌑🌑🌑☀️☀️☀️☀️☀️☀️🌑🌑🌑🌑🌑🌑🌑🌑🌑"`. + +```js +assert.equal(getDaytimeHours(-50), "🌑🌑🌑🌑🌑🌑🌑🌑🌑☀️☀️☀️☀️☀️☀️🌑🌑🌑🌑🌑🌑🌑🌑🌑"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getDaytimeHours(latitude) { + + return latitude; +} +``` + +# --solutions-- + +```js +function getDaytimeHours(latitude) { + const daylightHours = Math.round((12 + (latitude / 90) * 12) / 2) * 2; + const sunrise = 12 - daylightHours / 2; + const sunset = 12 + daylightHours / 2; + + let result = ""; + for (let hour = 0; hour < 24; hour++) { + result += hour >= sunrise && hour < sunset ? "☀️" : "🌑"; + } + + return result; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a264955a.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a264955a.md new file mode 100644 index 0000000000000000000000000000000000000000..8631dedb8e4dc6e6f6077c3612c03069e9dccad5 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a264955a.md @@ -0,0 +1,75 @@ +--- +id: 6a15cadf5f240d05a264955a +title: "Challenge 316: 1337 Speak" +challengeType: 28 +dashedName: challenge-316 +--- + +# --description-- + +Given a lowercase string, return it translated into leet speak by replacing the letters below with their leet substitutions: + +| Letter | Leet | +| - | - | +| `a` | `4` | +| `e` | `3` | +| `g` | `9` | +| `i` | `1` | +| `l` | `1` | +| `o` | `0` | +| `s` | `5` | +| `t` | `7` | + +- Characters with no substitution are left unchanged. + +# --hints-- + +`makeLeet("cool")` should return `"c001"`. + +```js +assert.equal(makeLeet("cool"), "c001"); +``` + +`makeLeet("leet")` should return `"1337"`. + +```js +assert.equal(makeLeet("leet"), "1337"); +``` + +`makeLeet("hacker")` should return `"h4ck3r"`. + +```js +assert.equal(makeLeet("hacker"), "h4ck3r"); +``` + +`makeLeet("satellite")` should return `"547311173"`. + +```js +assert.equal(makeLeet("satellite"), "547311173"); +``` + +`makeLeet("abcdefghijklmnopqrstuvwxyz")` should return `"4bcd3f9h1jk1mn0pqr57uvwxyz"`. + +```js +assert.equal(makeLeet("abcdefghijklmnopqrstuvwxyz"), "4bcd3f9h1jk1mn0pqr57uvwxyz"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function makeLeet(str) { + + return str; +} +``` + +# --solutions-- + +```js +function makeLeet(str) { + const map = { a: "4", e: "3", g: "9", i: "1", l: "1", o: "0", t: "7", s: "5" }; + return str.split("").map(char => map[char] || char).join(""); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a264955b.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a264955b.md new file mode 100644 index 0000000000000000000000000000000000000000..1d7499b07103e29844a60a87e2b39228387c94d6 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a264955b.md @@ -0,0 +1,63 @@ +--- +id: 6a15cadf5f240d05a264955b +title: "Challenge 317: BMI Calculator" +challengeType: 28 +dashedName: challenge-317 +--- + +# --description-- + +Given a weight in pounds and a height in inches, return the BMI (Body Mass Index) rounded to one decimal place. + +To get BMI: divide the weight by the height squared, then multiply the result by 703. + +# --hints-- + +`calculateBmi(180, 70)` should return `25.8`. + +```js +assert.equal(calculateBmi(180, 70), 25.8); +``` + +`calculateBmi(140, 64)` should return `24.0`. + +```js +assert.equal(calculateBmi(140, 64), 24.0); +``` + +`calculateBmi(160, 76)` should return `19.5`. + +```js +assert.equal(calculateBmi(160, 76), 19.5); +``` + +`calculateBmi(200, 60)` should return `39.1`. + +```js +assert.equal(calculateBmi(200, 60), 39.1); +``` + +`calculateBmi(150, 68)` should return `22.8`. + +```js +assert.equal(calculateBmi(150, 68), 22.8); +``` + +# --seed-- + +## --seed-contents-- + +```js +function calculateBmi(weight, height) { + + return weight; +} +``` + +# --solutions-- + +```js +function calculateBmi(weight, height) { + return Math.round((weight / (height * height)) * 703 * 10) / 10; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a264955c.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a264955c.md new file mode 100644 index 0000000000000000000000000000000000000000..7d44c3f1d995e9a5f3786063cd8b97fcac6947d5 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a264955c.md @@ -0,0 +1,70 @@ +--- +id: 6a15cadf5f240d05a264955c +title: "Challenge 318: DNA Mutations" +challengeType: 28 +dashedName: challenge-318 +--- + +# --description-- + +Given two DNA strands of equal length, return an array of indexes where the strands differ (mutations). + +- DNA strands are strings made up of the characters `"A"`, `"T"`, `"C"`, and `"G"` +- Return the indexes in ascending order +- If there are no mutations, return an empty array + +# --hints-- + +`detectMutations("ATCG", "ATGG")` should return `[2]`. + +```js +assert.deepEqual(detectMutations("ATCG", "ATGG"), [2]); +``` + +`detectMutations("ATGCGTACGTTAGC", "ATGCATACGATTGC")` should return `[4, 9, 11]`. + +```js +assert.deepEqual(detectMutations("ATGCGTACGTTAGC", "ATGCATACGATTGC"), [4, 9, 11]); +``` + +`detectMutations("GATCTAGCTAGGCTAGCTAG", "GATCTAGCTAGGCTAGCTAG")` should return `[]`. + +```js +assert.deepEqual(detectMutations("GATCTAGCTAGGCTAGCTAG", "GATCTAGCTAGGCTAGCTAG"), []); +``` + +`detectMutations("TCAGATCATGGCTAGCTACGATCAGCTAGCATGCATATCGACTG", "TCAGATCATGGCTAGAGCTGATCAGCTAGCATGCATATCGACTG")` should return `[15, 16, 17, 18]`. + +```js +assert.deepEqual(detectMutations("TCAGATCATGGCTAGCTACGATCAGCTAGCATGCATATCGACTG", "TCAGATCATGGCTAGAGCTGATCAGCTAGCATGCATATCGACTG"), [15, 16, 17, 18]); +``` + +`detectMutations("ACGTCAGTACGCACATGACCATTGACATA", "AACGTCAGTACGCACATGACCATTGACAT")` should return `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 23, 24, 25, 26, 27, 28]`. + +```js +assert.deepEqual(detectMutations("ACGTCAGTACGCACATGACCATTGACATA", "AACGTCAGTACGCACATGACCATTGACAT"), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 23, 24, 25, 26, 27, 28]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function detectMutations(strand1, strand2) { + + return strand1; +} +``` + +# --solutions-- + +```js +function detectMutations(strand1, strand2) { + return strand1 + .split("") + .reduce((mutations, base, i) => { + if (base !== strand2[i]) mutations.push(i); + return mutations; + }, []); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a264955d.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a264955d.md new file mode 100644 index 0000000000000000000000000000000000000000..8cef81d89bf6519cd046206e82ee513fd2ac0be5 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a264955d.md @@ -0,0 +1,90 @@ +--- +id: 6a15cadf5f240d05a264955d +title: "Challenge 319: Frontmatter Parser" +challengeType: 28 +dashedName: challenge-319 +--- + +# --description-- + +Given a string representing a frontmatter block, parse it and return an object (JavaScript) or dictionary (Python) with the keys and values. + +Frontmatter is wrapped in `---` delimiters and contains `key: value` pairs within them, one per line. For example: + +```md +--- +title: My Post +draft: false +views: 100 +--- +``` + +Should return: + +```js +{ + title: "My Post", + draft: false, + views: 100 +} +``` + +- Numbers, Booleans, and Strings should all be returned as their respective type. +- The given string will have new lines separated with the newline character (`"\n"`). The above example would be given as: `"---\ntitle: My Post\ndraft: false\nviews: 100\n---"`. + +# --hints-- + +`parseFrontmatter("---\ntitle: My Post\ndraft: false\nviews: 100\n---")` should return `{ title: "My Post", draft: false, views: 100 }`. + +```js +assert.deepEqual(parseFrontmatter("---\ntitle: My Post\ndraft: false\nviews: 100\n---"), { title: "My Post", draft: false, views: 100 }); +``` + +`parseFrontmatter("---\nid: 6a174db57256a112f932195c\ntitle: My Book\nlocale: en\nwordCount: 10000\npublished: false\n---")` should return `{ id: "6a174db57256a112f932195c", title: "My Book", locale: "en", wordCount: 10000, published: false }`. + +```js +assert.deepEqual(parseFrontmatter("---\nid: 6a174db57256a112f932195c\ntitle: My Book\nlocale: en\nwordCount: 10000\npublished: false\n---"), { id: "6a174db57256a112f932195c", title: "My Book", locale: "en", wordCount: 10000, published: false }); +``` + +`parseFrontmatter("---\nversion: 1.0.0\nurl: https://example.com\nprivate: true\n---")` should return `{ version: "1.0.0", url: "https://example.com", private: true }`. + +```js +assert.deepEqual(parseFrontmatter("---\nversion: 1.0.0\nurl: https://example.com\nprivate: true\n---"), { version: "1.0.0", url: "https://example.com", private: true }); +``` + +`parseFrontmatter("---\nrating: 4.5\nprice: 9.99\n---")` should return `{ rating: 4.5, price: 9.99 }`. + +```js +assert.deepEqual(parseFrontmatter("---\nrating: 4.5\nprice: 9.99\n---"), { rating: 4.5, price: 9.99 }); +``` + +# --seed-- + +## --seed-contents-- + +```js +function parseFrontmatter(str) { + + return str; +} +``` + +# --solutions-- + +```js +function parseFrontmatter(str) { + const lines = str.split("\n").filter(line => line !== "---" && line !== ""); + + return lines.reduce((obj, line) => { + const [key, ...rest] = line.split(":"); + const value = rest.join(":").trim(); + + if (value === "true") obj[key.trim()] = true; + else if (value === "false") obj[key.trim()] = false; + else if (!isNaN(value)) obj[key.trim()] = Number(value); + else obj[key.trim()] = value; + + return obj; + }, {}); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a264955e.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a264955e.md new file mode 100644 index 0000000000000000000000000000000000000000..2e165b2f33aa1a11000f1bd0564a7002482b26cd --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a264955e.md @@ -0,0 +1,97 @@ +--- +id: 6a15cadf5f240d05a264955e +title: "Challenge 320: Blood Bank" +challengeType: 28 +dashedName: challenge-320 +--- + +# --description-- + +Given an array of the inventory at a blood bank and an array of patient blood type requests, return a string in the format `"X of Y patients served"`. Where `X` is the maximum number of patients that can receive blood from the bank's inventory, and `Y` is the total number of patients. + +Each entry in both arrays is one of the following blood types: `"AB"`, `"A"`, `"B"`, or `"O"`. + +Compatibility rules: + +- `"AB"` can receive from any blood type. +- `"A"` can receive from `"A"` and `"O"`. +- `"B"` can receive from `"B"` and `"O"`. +- `"O"` can only receive from `"O"`. + +Duplicate entries in the given arrays represent quantity. + +# --hints-- + +`triageBlood(["O", "A", "B", "AB"], ["O", "A", "B", "AB"])` should return `"4 of 4 patients served"`. + +```js +assert.equal(triageBlood(["O", "A", "B", "AB"], ["O", "A", "B", "AB"]), "4 of 4 patients served"); +``` + +`triageBlood(["A", "A", "B", "B", "AB"], ["O", "A", "B", "B", "B"])` should return `"3 of 5 patients served"`. + +```js +assert.equal(triageBlood(["A", "A", "B", "B", "AB"], ["O", "A", "B", "B", "B"]), "3 of 5 patients served"); +``` + +`triageBlood(["O", "A", "B", "AB"], ["AB", "AB", "AB", "AB", "AB"])` should return `"4 of 5 patients served"`. + +```js +assert.equal(triageBlood(["O", "A", "B", "AB"], ["AB", "AB", "AB", "AB", "AB"]), "4 of 5 patients served"); +``` + +`triageBlood(["O", "O", "O", "O", "O"], ["O", "A", "B", "AB"])` should return `"4 of 4 patients served"`. + +```js +assert.equal(triageBlood(["O", "O", "O", "O", "O"], ["O", "A", "B", "AB"]), "4 of 4 patients served"); +``` + +`triageBlood(["A", "O", "B", "AB", "B", "AB", "O", "A", "A"], ["O", "A", "B", "AB", "A", "B", "A", "A", "B", "A", "B"])` should return `"8 of 11 patients served"`. + +```js +assert.equal(triageBlood(["A", "O", "B", "AB", "B", "AB", "O", "A", "A"], ["O", "A", "B", "AB", "A", "B", "A", "A", "B", "A", "B"]), "8 of 11 patients served"); +``` + +`triageBlood(["O", "B", "AB", "AB", "O", "A", "A", "AB", "O", "B", "B", "AB", "A", "B", "AB"], ["O", "A", "B", "B", "A", "B", "AB", "A", "B", "A", "O", "AB", "AB", "O"])` should return `"13 of 14 patients served"`. + +```js +assert.equal(triageBlood(["O", "B", "AB", "AB", "O", "A", "A", "AB", "O", "B", "B", "AB", "A", "B", "AB"], ["O", "A", "B", "B", "A", "B", "AB", "A", "B", "A", "O", "AB", "AB", "O"]), "13 of 14 patients served"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function triageBlood(bank, patients) { + + return bank; +} +``` + +# --solutions-- + +```js +function triageBlood(bank, patients) { + const b = {}; + const p = {}; + for (const t of bank) b[t] = (b[t] || 0) + 1; + for (const t of patients) p[t] = (p[t] || 0) + 1; + + const serve = (patient, donors) => { + for (const donor of donors) { + const n = Math.min(p[patient] || 0, b[donor] || 0); + p[patient] = (p[patient] || 0) - n; + b[donor] = (b[donor] || 0) - n; + saved += n; + } + }; + + let saved = 0; + serve("O", ["O"]); + serve("A", ["A", "O"]); + serve("B", ["B", "O"]); + serve("AB", ["AB", "A", "B", "O"]); + return `${saved} of ${patients.length} patients served`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a264955f.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a264955f.md new file mode 100644 index 0000000000000000000000000000000000000000..832b0bd17c9e12e81713d4c56b8a7b7a13c75d9e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a15cadf5f240d05a264955f.md @@ -0,0 +1,124 @@ +--- +id: 6a15cadf5f240d05a264955f +title: "Challenge 321: Periodic Spelling" +challengeType: 28 +dashedName: challenge-321 +--- + +# --description-- + +Given a word, determine if it can be spelled using element symbols from the periodic table. + +- Ignore casing when spelling a word. `"neon"` can be spelled with the symbols `"Ne"`, `"O"`, and `"N"`. + +Here's a full list of the element symbols: + +```json +["H","He","Li","Be","B","C","N","O","F","Ne","Na","Mg","Al","Si","P","S","Cl","Ar","K","Ca","Sc","Ti","V","Cr","Mn","Fe","Co","Ni","Cu","Zn","Ga","Ge","As","Se","Br","Kr","Rb","Sr","Y","Zr","Nb","Mo","Tc","Ru","Rh","Pd","Ag","Cd","In","Sn","Sb","Te","I","Xe","Cs","Ba","La","Ce","Pr","Nd","Pm","Sm","Eu","Gd","Tb","Dy","Ho","Er","Tm","Yb","Lu","Hf","Ta","W","Re","Os","Ir","Pt","Au","Hg","Tl","Pb","Bi","Po","At","Rn","Fr","Ra","Ac","Th","Pa","U","Np","Pu","Am","Cm","Bk","Cf","Es","Fm","Md","No","Lr","Rf","Db","Sg","Bh","Hs","Mt","Ds","Rg","Cn","Nh","Fl","Mc","Lv","Ts","Og"]; +``` + +Return an array of the elements used to spell the word, in their original casing and in the order to spell the word. Or, an empty array if it can't be spelled. + +# --hints-- + +`getPeriodicSpelling("neon")` should return `["Ne", "O", "N"]`. + +```js +assert.deepEqual(getPeriodicSpelling("neon"), ["Ne", "O", "N"]); +``` + +`getPeriodicSpelling("rational")` should return `["Ra", "Ti", "O", "N", "Al"]`. + +```js +assert.deepEqual(getPeriodicSpelling("rational"), ["Ra", "Ti", "O", "N", "Al"]); +``` + +`getPeriodicSpelling("yarn")` should return `["Y", "Ar", "N"]`. + +```js +assert.deepEqual(getPeriodicSpelling("yarn"), ["Y", "Ar", "N"]); +``` + +`getPeriodicSpelling("carbon")` should return `["C", "Ar", "B", "O", "N"]` or `["Ca", "Rb", "O", "N"]`. + +```js +const result = JSON.stringify(getPeriodicSpelling("carbon")); +const path1 = JSON.stringify(["C", "Ar", "B", "O", "N"]); +const path2 = JSON.stringify(["Ca", "Rb", "O", "N"]); +assert.isTrue(result === path1 || result === path2); +``` + + +`getPeriodicSpelling("noisy")` should return `["N", "O", "I", "S", "Y"]` or `["No", "I", "S", "Y"]`. + +```js +const result = JSON.stringify(getPeriodicSpelling("noisy")); +const path1 = JSON.stringify(["N", "O", "I", "S", "Y"]); +const path2 = JSON.stringify(["No", "I", "S", "Y"]); +assert.isTrue(result === path1 || result === path2); +``` + + +`getPeriodicSpelling("bicycles")` should return `["B", "I", "C", "Y", "Cl", "Es"]` or `["Bi", "C", "Y", "Cl", "Es"]`. + +```js +const result = JSON.stringify(getPeriodicSpelling("bicycles")); +const path1 = JSON.stringify(["B", "I", "C", "Y", "Cl", "Es"]); +const path2 = JSON.stringify(["Bi", "C", "Y", "Cl", "Es"]); +assert.isTrue(result === path1 || result === path2); +``` + +`getPeriodicSpelling("optics")` should return `["O", "P", "Ti", "C", "S"]`, `["O", "P", "Ti", "Cs"]`, `["O", "Pt", "I", "C", "S"]`, or `["O", "Pt", "I", "Cs"]`. + +```js +const result = JSON.stringify(getPeriodicSpelling("optics")); +const path1 = JSON.stringify(["O", "P", "Ti", "C", "S"]); +const path2 = JSON.stringify(["O", "P", "Ti", "Cs"]); +const path3 = JSON.stringify(["O", "Pt", "I", "C", "S"]); +const path4 = JSON.stringify(["O", "Pt", "I", "Cs"]); +assert.isTrue(result === path1 || result === path2 || result === path3 || result === path4); +``` + +`getPeriodicSpelling("value")` should return `[]`. + +```js +assert.deepEqual(getPeriodicSpelling("value"), []); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getPeriodicSpelling(word) { + + return word; +} +``` + +# --solutions-- + +```js +function getPeriodicSpelling(word) { + const elements = ["H","He","Li","Be","B","C","N","O","F","Ne","Na","Mg","Al","Si","P","S","Cl","Ar","K","Ca","Sc","Ti","V","Cr","Mn","Fe","Co","Ni","Cu","Zn","Ga","Ge","As","Se","Br","Kr","Rb","Sr","Y","Zr","Nb","Mo","Tc","Ru","Rh","Pd","Ag","Cd","In","Sn","Sb","Te","I","Xe","Cs","Ba","La","Ce","Pr","Nd","Pm","Sm","Eu","Gd","Tb","Dy","Ho","Er","Tm","Yb","Lu","Hf","Ta","W","Re","Os","Ir","Pt","Au","Hg","Tl","Pb","Bi","Po","At","Rn","Fr","Ra","Ac","Th","Pa","U","Np","Pu","Am","Cm","Bk","Cf","Es","Fm","Md","No","Lr","Rf","Db","Sg","Bh","Hs","Mt","Ds","Rg","Cn","Nh","Fl","Mc","Lv","Ts","Og"]; + + const lower = new Map(elements.map(e => [e.toLowerCase(), e])); + + function spell(word, i) { + if (i === word.length) return []; + const one = word.slice(i, i + 1); + const two = word.slice(i, i + 2); + if (lower.has(two)) { + const rest = spell(word, i + 2); + if (rest !== null) return [lower.get(two), ...rest]; + } + if (lower.has(one)) { + const rest = spell(word, i + 1); + if (rest !== null) return [lower.get(one), ...rest]; + } + return null; + } + + return spell(word.toLowerCase(), 0) ?? []; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a19b1062d1b153d8ac76d70.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a19b1062d1b153d8ac76d70.md new file mode 100644 index 0000000000000000000000000000000000000000..3674b94444d96fd72f8366146359564890fb61c4 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a19b1062d1b153d8ac76d70.md @@ -0,0 +1,98 @@ +--- +id: 6a19b1062d1b153d8ac76d70 +title: "Challenge 322: Connect 3" +challengeType: 28 +dashedName: challenge-322 +--- + +# --description-- + +Given a matrix of strings representing pieces on a game grid, determine if any player has three in a row. + +- Each cell contains `"R"`, `"Y"`, or `""` (empty string). +- Three in a row means three consecutive non-empty cells of the same type horizontally, vertically, or diagonally. + +Return: + +- A flat array with the winner and the coordinates of their three winning cells in the format: `["R", [0,2], [1,3], [2,4]]`. Coordinates are returned top-to-bottom, then left-to-right. +- An empty array if there is no winner. + +# --hints-- + +`connectThree([["", "", "", ""], ["", "", "", ""], ["", "Y", "", ""], ["Y", "R", "R", "R"]])` should return `["R", [3, 1], [3, 2], [3, 3]]`. + +```js +assert.deepEqual(connectThree([["", "", "", ""], ["", "", "", ""], ["", "Y", "", ""], ["Y", "R", "R", "R"]]), ["R", [3, 1], [3, 2], [3, 3]]); +``` + +`connectThree([["", "", "", ""], ["", "Y", "Y", ""], ["", "Y", "R", "R"], ["", "Y", "R", "R"]])` should return `["Y", [1, 1], [2, 1], [3, 1]]`. + +```js +assert.deepEqual(connectThree([["", "", "", ""], ["", "Y", "Y", ""], ["", "Y", "R", "R"], ["", "Y", "R", "R"]]), ["Y", [1, 1], [2, 1], [3, 1]]); +``` + +`connectThree([["", "", "Y", "R"], ["", "Y", "R", "Y"], ["", "R", "Y", "R"], ["", "R", "Y", "R"]])` should return `["R", [0, 3], [1, 2], [2, 1]]`. + +```js +assert.deepEqual(connectThree([["", "", "Y", "R"], ["", "Y", "R", "Y"], ["", "R", "Y", "R"], ["", "R", "Y", "R"]]), ["R", [0, 3], [1, 2], [2, 1]]); +``` + +`connectThree([["", "Y", "", ""], ["", "Y", "Y", ""], ["", "R", "R", "Y"], ["R", "R", "Y", "R"]])` should return `["Y", [0, 1], [1, 2], [2, 3]]`. + +```js +assert.deepEqual(connectThree([["", "Y", "", ""], ["", "Y", "Y", ""], ["", "R", "R", "Y"], ["R", "R", "Y", "R"]]), ["Y", [0, 1], [1, 2], [2, 3]]); +``` + +`connectThree([["Y", "R", "R", "Y"], ["R", "Y", "Y", "R"], ["Y", "R", "R", "Y"], ["R", "Y", "Y", "R"]])` should return `[]`. + +```js +assert.deepEqual(connectThree([["Y", "R", "R", "Y"], ["R", "Y", "Y", "R"], ["Y", "R", "R", "Y"], ["R", "Y", "Y", "R"]]), []); +``` + +# --seed-- + +## --seed-contents-- + +```js +function connectThree(matrix) { + + return matrix; +} +``` + +# --solutions-- + +```js +function connectThree(matrix) { + const rows = matrix.length; + const cols = matrix[0].length; + + const directions = [[0, 1], [1, 0], [1, 1], [1, -1]]; + + for (let r = 0; r < rows; r++) { + for (let c = 0; c < cols; c++) { + const piece = matrix[r][c]; + if (!piece) continue; + + for (const [dr, dc] of directions) { + const cells = [[r, c]]; + + for (let i = 1; i < 3; i++) { + const nr = r + dr * i; + const nc = c + dc * i; + if (nr < 0 || nr >= rows || nc < 0 || nc >= cols) break; + if (matrix[nr][nc] !== piece) break; + cells.push([nr, nc]); + } + + if (cells.length === 3) { + cells.sort(([r1, c1], [r2, c2]) => r1 !== r2 ? r1 - r2 : c1 - c2); + return [piece, ...cells]; + } + } + } + } + + return []; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a19b1062d1b153d8ac76d71.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a19b1062d1b153d8ac76d71.md new file mode 100644 index 0000000000000000000000000000000000000000..c0468d9911e137ef7373e46f534e916efdacd373 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a19b1062d1b153d8ac76d71.md @@ -0,0 +1,101 @@ +--- +id: 6a19b1062d1b153d8ac76d71 +title: "Challenge 323: Song Mood Finder" +challengeType: 28 +dashedName: challenge-323 +--- + +# --description-- + +Given a genre string and a BPM number for a song, determine the mood using the following table: + +| Mood | Genre | BPM Range | +|------|-------|-----------| +| `"focus"` | `"classical"` | 60–109 | +| `"focus"` | `"electronic"` | 60–89 | +| `"happy"` | `"pop"` | 60–180 | +| `"happy"` | `"classical"` | 110–180 | +| `"happy"` | `"rock"` | 60–129 | +| `"happy"` | `"electronic"` | 90–134 | +| `"hype"` | `"rock"` | 130–180 | +| `"hype"` | `"electronic"` | 135–180 | + +# --hints-- + +`getMood("rock", 111)` should return `"happy"`. + +```js +assert.equal(getMood("rock", 111), "happy"); +``` + +`getMood("electronic", 74)` should return `"focus"`. + +```js +assert.equal(getMood("electronic", 74), "focus"); +``` + +`getMood("classical", 180)` should return `"happy"`. + +```js +assert.equal(getMood("classical", 180), "happy"); +``` + +`getMood("rock", 155)` should return `"hype"`. + +```js +assert.equal(getMood("rock", 155), "hype"); +``` + +`getMood("electronic", 90)` should return `"happy"`. + +```js +assert.equal(getMood("electronic", 90), "happy"); +``` + +`getMood("classical", 67)` should return `"focus"`. + +```js +assert.equal(getMood("classical", 67), "focus"); +``` + +`getMood("pop", 100)` should return `"happy"`. + +```js +assert.equal(getMood("pop", 100), "happy"); +``` + +`getMood("electronic", 135)` should return `"hype"`. + +```js +assert.equal(getMood("electronic", 135), "hype"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getMood(genre, bpm) { + + return genre; +} +``` + +# --solutions-- + +```js +function getMood(genre, bpm) { + const table = [ + { mood: "focus", genre: "classical", min: 60, max: 109 }, + { mood: "focus", genre: "electronic", min: 60, max: 89 }, + { mood: "happy", genre: "pop", min: 60, max: 180 }, + { mood: "happy", genre: "classical", min: 110, max: 180 }, + { mood: "happy", genre: "rock", min: 60, max: 129 }, + { mood: "happy", genre: "electronic", min: 90, max: 134 }, + { mood: "hype", genre: "rock", min: 130, max: 180 }, + { mood: "hype", genre: "electronic", min: 135, max: 180 }, + ]; + + return table.find(row => row.genre === genre && bpm >= row.min && bpm <= row.max).mood; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a19b1062d1b153d8ac76d72.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a19b1062d1b153d8ac76d72.md new file mode 100644 index 0000000000000000000000000000000000000000..01e5d717c2721c216fda5a07eb8d0e38991e13db --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a19b1062d1b153d8ac76d72.md @@ -0,0 +1,75 @@ +--- +id: 6a19b1062d1b153d8ac76d72 +title: "Challenge 324: Duplicate Character Count" +challengeType: 28 +dashedName: challenge-324 +--- + +# --description-- + +Given two strings, return a count of characters from the second string that can be found in the first. + +- Duplicate characters in the second string are counted separately. + +# --hints-- + +`duplicateCharacterCount("aloha", "hei")` should return `1`. + +```js +assert.equal(duplicateCharacterCount("aloha", "hei"), 1); +``` + +`duplicateCharacterCount("jambo", "bonjour")` should return `4`. + +```js +assert.equal(duplicateCharacterCount("jambo", "bonjour"), 4); +``` + +`duplicateCharacterCount("hello", "hola")` should return `3`. + +```js +assert.equal(duplicateCharacterCount("hello", "hola"), 3); +``` + +`duplicateCharacterCount("ola", "hej")` should return `0`. + +```js +assert.equal(duplicateCharacterCount("ola", "hej"), 0); +``` + +`duplicateCharacterCount("ciao", "konnichiwa")` should return `5`. + +```js +assert.equal(duplicateCharacterCount("ciao", "konnichiwa"), 5); +``` + +`duplicateCharacterCount("merhaba", "xin chao")` should return `2`. + +```js +assert.equal(duplicateCharacterCount("merhaba", "xin chao"), 2); +``` + +`duplicateCharacterCount("hello world", "hello to everyone around the world")` should return `26`. + +```js +assert.equal(duplicateCharacterCount("hello world", "hello to everyone around the world"), 26); +``` + +# --seed-- + +## --seed-contents-- + +```js +function duplicateCharacterCount(str1, str2) { + + return str1; +} +``` + +# --solutions-- + +```js +function duplicateCharacterCount(str1, str2) { + return str2.split("").filter(char => str1.includes(char)).length; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a19b1062d1b153d8ac76d73.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a19b1062d1b153d8ac76d73.md new file mode 100644 index 0000000000000000000000000000000000000000..3e0a6c4baab1b189172e4b0d7ecc7e54f9394459 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a19b1062d1b153d8ac76d73.md @@ -0,0 +1,98 @@ +--- +id: 6a19b1062d1b153d8ac76d73 +title: "Challenge 325: Lucky Number" +challengeType: 28 +dashedName: challenge-325 +--- + +# --description-- + +Given a string of a person's first and last name, calculate their lucky number using the following rules: + +- First and last names are separated by a space +- Find the vowel and consonant count for each name +- Multiply the smaller vowel and consonant counts by each other and then by the length of the smaller name +- Do the same for the two larger counts and the larger name +- Subtract the smaller value from the larger one to get their lucky number + +If the final value is zero (`0`), return `13`. + +# --hints-- + +`getLuckyNumber("John Doe")` should return `21`. + +```js +assert.equal(getLuckyNumber("John Doe"), 21); +``` + +`getLuckyNumber("Olivia Lewis")` should return `52`. + +```js +assert.equal(getLuckyNumber("Olivia Lewis"), 52); +``` + +`getLuckyNumber("James Wilson")` should return `18`. + +```js +assert.equal(getLuckyNumber("James Wilson"), 18); +``` + +`getLuckyNumber("Elizabeth Hernandez")` should return `81`. + +```js +assert.equal(getLuckyNumber("Elizabeth Hernandez"), 81); +``` + +`getLuckyNumber("Mike Walker")` should return `32`. + +```js +assert.equal(getLuckyNumber("Mike Walker"), 32); +``` + +`getLuckyNumber("Chloe Perez")` should return `13`. + +```js +assert.equal(getLuckyNumber("Chloe Perez"), 13); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getLuckyNumber(name) { + + return name; +} +``` + +# --solutions-- + +```js +function getLuckyNumber(name) { + const vowels = "aeiouAEIOU"; + + function nameStats(str) { + const vowelCount = str.split("").filter(c => vowels.includes(c)).length; + const consonantCount = str.split("").filter(c => c.match(/[a-zA-Z]/) && !vowels.includes(c)).length; + return { vowelCount, consonantCount, length: str.length }; + } + + const [first, last] = name.split(" "); + const firstStats = nameStats(first); + const lastStats = nameStats(last); + + const largerVowels = Math.max(firstStats.vowelCount, lastStats.vowelCount); + const smallerVowels = Math.min(firstStats.vowelCount, lastStats.vowelCount); + const largerConsonants = Math.max(firstStats.consonantCount, lastStats.consonantCount); + const smallerConsonants = Math.min(firstStats.consonantCount, lastStats.consonantCount); + const largerLength = Math.max(firstStats.length, lastStats.length); + const smallerLength = Math.min(firstStats.length, lastStats.length); + + const largerValue = largerVowels * largerConsonants * largerLength; + const smallerValue = smallerVowels * smallerConsonants * smallerLength; + const result = largerValue - smallerValue; + + return result === 0 ? 13 : result; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a19dd69388e5a6e59e4f2ef.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a19dd69388e5a6e59e4f2ef.md new file mode 100644 index 0000000000000000000000000000000000000000..1f064556a4a2050359790796bbfc0900135d4ca1 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a19dd69388e5a6e59e4f2ef.md @@ -0,0 +1,82 @@ +--- +id: 6a19dd69388e5a6e59e4f2ef +title: "Challenge 326: Max Profit" +challengeType: 28 +dashedName: challenge-326 +--- + +# --description-- + +Given an array of daily stock prices and a budget (in dollars), calculate the maximum profit you could make by buying and selling the stock over the given period. + +- You may only sell after you buy. +- You may perform at most one buy and one sell transaction. Once you sell, you cannot buy again. +- You can only buy whole shares. +- Return the maximum possible profit as a string, rounded down to the nearest cent and formatted to two decimal places. + +# --hints-- + +`getMaxProfit([5, 6], 50)` should return `"10.00"`. + +```js +assert.equal(getMaxProfit([5, 6], 50), "10.00"); +``` + +`getMaxProfit([8, 2, 5, 10], 20)` should return `"80.00"`. + +```js +assert.equal(getMaxProfit([8, 2, 5, 10], 20), "80.00"); +``` + +`getMaxProfit([4, 5, 3, 6], 20)` should return `"18.00"`. + +```js +assert.equal(getMaxProfit([4, 5, 3, 6], 20), "18.00"); +``` + +`getMaxProfit([54.40, 51.22, 53.99, 50.28, 53.01, 52.84], 200)` should return `"8.31"`. + +```js +assert.equal(getMaxProfit([54.40, 51.22, 53.99, 50.28, 53.01, 52.84], 200), "8.31"); +``` + +`getMaxProfit([15.38, 15.01, 14.99, 14.62, 14.28], 80)` should return `"0.00"`. + +```js +assert.equal(getMaxProfit([15.38, 15.01, 14.99, 14.62, 14.28], 80), "0.00"); +``` + +`getMaxProfit([121.45, 126.82, 122.91, 124.65, 128.83, 128.83, 127.33], 1230.25)` should return `"73.80"`. + +```js +assert.equal(getMaxProfit([121.45, 126.82, 122.91, 124.65, 128.83, 128.83, 127.33], 1230.25), "73.80"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getMaxProfit(prices, budget) { + + return prices; +} +``` + +# --solutions-- + +```js +function getMaxProfit(prices, budget) { + let maxProfit = 0; + + for (let buy = 0; buy < prices.length - 1; buy++) { + for (let sell = buy + 1; sell < prices.length; sell++) { + const shares = Math.floor(budget / prices[buy]); + const profit = shares * (prices[sell] - prices[buy]); + if (profit > maxProfit) maxProfit = profit; + } + } + + return (Math.floor(maxProfit * 100) / 100).toFixed(2); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994d9.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994d9.md new file mode 100644 index 0000000000000000000000000000000000000000..445cc80e1f391921615e4898529647b90e01b662 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994d9.md @@ -0,0 +1,63 @@ +--- +id: 6a1d9f98e819ed70a0e994d9 +title: "Challenge 327: Database Migration" +challengeType: 28 +dashedName: challenge-327 +--- + +# --description-- + +Given two database objects, return the second object with any missing properties from the first filled in. + +- Fields that already exist in the record should not be overwritten. + +# --hints-- + +`migrateRecord({ username: "", posts: 0 }, { verified: true })` should return `{ username: "", posts: 0, verified: true }`. + +```js +assert.deepEqual(migrateRecord({ username: "", posts: 0 }, { verified: true }), { username: "", posts: 0, verified: true }); +``` + +`migrateRecord({ username: "", posts: 0 }, { username: "camper", posts: 5 })` should return `{ username: "camper", posts: 5 }`. + +```js +assert.deepEqual(migrateRecord({ username: "", posts: 0 }, { username: "camper", posts: 5 }), { username: "camper", posts: 5 }); +``` + +`migrateRecord({ username: "", posts: 0, verified: false }, { username: "camper" })` should return `{ username: "camper", posts: 0, verified: false }`. + +```js +assert.deepEqual(migrateRecord({ username: "", posts: 0, verified: false }, { username: "camper" }), { username: "camper", posts: 0, verified: false }); +``` + +`migrateRecord({ username: "", posts: 0 }, { username: "camper", role: "admin" })` should return `{ username: "camper", role: "admin", posts: 0 }`. + +```js +assert.deepEqual(migrateRecord({ username: "", posts: 0 }, { username: "camper", role: "admin" }), { username: "camper", role: "admin", posts: 0 }); +``` + +`migrateRecord({ username: "", email: "", posts: 0, verified: false, role: "user", banned: false }, { username: "camper", email: "camper@freecodecamp.org", role: "admin" })` should return `{ username: "camper", email: "camper@freecodecamp.org", role: "admin", posts: 0, verified: false, banned: false }`. + +```js +assert.deepEqual(migrateRecord({ username: "", email: "", posts: 0, verified: false, role: "user", banned: false }, { username: "camper", email: "camper@freecodecamp.org", role: "admin" }), { username: "camper", email: "camper@freecodecamp.org", role: "admin", posts: 0, verified: false, banned: false }); +``` + +# --seed-- + +## --seed-contents-- + +```js +function migrateRecord(schema, record) { + + return schema; +} +``` + +# --solutions-- + +```js +function migrateRecord(schema, record) { + return { ...schema, ...record }; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994da.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994da.md new file mode 100644 index 0000000000000000000000000000000000000000..7b6eb1b052c1e65761296fc1be8957d9caeaf9ee --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994da.md @@ -0,0 +1,79 @@ +--- +id: 6a1d9f98e819ed70a0e994da +title: "Challenge 328: Kaprekar's Routine" +challengeType: 28 +dashedName: challenge-328 +--- + +# --description-- + +Given a 4-digit number, return the number of times you need to apply Kaprekar's routine until reaching 6174. + +Kaprekar's routine works as follows: + +- Arrange the digits in descending order to form the largest number +- Arrange the digits in ascending order to form the smallest number (pad with leading zeros if necessary) +- Subtract the smaller from the larger +- Repeat with the new number + +# --hints-- + +`kaprekar(1234)` should return `3`. + +```js +assert.equal(kaprekar(1234), 3); +``` + +`kaprekar(2025)` should return `6`. + +```js +assert.equal(kaprekar(2025), 6); +``` + +`kaprekar(7173)` should return `4`. + +```js +assert.equal(kaprekar(7173), 4); +``` + +`kaprekar(3164)` should return `7`. + +```js +assert.equal(kaprekar(3164), 7); +``` + +`kaprekar(8082)` should return `2`. + +```js +assert.equal(kaprekar(8082), 2); +``` + +# --seed-- + +## --seed-contents-- + +```js +function kaprekar(n) { + + return n; +} +``` + +# --solutions-- + +```js +function kaprekar(n) { + let steps = 0; + let current = n; + + while (current !== 6174) { + const digits = String(current).padStart(4, "0").split("").map(Number); + const desc = parseInt(digits.slice().sort((a, b) => b - a).join("")); + const asc = parseInt(digits.slice().sort((a, b) => a - b).join("")); + current = desc - asc; + steps++; + } + + return steps; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994db.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994db.md new file mode 100644 index 0000000000000000000000000000000000000000..42bff63d7822f744d7e2af09373149da61e2a206 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994db.md @@ -0,0 +1,81 @@ +--- +id: 6a1d9f98e819ed70a0e994db +title: "Challenge 329: Bucket Fill" +challengeType: 28 +dashedName: challenge-329 +--- + +# --description-- + +Given a 2D grid, a starting position (`[row, col]`), and a new value, replace the value at the starting position and all connected cells of the same value with the new value. + +- Cells are connected if they are adjacent horizontally or vertically (not diagonally). + +Return the updated grid. + +# --hints-- + +`bucketFill([["R", "G"], ["R", "G"]], [0, 1], "B")` should return `[["R", "B"], ["R", "B"]]`. + +```js +assert.deepEqual(bucketFill([["R", "G"], ["R", "G"]], [0, 1], "B"), [["R", "B"], ["R", "B"]]); +``` + +`bucketFill([["Y", "G", "G"], ["Y", "Y", "Y"], ["B", "Y", "R"]], [1, 2], "B")` should return `[["B", "G", "G"], ["B", "B", "B"], ["B", "B", "R"]]`. + +```js +assert.deepEqual(bucketFill([["Y", "G", "G"], ["Y", "Y", "Y"], ["B", "Y", "R"]], [1, 2], "B"), [["B", "G", "G"], ["B", "B", "B"], ["B", "B", "R"]]); +``` + +`bucketFill([["O", "O", "P"], ["P", "O", "O"], ["P", "P", "O"]], [2, 0], "R")` should return `[["O", "O", "P"], ["R", "O", "O"], ["R", "R", "O"]]`. + +```js +assert.deepEqual(bucketFill([["O", "O", "P"], ["P", "O", "O"], ["P", "P", "O"]], [2, 0], "R"), [["O", "O", "P"], ["R", "O", "O"], ["R", "R", "O"]]); +``` + +`bucketFill([["T", "T", "R", "T"], ["R", "T", "R", "T"], ["R", "T", "R", "T"], ["T", "T", "T", "T"]], [0, 3], "Y")` should return `[["Y", "Y", "R", "Y"], ["R", "Y", "R", "Y"], ["R", "Y", "R", "Y"], ["Y", "Y", "Y", "Y"]]`. + +```js +assert.deepEqual(bucketFill([["T", "T", "R", "T"], ["R", "T", "R", "T"], ["R", "T", "R", "T"], ["T", "T", "T", "T"]], [0, 3], "Y"), [["Y", "Y", "R", "Y"], ["R", "Y", "R", "Y"], ["R", "Y", "R", "Y"], ["Y", "Y", "Y", "Y"]]); +``` + +`bucketFill([["G", "B", "G", "B"], ["R", "B", "B", "G"], ["B", "G", "B", "R"], ["B", "G", "G", "B"]], [2, 2], "G")` should return `[["G", "G", "G", "B"], ["R", "G", "G", "G"], ["B", "G", "G", "R"], ["B", "G", "G", "B"]]`. + +```js +assert.deepEqual(bucketFill([["G", "B", "G", "B"], ["R", "B", "B", "G"], ["B", "G", "B", "R"], ["B", "G", "G", "B"]], [2, 2], "G"), [["G", "G", "G", "B"], ["R", "G", "G", "G"], ["B", "G", "G", "R"], ["B", "G", "G", "B"]]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function bucketFill(grid, [row, col], newValue) { + + return grid; +} +``` + +# --solutions-- + +```js +function bucketFill(grid, [row, col], newValue) { + const target = grid[row][col]; + if (target === newValue) return grid; + + function fill(r, c) { + if (r < 0 || r >= grid.length) return; + if (c < 0 || c >= grid[0].length) return; + if (grid[r][c] !== target) return; + + grid[r][c] = newValue; + fill(r - 1, c); + fill(r + 1, c); + fill(r, c - 1); + fill(r, c + 1); + } + + fill(row, col); + return grid; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994dc.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994dc.md new file mode 100644 index 0000000000000000000000000000000000000000..f473b0261394f1ab8fb35a121e836e791088169c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994dc.md @@ -0,0 +1,61 @@ +--- +id: 6a1d9f98e819ed70a0e994dc +title: "Challenge 330: lowercase words" +challengeType: 28 +dashedName: challenge-330 +--- + +# --description-- + +Given a string, return only the words that are entirely lowercase, in their original order and with a space between each word. + +# --hints-- + +`getLowercaseWords("hello GOOD world")` should return `"hello world"`. + +```js +assert.equal(getLowercaseWords("hello GOOD world"), "hello world"); +``` + +`getLowercaseWords("these are all lowercase")` should return `"these are all lowercase"`. + +```js +assert.equal(getLowercaseWords("these are all lowercase"), "these are all lowercase"); +``` + +`getLowercaseWords("less is NoT more")` should return `"less is more"`. + +```js +assert.equal(getLowercaseWords("less is NoT more"), "less is more"); +``` + +`getLowercaseWords("DonT eat pizza every OTHER day")` should return `"eat pizza every day"`. + +```js +assert.equal(getLowercaseWords("DonT eat pizza every OTHER day"), "eat pizza every day"); +``` + +`getLowercaseWords("the Super quick AND snEaky brown fox Leapt anD jumped over aNd AROUND the lazy SloW dog")` should return `"the quick brown fox jumped over the lazy dog"`. + +```js +assert.equal(getLowercaseWords("the Super quick AND snEaky brown fox Leapt anD jumped over aNd AROUND the lazy SloW dog"), "the quick brown fox jumped over the lazy dog"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getLowercaseWords(str) { + + return str; +} +``` + +# --solutions-- + +```js +function getLowercaseWords(str) { + return str.split(" ").filter(word => word === word.toLowerCase()).join(" "); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994dd.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994dd.md new file mode 100644 index 0000000000000000000000000000000000000000..4389a231027a5746637a56ca9ed8a90465ecce23 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994dd.md @@ -0,0 +1,61 @@ +--- +id: 6a1d9f98e819ed70a0e994dd +title: "Challenge 331: Nearest Multiple" +challengeType: 28 +dashedName: challenge-331 +--- + +# --description-- + +Given two integers, round the first to the nearest multiple of the second. + +# --hints-- + +`roundToNearestMultiple(5, 3)` should return `6`. + +```js +assert.equal(roundToNearestMultiple(5, 3), 6); +``` + +`roundToNearestMultiple(17, 4)` should return `16`. + +```js +assert.equal(roundToNearestMultiple(17, 4), 16); +``` + +`roundToNearestMultiple(43, 5)` should return `45`. + +```js +assert.equal(roundToNearestMultiple(43, 5), 45); +``` + +`roundToNearestMultiple(38, 11)` should return `33`. + +```js +assert.equal(roundToNearestMultiple(38, 11), 33); +``` + +`roundToNearestMultiple(93, 12)` should return `96`. + +```js +assert.equal(roundToNearestMultiple(93, 12), 96); +``` + +# --seed-- + +## --seed-contents-- + +```js +function roundToNearestMultiple(num, multiple) { + + return num; +} +``` + +# --solutions-- + +```js +function roundToNearestMultiple(num, multiple) { + return Math.round(num / multiple) * multiple; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994de.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994de.md new file mode 100644 index 0000000000000000000000000000000000000000..5132977c35711046568a2eadb003382402e71501 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994de.md @@ -0,0 +1,75 @@ +--- +id: 6a1d9f98e819ed70a0e994de +title: "Challenge 332: Issue Triage" +challengeType: 28 +dashedName: challenge-332 +--- + +# --description-- + +Given a number of milliseconds since the last post on an issue, and the last message posted on the issue, determine what you should do with the issue according to these rules: + +- If the last message is less than 7 days ago, return `"leave it"` +- If the last message is 7 or more days ago and its content contains `"bump"` (case-insensitive), return `"close it"` +- Otherwise, return `"bump it"` + +# --hints-- + +`triageIssue(86400000, "Lets fix it")` should return `"leave it"`. + +```js +assert.equal(triageIssue(86400000, "Lets fix it"), "leave it"); +``` + +`triageIssue(1209600000, "still waiting")` should return `"bump it"`. + +```js +assert.equal(triageIssue(1209600000, "still waiting"), "bump it"); +``` + +`triageIssue(864000000, "bump")` should return `"close it"`. + +```js +assert.equal(triageIssue(864000000, "bump"), "close it"); +``` + +`triageIssue(604800000, "Do we still want this?")` should return `"bump it"`. + +```js +assert.equal(triageIssue(604800000, "Do we still want this?"), "bump it"); +``` + +`triageIssue(604800000, "Bumping this")` should return `"close it"`. + +```js +assert.equal(triageIssue(604800000, "Bumping this"), "close it"); +``` + +`triageIssue(345600000, "I'll make a PR")` should return `"leave it"`. + +```js +assert.equal(triageIssue(345600000, "I'll make a PR"), "leave it"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function triageIssue(ms, message) { + + return ms; +} +``` + +# --solutions-- + +```js +function triageIssue(ms, message) { + const sevenDays = 7 * 24 * 60 * 60 * 1000; + + if (ms < sevenDays) return "leave it"; + if (message.toLowerCase().includes("bump")) return "close it"; + return "bump it"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994df.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994df.md new file mode 100644 index 0000000000000000000000000000000000000000..85531924de853dd5ae0bf06a289a85584f3ed226 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994df.md @@ -0,0 +1,127 @@ +--- +id: 6a1d9f98e819ed70a0e994df +title: "Challenge 333: Issue Triage 2" +challengeType: 28 +dashedName: challenge-333 +--- + +# --description-- + +Given an issue title and an array of current labels, return an updated array of labels based on the following rules: + +If the issue doesn't have any labels, add: + +- `"bug"` and `"needs triage"` if the title contains `"error"` or `"bug"` +- `"enhancement"` and `"discussing"` if the title contains `"feature"` or `"add"` + +Otherwise, if the given labels contain: + +- `"needs triage"` and the title contains `"simple"` or `"easy"`, remove `"needs triage"` and add `"good first issue"` +- `"discussing"` and the title contains `"planned"` or `"next"`, remove `"discussing"` and add `"on the roadmap"` +- Otherwise, if `"needs triage"` or `"discussing"` is present, remove it and add `"help wanted"` + +If the title contains: + +- `"security"`, add a `"critical"` label + +# --hints-- + +`triageIssue("app crashes with error", [])` should return `["bug", "needs triage"]`. + +```js +assert.deepEqual(triageIssue("app crashes with error", []).sort(), ["bug", "needs triage"].sort()); +``` + +`triageIssue("app crashes with error", ["bug", "needs triage"])` should return `["bug", "help wanted"]`. + +```js +assert.deepEqual(triageIssue("app crashes with error", ["bug", "needs triage"]).sort(), ["bug", "help wanted"].sort()); +``` + +`triageIssue("add dark mode", [])` should return `["enhancement", "discussing"]`. + +```js +assert.deepEqual(triageIssue("add dark mode", []).sort(), ["enhancement", "discussing"].sort()); +``` + +`triageIssue("add dark mode", ["enhancement", "discussing"])` should return `["enhancement", "help wanted"]`. + +```js +assert.deepEqual(triageIssue("add dark mode", ["enhancement", "discussing"]).sort(), ["enhancement", "help wanted"].sort()); +``` + +`triageIssue("xss security bug", [])` should return `["bug", "needs triage", "critical"]`. + +```js +assert.deepEqual(triageIssue("xss security bug", []).sort(), ["bug", "needs triage", "critical"].sort()); +``` + +`triageIssue("security vulnerability in auth", [])` should return `["critical"]`. + +```js +assert.deepEqual(triageIssue("security vulnerability in auth", []).sort(), ["critical"].sort()); +``` + +`triageIssue("easy a11y fix", ["bug", "needs triage"])` should return `["bug", "good first issue"]`. + +```js +assert.deepEqual(triageIssue("easy a11y fix", ["bug", "needs triage"]).sort(), ["bug", "good first issue"].sort()); +``` + +`triageIssue("planned api migration", ["enhancement", "discussing"])` should return `["enhancement", "on the roadmap"]`. + +```js +assert.deepEqual(triageIssue("planned api migration", ["enhancement", "discussing"]).sort(), ["enhancement", "on the roadmap"].sort()); +``` + +`triageIssue("improve security", ["enhancement", "discussing"])` should return `["enhancement", "help wanted", "critical"]`. + +```js +assert.deepEqual(triageIssue("improve security", ["enhancement", "discussing"]).sort(), ["enhancement", "help wanted", "critical"].sort()); +``` + +# --seed-- + +## --seed-contents-- + +```js +function triageIssue(title, labels) { + + return title; +} +``` + +# --solutions-- + +```js +function triageIssue(title, labels) { + const result = [...labels]; + const t = title.toLowerCase(); + + const has = label => result.includes(label); + const add = label => { if (!has(label)) result.push(label); }; + const remove = label => { const i = result.indexOf(label); if (i > -1) result.splice(i, 1); }; + + if (result.length === 0) { + if (t.includes("error") || t.includes("bug")) { + add("bug"); add("needs triage"); + } else if (t.includes("feature") || t.includes("add")) { + add("enhancement"); add("discussing"); + } + } else { + if (has("needs triage") && (t.includes("simple") || t.includes("easy"))) { + remove("needs triage"); add("good first issue"); + } else if (has("discussing") && (t.includes("planned") || t.includes("next"))) { + remove("discussing"); add("on the roadmap"); + } else if (has("needs triage") || has("discussing")) { + remove("needs triage"); remove("discussing"); add("help wanted"); + } + } + + if (t.includes("security")) { + add("critical"); + } + + return result; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994e0.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994e0.md new file mode 100644 index 0000000000000000000000000000000000000000..99eaefb14e3dbd75c0d701a002b5f60afe7028c3 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994e0.md @@ -0,0 +1,77 @@ +--- +id: 6a1d9f98e819ed70a0e994e0 +title: "Challenge 334: Exact Change" +challengeType: 28 +dashedName: challenge-334 +--- + +# --description-- + +Given an integer amount in cents, return the number of distinct ways to make exact change using pennies (1 cent), nickels (5 cents), dimes (10 cents), and quarters (25 cents). + +# --hints-- + +`exactChange(3)` should return `1`. + +```js +assert.equal(exactChange(3), 1); +``` + +`exactChange(9)` should return `2`. + +```js +assert.equal(exactChange(9), 2); +``` + +`exactChange(17)` should return `6`. + +```js +assert.equal(exactChange(17), 6); +``` + +`exactChange(39)` should return `24`. + +```js +assert.equal(exactChange(39), 24); +``` + +`exactChange(61)` should return `73`. + +```js +assert.equal(exactChange(61), 73); +``` + +`exactChange(99)` should return `213`. + +```js +assert.equal(exactChange(99), 213); +``` + +# --seed-- + +## --seed-contents-- + +```js +function exactChange(amount) { + + return amount; +} +``` + +# --solutions-- + +```js +function exactChange(amount) { + const coins = [1, 5, 10, 25]; + const dp = new Array(amount + 1).fill(0); + dp[0] = 1; + + for (const coin of coins) { + for (let i = coin; i <= amount; i++) { + dp[i] += dp[i - coin]; + } + } + + return dp[amount]; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994e1.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994e1.md new file mode 100644 index 0000000000000000000000000000000000000000..182a01e7820abd9fe6be804903ecc0829427b2d0 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994e1.md @@ -0,0 +1,122 @@ +--- +id: 6a1d9f98e819ed70a0e994e1 +title: "Challenge 335: Five Dice" +challengeType: 28 +dashedName: challenge-335 +--- + +# --description-- + +Given an array of five dice with values 1-6, return the best possible hand. + +Here are the hands ranked lowest to highest: + +| Hand | Description | +|------|-------------| +| `"no pair"` | No pair or better | +| `"pair"` | Two dice with the same value | +| `"two pair"` | Two different pairs | +| `"three of a kind"` | Three dice with the same value | +| `"small straight"` | Four consecutive values | +| `"large straight"` | Five consecutive values | +| `"full house"` | Three of a kind and a pair | +| `"four of a kind"` | Four dice with the same value | +| `"five of a kind"` | All five dice with the same value | + +# --hints-- + +`fiveDice([1, 1, 1, 1, 1])` should return `"five of a kind"`. + +```js +assert.equal(fiveDice([1, 1, 1, 1, 1]), "five of a kind"); +``` + +`fiveDice([5, 5, 5, 6, 5])` should return `"four of a kind"`. + +```js +assert.equal(fiveDice([5, 5, 5, 6, 5]), "four of a kind"); +``` + +`fiveDice([2, 5, 6, 4, 3])` should return `"large straight"`. + +```js +assert.equal(fiveDice([2, 5, 6, 4, 3]), "large straight"); +``` + +`fiveDice([4, 3, 3, 3, 1])` should return `"three of a kind"`. + +```js +assert.equal(fiveDice([4, 3, 3, 3, 1]), "three of a kind"); +``` + +`fiveDice([4, 6, 2, 6, 5])` should return `"pair"`. + +```js +assert.equal(fiveDice([4, 6, 2, 6, 5]), "pair"); +``` + +`fiveDice([1, 4, 5, 6, 2])` should return `"no pair"`. + +```js +assert.equal(fiveDice([1, 4, 5, 6, 2]), "no pair"); +``` + +`fiveDice([1, 3, 4, 6, 2])` should return `"small straight"`. + +```js +assert.equal(fiveDice([1, 3, 4, 6, 2]), "small straight"); +``` + +`fiveDice([2, 2, 5, 2, 5])` should return `"full house"`. + +```js +assert.equal(fiveDice([2, 2, 5, 2, 5]), "full house"); +``` + +`fiveDice([6, 4, 5, 6, 4])` should return `"two pair"`. + +```js +assert.equal(fiveDice([6, 4, 5, 6, 4]), "two pair"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function fiveDice(dice) { + + return dice; +} +``` + +# --solutions-- + +```js +function fiveDice(dice) { + const counts = {}; + for (const d of dice) counts[d] = (counts[d] || 0) + 1; + const values = Object.values(counts).sort((a, b) => b - a); + const keys = Object.keys(counts).map(Number).sort((a, b) => a - b); + + const isLargeStraight = keys.length === 5 && keys[4] - keys[0] === 4; + const isSmallStraight = !isLargeStraight && (() => { + for (let i = 0; i <= 1; i++) { + const slice = keys.slice(i, i + 4); + if (slice.length === 4 && slice[3] - slice[0] === 3 && + new Set(slice).size === 4) return true; + } + return false; + })(); + + if (values[0] === 5) return "five of a kind"; + if (values[0] === 4) return "four of a kind"; + if (values[0] === 3 && values[1] === 2) return "full house"; + if (isLargeStraight) return "large straight"; + if (isSmallStraight) return "small straight"; + if (values[0] === 3) return "three of a kind"; + if (values[0] === 2 && values[1] === 2) return "two pair"; + if (values[0] === 2) return "pair"; + return "no pair"; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994e2.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994e2.md new file mode 100644 index 0000000000000000000000000000000000000000..926c26d2dd1ede9b304321e99088cc5979f5de00 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a1d9f98e819ed70a0e994e2.md @@ -0,0 +1,93 @@ +--- +id: 6a1d9f98e819ed70a0e994e2 +title: "Challenge 336: Horoscope Match" +challengeType: 28 +dashedName: challenge-336 +--- + +# --description-- + +Given two star sign strings, return their compatibility percentage. + +The signs are arranged in a wheel of 12 positions in this order: `"Aries"`, `"Taurus"`, `"Gemini"`, `"Cancer"`, `"Leo"`, `"Virgo"`, `"Libra"`, `"Scorpio"`, `"Sagittarius"`, `"Capricorn"`, `"Aquarius"`, `"Pisces"`, wrapping back to `"Aries"` after `"Pisces"`. Find the shortest distance between the two signs and return the compatibility: + +| Distance | Compatibility | +|----------|---------------| +| 0 | `"100%"` | +| 1 | `"40%"` | +| 2 | `"80%"` | +| 3 | `"30%"` | +| 4 | `"90%"` | +| 5 | `"20%"` | +| 6 | `"50%"` | + +# --hints-- + +`horoscopeMatch("Libra", "Sagittarius")` should return `"80%"`. + +```js +assert.equal(horoscopeMatch("Libra", "Sagittarius"), "80%"); +``` + +`horoscopeMatch("Gemini", "Scorpio")` should return `"20%"`. + +```js +assert.equal(horoscopeMatch("Gemini", "Scorpio"), "20%"); +``` + +`horoscopeMatch("Pisces", "Aries")` should return `"40%"`. + +```js +assert.equal(horoscopeMatch("Pisces", "Aries"), "40%"); +``` + +`horoscopeMatch("Capricorn", "Cancer")` should return `"50%"`. + +```js +assert.equal(horoscopeMatch("Capricorn", "Cancer"), "50%"); +``` + +`horoscopeMatch("Aquarius", "Aquarius")` should return `"100%"`. + +```js +assert.equal(horoscopeMatch("Aquarius", "Aquarius"), "100%"); +``` + +`horoscopeMatch("Virgo", "Taurus")` should return `"90%"`. + +```js +assert.equal(horoscopeMatch("Virgo", "Taurus"), "90%"); +``` + +`horoscopeMatch("Leo", "Scorpio")` should return `"30%"`. + +```js +assert.equal(horoscopeMatch("Leo", "Scorpio"), "30%"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function horoscopeMatch(sign1, sign2) { + + return sign1; +} +``` + +# --solutions-- + +```js +function horoscopeMatch(sign1, sign2) { + const signs = ["Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo", "Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces"]; + + const a = signs.indexOf(sign1) + 1; + const b = signs.indexOf(sign2) + 1; + const diff = Math.abs(a - b); + const distance = Math.min(diff, 12 - diff); + + const compatibility = { 0: "100%", 1: "40%", 2: "80%", 3: "30%", 4: "90%", 5: "20%", 6: "50%" }; + return compatibility[distance]; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0005fff.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0005fff.md new file mode 100644 index 0000000000000000000000000000000000000000..beb340403b42204457ed947384295846044b5b36 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0005fff.md @@ -0,0 +1,65 @@ +--- +id: 6a2037a68a0bc2aef0005fff +title: "Challenge 337: Tally Counter" +challengeType: 28 +dashedName: challenge-337 +--- + +# --description-- + +Given a string of tally marks, return the total count represented. + +- Each pipe `"|"` represents one count. +- Every fifth mark is represented as a forward slash `"/"`, completing a group of five (`"||||/"`). +- Groups are separated by a space. + +# --hints-- + +`getTallyCount("||||")` should return `4`. + +```js +assert.equal(getTallyCount("||||"), 4); +``` + +`getTallyCount("||||/")` should return `5`. + +```js +assert.equal(getTallyCount("||||/"), 5); +``` + +`getTallyCount("||||/ |||")` should return `8`. + +```js +assert.equal(getTallyCount("||||/ |||"), 8); +``` + +`getTallyCount("||||/ ||||/ ||||/ ||")` should return `17`. + +```js +assert.equal(getTallyCount("||||/ ||||/ ||||/ ||"), 17); +``` + +`getTallyCount("||||/ ||||/ ||||/ ||||/ ||||/ ||||/ ||||/ ||||/ |")` should return `41`. + +```js +assert.equal(getTallyCount("||||/ ||||/ ||||/ ||||/ ||||/ ||||/ ||||/ ||||/ |"), 41); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getTallyCount(str) { + + return str; +} +``` + +# --solutions-- + +```js +function getTallyCount(str) { + return str.replace(/ /g, "").length; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0006000.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0006000.md new file mode 100644 index 0000000000000000000000000000000000000000..15423ee923719b37b344d5328d0ed112fbd26353 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0006000.md @@ -0,0 +1,93 @@ +--- +id: 6a2037a68a0bc2aef0006000 +title: "Challenge 338: Pet Age Calculator" +challengeType: 28 +dashedName: challenge-338 +--- + +# --description-- + +Given a pet type and age in human years, return the equivalent age in pet years using the following conversion table: + +| Pet | Multiplier | +|-----|-----------| +| `"dog"` | 7 | +| `"cat"` | 6 | +| `"rabbit"` | 8 | +| `"hamster"` | 30 | +| `"guinea pig"` | 12 | +| `"goldfish"` | 6 | +| `"bird"` | 5 | + +# --hints-- + +`petYears("dog", 5)` should return `35`. + +```js +assert.equal(petYears("dog", 5), 35); +``` + +`petYears("cat", 9)` should return `54`. + +```js +assert.equal(petYears("cat", 9), 54); +``` + +`petYears("rabbit", 3)` should return `24`. + +```js +assert.equal(petYears("rabbit", 3), 24); +``` + +`petYears("hamster", 4)` should return `120`. + +```js +assert.equal(petYears("hamster", 4), 120); +``` + +`petYears("guinea pig", 5)` should return `60`. + +```js +assert.equal(petYears("guinea pig", 5), 60); +``` + +`petYears("goldfish", 2)` should return `12`. + +```js +assert.equal(petYears("goldfish", 2), 12); +``` + +`petYears("bird", 1)` should return `5`. + +```js +assert.equal(petYears("bird", 1), 5); +``` + +# --seed-- + +## --seed-contents-- + +```js +function petYears(pet, age) { + + return pet; +} +``` + +# --solutions-- + +```js +function petYears(pet, age) { + const table = { + dog: 7, + cat: 6, + rabbit: 8, + hamster: 30, + "guinea pig": 12, + goldfish: 6, + bird: 5, + }; + + return age * table[pet]; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0006001.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0006001.md new file mode 100644 index 0000000000000000000000000000000000000000..5e2c2c1096c4cd152b757051fa29eb01d3bc8b66 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0006001.md @@ -0,0 +1,67 @@ +--- +id: 6a2037a68a0bc2aef0006001 +title: "Challenge 339: Array Chunks" +challengeType: 28 +dashedName: challenge-339 +--- + +# --description-- + +Given an array and a chunk size, return the array split into sub-arrays of that size. + +- The last chunk may be smaller if the array doesn't divide evenly. + +# --hints-- + +`chunkArray([1, 2, 3, 4, 5, 6], 3)` should return `[[1, 2, 3], [4, 5, 6]]`. + +```js +assert.deepEqual(chunkArray([1, 2, 3, 4, 5, 6], 3), [[1, 2, 3], [4, 5, 6]]); +``` + +`chunkArray([1, "two", 3, "four", 5, "six", 7, "eight"], 2)` should return `[[1, "two"], [3, "four"], [5, "six"], [7, "eight"]]`. + +```js +assert.deepEqual(chunkArray([1, "two", 3, "four", 5, "six", 7, "eight"], 2), [[1, "two"], [3, "four"], [5, "six"], [7, "eight"]]); +``` + +`chunkArray([1, 2, 3, 4, 5], 3)` should return `[[1, 2, 3], [4, 5]]`. + +```js +assert.deepEqual(chunkArray([1, 2, 3, 4, 5], 3), [[1, 2, 3], [4, 5]]); +``` + +`chunkArray(["a", "b", "c", "d", "e"], 1)` should return `[["a"], ["b"], ["c"], ["d"], ["e"]]`. + +```js +assert.deepEqual(chunkArray(["a", "b", "c", "d", "e"], 1), [["a"], ["b"], ["c"], ["d"], ["e"]]); +``` + +`chunkArray([1, 2, 3], 5)` should return `[[1, 2, 3]]`. + +```js +assert.deepEqual(chunkArray([1, 2, 3], 5), [[1, 2, 3]]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function chunkArray(arr, size) { + + return arr; +} +``` + +# --solutions-- + +```js +function chunkArray(arr, size) { + const result = []; + for (let i = 0; i < arr.length; i += size) { + result.push(arr.slice(i, i + size)); + } + return result; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0006002.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0006002.md new file mode 100644 index 0000000000000000000000000000000000000000..698c661251ab50d6d07ca43b8ed33563dcefe4a3 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0006002.md @@ -0,0 +1,94 @@ +--- +id: 6a2037a68a0bc2aef0006002 +title: "Challenge 340: Pig Latin Converter" +challengeType: 28 +dashedName: challenge-340 +--- + +# --description-- + +Given a string, convert it to Pig Latin using the following rules: + +- If a word begins with a vowel (`"a"`, `"e"`, `"i"`, `"o"`, or `"u"`), add `"way"` to the end. For example, `"universe"` converts to `"universeway"`. +- If a word begins with one or more consonants, move them to the end and add `"ay"`. For example, `"hello"` converts to `"ellohay"`. +- Preserve the case of the first letter. For example, `"Hello"` converts to `"Ellohay"`. + +# --hints-- + +`pigLatin("universe")` should return `"universeway"`. + +```js +assert.equal(pigLatin("universe"), "universeway"); +``` + +`pigLatin("hello")` should return `"ellohay"`. + +```js +assert.equal(pigLatin("hello"), "ellohay"); +``` + +`pigLatin("hello universe")` should return `"ellohay universeway"`. + +```js +assert.equal(pigLatin("hello universe"), "ellohay universeway"); +``` + +`pigLatin("Hello universe")` should return `"Ellohay universeway"`. + +```js +assert.equal(pigLatin("Hello universe"), "Ellohay universeway"); +``` + +`pigLatin("Pig Latin is fun")` should return `"Igpay Atinlay isway unfay"`. + +```js +assert.equal(pigLatin("Pig Latin is fun"), "Igpay Atinlay isway unfay"); +``` + +`pigLatin("The quick brown fox jumped over the lazy dog")` should return `"Ethay uickqay ownbray oxfay umpedjay overway ethay azylay ogday"`. + +```js +assert.equal(pigLatin("The quick brown fox jumped over the lazy dog"), "Ethay uickqay ownbray oxfay umpedjay overway ethay azylay ogday"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function pigLatin(str) { + + return str; +} +``` + +# --solutions-- + +```js +function pigLatin(str) { + const vowels = "aeiou"; + + return str.split(" ").map(word => { + const lowerWord = word.toLowerCase(); + + if (vowels.includes(lowerWord[0])) { + return word + "way"; + } + + let i = 0; + while (i < word.length && !vowels.includes(lowerWord[i])) { + i++; + } + + const consonants = word.slice(0, i); + const rest = word.slice(i); + const result = rest + consonants + "ay"; + + if (word[0] === word[0].toUpperCase()) { + return result[0].toUpperCase() + result.slice(1).toLowerCase(); + } + + return result; + }).join(" "); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0006003.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0006003.md new file mode 100644 index 0000000000000000000000000000000000000000..a5976cc30b1313473fe3907ce1210b5a1e3efd89 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0006003.md @@ -0,0 +1,97 @@ +--- +id: 6a2037a68a0bc2aef0006003 +title: "Challenge 341: Birthday Countdown" +challengeType: 28 +dashedName: challenge-341 +--- + +# --description-- + +Given today's date and a birthday, return the number of days until the person's next birthday. + +- Today's date is given as a string in `"YYYY-MM-DD"` format, with leading zeros, for example: `"2026-07-16"`. +- The birthday is given as a string in `"M/D"` format, without leading zeros, for example: `"9/7"`. +- If today is their birthday, return the number of days until their next birthday (not `0`). +- Leap years should be accounted for. + +# --hints-- + +`daysUntilBirthday("2026-07-16", "9/7")` should return `53`. + +```js +assert.equal(daysUntilBirthday("2026-07-16", "9/7"), 53); +``` + +`daysUntilBirthday("2026-07-16", "3/22")` should return `249`. + +```js +assert.equal(daysUntilBirthday("2026-07-16", "3/22"), 249); +``` + +`daysUntilBirthday("2026-07-16", "7/16")` should return `365`. + +```js +assert.equal(daysUntilBirthday("2026-07-16", "7/16"), 365); +``` + +`daysUntilBirthday("2024-02-28", "3/1")` should return `2`. + +```js +assert.equal(daysUntilBirthday("2024-02-28", "3/1"), 2); +``` + +`daysUntilBirthday("2023-04-24", "12/30")` should return `250`. + +```js +assert.equal(daysUntilBirthday("2023-04-24", "12/30"), 250); +``` + +`daysUntilBirthday("2024-03-01", "2/29")` should return `1460`. + +```js +assert.equal(daysUntilBirthday("2024-03-01", "2/29"), 1460); +``` + +`daysUntilBirthday("2096-03-01", "2/29")` should return `2920`. + +```js +assert.equal(daysUntilBirthday("2096-03-01", "2/29"), 2920); +``` + +# --seed-- + +## --seed-contents-- + +```js +function daysUntilBirthday(today, birthday) { + + return today; +} +``` + +# --solutions-- + +```js +function daysUntilBirthday(today, birthday) { + const [year, month, day] = today.split("-").map(Number); + const [bMonth, bDay] = birthday.split("/").map(Number); + + const todayDate = new Date(year, month - 1, day); + + function isLeapYear(y) { + return (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0; + } + + function nextValidBirthday(fromYear) { + for (let y = fromYear; y <= fromYear + 8; y++) { + if (bMonth === 2 && bDay === 29 && !isLeapYear(y)) continue; + const date = new Date(y, bMonth - 1, bDay); + if (date > todayDate) return date; + } + } + + const nextBirthday = nextValidBirthday(year); + const diff = nextBirthday - todayDate; + return Math.round(diff / (1000 * 60 * 60 * 24)); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0006004.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0006004.md new file mode 100644 index 0000000000000000000000000000000000000000..68fb2ea7ad5e69041d025e768e8d78b7050fc729 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0006004.md @@ -0,0 +1,85 @@ +--- +id: 6a2037a68a0bc2aef0006004 +title: "Challenge 342: Dice Odds" +challengeType: 28 +dashedName: challenge-342 +--- + +# --description-- + +Given a number of six-sided dice to roll and a target sum, return the odds of rolling that sum as a string in the format `"1 in X"`. + +- The number of dice will be between 1 and 6. +- The target sum is always achievable with the given number of dice. +- Round `"X"` to the nearest whole number. + +# --hints-- + +`getOdds(1, 5)` should return `"1 in 6"`. + +```js +assert.equal(getOdds(1, 5), "1 in 6"); +``` + +`getOdds(2, 4)` should return `"1 in 12"`. + +```js +assert.equal(getOdds(2, 4), "1 in 12"); +``` + +`getOdds(3, 10)` should return `"1 in 8"`. + +```js +assert.equal(getOdds(3, 10), "1 in 8"); +``` + +`getOdds(4, 7)` should return `"1 in 65"`. + +```js +assert.equal(getOdds(4, 7), "1 in 65"); +``` + +`getOdds(5, 26)` should return `"1 in 111"`. + +```js +assert.equal(getOdds(5, 26), "1 in 111"); +``` + +`getOdds(6, 35)` should return `"1 in 7776"`. + +```js +assert.equal(getOdds(6, 35), "1 in 7776"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getOdds(dice, target) { + + return dice; +} +``` + +# --solutions-- + +```js +function getOdds(dice, target) { + let validCombos = 0; + const totalCombos = Math.pow(6, dice); + + function roll(diceLeft, sum) { + if (diceLeft === 0) { + if (sum === target) validCombos++; + return; + } + for (let face = 1; face <= 6; face++) { + roll(diceLeft - 1, sum + face); + } + } + + roll(dice, 0); + return `1 in ${Math.round(totalCombos / validCombos)}`; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0006005.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0006005.md new file mode 100644 index 0000000000000000000000000000000000000000..9dd425aee3a6136c161c096379664300ac9f791c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0006005.md @@ -0,0 +1,69 @@ +--- +id: 6a2037a68a0bc2aef0006005 +title: "Challenge 343: Elevator Stops" +challengeType: 28 +dashedName: challenge-343 +--- + +# --description-- + +Given a number for the current floor of an elevator and an array of requested floors, return an array of the order the elevator should visit them to minimize number of floors traveled. + +- If tied, go up first +- Floors with a request must be visited when the elevator first passes them + +# --hints-- + +`elevatorStops(5, [2, 8, 3, 9])` should return `[3, 2, 8, 9]`. + +```js +assert.deepEqual(elevatorStops(5, [2, 8, 3, 9]), [3, 2, 8, 9]); +``` + +`elevatorStops(6, [2, 10, 8, 3, 1, 9])` should return `[8, 9, 10, 3, 2, 1]`. + +```js +assert.deepEqual(elevatorStops(6, [2, 10, 8, 3, 1, 9]), [8, 9, 10, 3, 2, 1]); +``` + +`elevatorStops(1, [4, 8, 3, 6, 9])` should return `[3, 4, 6, 8, 9]`. + +```js +assert.deepEqual(elevatorStops(1, [4, 8, 3, 6, 9]), [3, 4, 6, 8, 9]); +``` + +`elevatorStops(12, [6, 10, 7, 3, 1, 4])` should return `[10, 7, 6, 4, 3, 1]`. + +```js +assert.deepEqual(elevatorStops(12, [6, 10, 7, 3, 1, 4]), [10, 7, 6, 4, 3, 1]); +``` + +`elevatorStops(11, [2, 8, 23, 5, 12, 10, 6, 9, 19])` should return `[10, 9, 8, 6, 5, 2, 12, 19, 23]`. + +```js +assert.deepEqual(elevatorStops(11, [2, 8, 23, 5, 12, 10, 6, 9, 19]), [10, 9, 8, 6, 5, 2, 12, 19, 23]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function elevatorStops(currentFloor, stops) { + + return currentFloor; +} +``` + +# --solutions-- + +```js +function elevatorStops(currentFloor, stops) { + stops = stops.sort((a, b) => a - b); + const above = stops.filter(s => s > currentFloor); + const below = stops.filter(s => s < currentFloor).reverse(); + const upDistance = above.length ? above[above.length - 1] - currentFloor : Infinity; + const downDistance = below.length ? currentFloor - below[below.length - 1] : Infinity; + return downDistance < upDistance ? [...below, ...above] : [...above, ...below]; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0006006.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0006006.md new file mode 100644 index 0000000000000000000000000000000000000000..49e1f21af9b20077040247b4a75073ec591c439f --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0006006.md @@ -0,0 +1,72 @@ +--- +id: 6a2037a68a0bc2aef0006006 +title: "Challenge 344: Golden Ratio" +challengeType: 28 +dashedName: challenge-344 +--- + +# --description-- + +Given two numbers, determine if their ratio approximates the golden ratio. + +- Use a golden ratio of `1.618` +- Allow a tolerance of `0.01` + +# --hints-- + +`isGoldenRatio(21, 34)` should return `true`. + +```js +assert.isTrue(isGoldenRatio(21, 34)); +``` + +`isGoldenRatio(15, 20)` should return `false`. + +```js +assert.isFalse(isGoldenRatio(15, 20)); +``` + +`isGoldenRatio(8, 13)` should return `true`. + +```js +assert.isTrue(isGoldenRatio(8, 13)); +``` + +`isGoldenRatio(10, 16)` should return `false`. + +```js +assert.isFalse(isGoldenRatio(10, 16)); +``` + +`isGoldenRatio(1618, 1000)` should return `true`. + +```js +assert.isTrue(isGoldenRatio(1618, 1000)); +``` + +`isGoldenRatio(88, 55)` should return `false`. + +```js +assert.isFalse(isGoldenRatio(88, 55)); +``` + +# --seed-- + +## --seed-contents-- + +```js +function isGoldenRatio(a, b) { + + return a; +} +``` + +# --solutions-- + +```js +function isGoldenRatio(a, b) { + const goldenRatio = 1.618; + const ratio = Math.max(a, b) / Math.min(a, b); + return Math.abs(ratio - goldenRatio) <= 0.01; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0006007.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0006007.md new file mode 100644 index 0000000000000000000000000000000000000000..4c67cb9bdec6c3fe5098f81749b26ac37a2639bd --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0006007.md @@ -0,0 +1,71 @@ +--- +id: 6a2037a68a0bc2aef0006007 +title: "Challenge 345: Word Blender" +challengeType: 28 +dashedName: challenge-345 +--- + +# --description-- + +Given two words, return a new word by combining the first half of the first word with the second half of the second word. + +- For odd-length words, the first half is the shorter half. + +# --hints-- + +`blendWords("turtle", "toucan")` should return `"turcan"`. + +```js +assert.equal(blendWords("turtle", "toucan"), "turcan"); +``` + +`blendWords("chipmunk", "flamingo")` should return `"chipingo"`. + +```js +assert.equal(blendWords("chipmunk", "flamingo"), "chipingo"); +``` + +`blendWords("falcon", "pelican")` should return `"falican"`. + +```js +assert.equal(blendWords("falcon", "pelican"), "falican"); +``` + +`blendWords("hyena", "iguana")` should return `"hyana"`. + +```js +assert.equal(blendWords("hyena", "iguana"), "hyana"); +``` + +`blendWords("scorpion", "gorilla")` should return `"scorilla"`. + +```js +assert.equal(blendWords("scorpion", "gorilla"), "scorilla"); +``` + +`blendWords("platypus", "wolverine")` should return `"platerine"`. + +```js +assert.equal(blendWords("platypus", "wolverine"), "platerine"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function blendWords(word1, word2) { + + return word1; +} +``` + +# --solutions-- + +```js +function blendWords(word1, word2) { + const firstHalf = word1.slice(0, Math.floor(word1.length / 2)); + const secondHalf = word2.slice(Math.floor(word2.length / 2)); + return firstHalf + secondHalf; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0006008.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0006008.md new file mode 100644 index 0000000000000000000000000000000000000000..b61bd6c4f3a699e7b54f67f784772a2668c3d617 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a2037a68a0bc2aef0006008.md @@ -0,0 +1,81 @@ +--- +id: 6a2037a68a0bc2aef0006008 +title: "Challenge 346: Piggy Bank" +challengeType: 28 +dashedName: challenge-346 +--- + +# --description-- + +Given an object representing a piggy bank, return the total value as a string formatted as `"$D.CC"`. + +The object may contain any of the following: + +| Coin | Value | +|------|-------| +| `pennies` | $0.01 | +| `nickels` | $0.05 | +| `dimes` | $0.10 | +| `quarters` | $0.25 | + +# --hints-- + +`piggyBank({ pennies: 3, nickels: 5, dimes: 2, quarters: 6 })` should return `"$1.98"`. + +```js +assert.equal(piggyBank({ pennies: 3, nickels: 5, dimes: 2, quarters: 6 }), "$1.98"); +``` + +`piggyBank({ pennies: 1, nickels: 1, dimes: 1, quarters: 1 })` should return `"$0.41"`. + +```js +assert.equal(piggyBank({ pennies: 1, nickels: 1, dimes: 1, quarters: 1 }), "$0.41"); +``` + +`piggyBank({ nickels: 8, dimes: 6, quarters: 5 })` should return `"$2.25"`. + +```js +assert.equal(piggyBank({ nickels: 8, dimes: 6, quarters: 5 }), "$2.25"); +``` + +`piggyBank({})` should return `"$0.00"`. + +```js +assert.equal(piggyBank({}), "$0.00"); +``` + +`piggyBank({ pennies: 146, nickels: 11, dimes: 0, quarters: 19 })` should return `"$6.76"`. + +```js +assert.equal(piggyBank({ pennies: 146, nickels: 11, dimes: 0, quarters: 19 }), "$6.76"); +``` + +# --seed-- + +## --seed-contents-- + +```js +function piggyBank(coins) { + + return coins; +} +``` + +# --solutions-- + +```js +function piggyBank(coins) { + const values = { + pennies: 0.01, + nickels: 0.05, + dimes: 0.10, + quarters: 0.25, + }; + + const total = Object.entries(coins).reduce((sum, [coin, count]) => { + return sum + (values[coin] * count); + }, 0); + + return "$" + total.toFixed(2); +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a22d77ddf034bc4e35b1d54.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a22d77ddf034bc4e35b1d54.md new file mode 100644 index 0000000000000000000000000000000000000000..7088db884b48249cba20e6b525d598c0e860c3f3 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a22d77ddf034bc4e35b1d54.md @@ -0,0 +1,81 @@ +--- +id: 6a22d77ddf034bc4e35b1d54 +title: "Challenge 347: Game Theory" +challengeType: 28 +dashedName: challenge-347 +--- + +# --description-- + +Given two equal length strings representing two players' strategies for a game, return the scores as an array `[player1, player2]`. + +- The given strings will only contain one of two letters: `"C"` (cooperate) or `"D"` (defect). +- Each character represents one round, scored as follows: + - If both players cooperate, each scores 3. + - If both players defect, each scores 1. + - If one player defects and the other cooperates, the defector scores 5 and the cooperator scores 0. + +# --hints-- + +`playGame("CCCC", "CCCC")` should return `[12, 12]`. + +```js +assert.deepEqual(playGame("CCCC", "CCCC"), [12, 12]); +``` + +`playGame("DDDD", "DDDD")` should return `[4, 4]`. + +```js +assert.deepEqual(playGame("DDDD", "DDDD"), [4, 4]); +``` + +`playGame("CCDD", "CDDD")` should return `[5, 10]`. + +```js +assert.deepEqual(playGame("CCDD", "CDDD"), [5, 10]); +``` + +`playGame("CCCDCDCCCDDC", "CCDDCDCDDCCD")` should return `[24, 34]`. + +```js +assert.deepEqual(playGame("CCCDCDCCCDDC", "CCDDCDCDDCCD"), [24, 34]); +``` + +`playGame("DDCCDDDDCDDCDDDCDD", "CCDCCCDCCCDCCCCDCC")` should return `[66, 21]`. + +```js +assert.deepEqual(playGame("DDCCDDDDCDDCDDDCDD", "CCDCCCDCCCDCCCCDCC"), [66, 21]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function playGame(p1, p2) { + + return p1; +} +``` + +# --solutions-- + +```js +function playGame(p1, p2) { + let scores = [0, 0]; + + for (let i = 0; i < p1.length; i++) { + if (p1[i] === 'C' && p2[i] === 'C') { + scores[0] += 3; scores[1] += 3; + } else if (p1[i] === 'D' && p2[i] === 'D') { + scores[0] += 1; scores[1] += 1; + } else if (p1[i] === 'D' && p2[i] === 'C') { + scores[0] += 5; scores[1] += 0; + } else { + scores[0] += 0; scores[1] += 5; + } + } + + return scores; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a22d77ddf034bc4e35b1d55.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a22d77ddf034bc4e35b1d55.md new file mode 100644 index 0000000000000000000000000000000000000000..41e2c49961a2ca81936b9b3c336231b6d34043d3 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a22d77ddf034bc4e35b1d55.md @@ -0,0 +1,75 @@ +--- +id: 6a22d77ddf034bc4e35b1d55 +title: "Challenge 348: Loan Calculator" +challengeType: 28 +dashedName: challenge-348 +--- + +# --description-- + +Given a loan amount, annual interest rate percentage, and fixed monthly payment, return an array of remaining balances after each monthly payment until the loan is paid off. + +- Each month, interest is calculated on the remaining balance using the monthly interest rate: `(annual rate / 100) / 12`, then the monthly payment is subtracted. +- Return each remaining balance rounded to the nearest dollar. +- Include the loan amount in the returned array. The first element in the array will always be the loan amount, and the last element of the array will always be 0. + +# --hints-- + +`getLoanSchedule(1000, 0, 200)` should return `[1000, 800, 600, 400, 200, 0]`. + +```js +assert.deepEqual(getLoanSchedule(1000, 0, 200), [1000, 800, 600, 400, 200, 0]); +``` + +`getLoanSchedule(1000, 5, 200)` should return `[1000, 804, 608, 410, 212, 13, 0]`. + +```js +assert.deepEqual(getLoanSchedule(1000, 5, 200), [1000, 804, 608, 410, 212, 13, 0]); +``` + +`getLoanSchedule(10, 50, 1)` should return `[10, 9, 9, 8, 8, 7, 6, 5, 5, 4, 3, 2, 1, 0, 0]`. + +```js +assert.deepEqual(getLoanSchedule(10, 50, 1), [10, 9, 9, 8, 8, 7, 6, 5, 5, 4, 3, 2, 1, 0, 0]); +``` + +`getLoanSchedule(5500, 8, 400)` should return `[5500, 5137, 4771, 4403, 4032, 3659, 3283, 2905, 2525, 2141, 1756, 1367, 977, 583, 187, 0]`. + +```js +assert.deepEqual(getLoanSchedule(5500, 8, 400), [5500, 5137, 4771, 4403, 4032, 3659, 3283, 2905, 2525, 2141, 1756, 1367, 977, 583, 187, 0]); +``` + +`getLoanSchedule(50000, 5.2, 1650)` should return `[50000, 48567, 47127, 45681, 44229, 42771, 41306, 39835, 38358, 36874, 35384, 33887, 32384, 30874, 29358, 27835, 26306, 24770, 23227, 21678, 20122, 18559, 16990, 15413, 13830, 12240, 10643, 9039, 7428, 5810, 4186, 2554, 915, 0]`. + +```js +assert.deepEqual(getLoanSchedule(50000, 5.2, 1650), [50000, 48567, 47127, 45681, 44229, 42771, 41306, 39835, 38358, 36874, 35384, 33887, 32384, 30874, 29358, 27835, 26306, 24770, 23227, 21678, 20122, 18559, 16990, 15413, 13830, 12240, 10643, 9039, 7428, 5810, 4186, 2554, 915, 0]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function getLoanSchedule(loanAmount, annualRate, monthlyPayment) { + + return loanAmount; +} +``` + +# --solutions-- + +```js +function getLoanSchedule(loanAmount, annualRate, monthlyPayment) { + const monthlyRate = (annualRate / 100) / 12; + const balances = [loanAmount]; + let balance = loanAmount; + + while (balance > 0) { + balance += balance * monthlyRate; + balance -= monthlyPayment; + balances.push(Math.round(Math.max(balance, 0))); + } + + return balances; +} +``` diff --git a/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a22d77ddf034bc4e35b1d56.md b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a22d77ddf034bc4e35b1d56.md new file mode 100644 index 0000000000000000000000000000000000000000..5ccc45da364bcde5370c9e8f6ab1f6fe431dbc80 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a22d77ddf034bc4e35b1d56.md @@ -0,0 +1,88 @@ +--- +id: 6a22d77ddf034bc4e35b1d56 +title: "Challenge 349: Cell Signal" +challengeType: 28 +dashedName: challenge-349 +--- + +# --description-- + +Given a grid containing three cell tower readings, determine the location of the phone. + +- Each cell in the grid is either `0` (no tower) or a positive integer representing the number of cells to the phone, measured in a straight line: horizontal, vertical, or diagonal. +- Return the `[row, col]` of the cell that is the correct number of cells from all three towers. +- There is always exactly one solution. + +# --hints-- + +`findSignal([[0, 0, 1], [0, 1, 0], [0, 0, 1]])` should return `[1, 2]`. + +```js +assert.deepEqual(findSignal([[0, 0, 1], [0, 1, 0], [0, 0, 1]]), [1, 2]); +``` + +`findSignal([[0, 2, 0], [1, 0, 0], [0, 0, 1]])` should return `[2, 1]`. + +```js +assert.deepEqual(findSignal([[0, 2, 0], [1, 0, 0], [0, 0, 1]]), [2, 1]); +``` + +`findSignal([[0, 0, 2, 0], [0, 0, 0, 0], [2, 0, 0, 0], [0, 0, 0, 1]])` should return `[2, 2]`. + +```js +assert.deepEqual(findSignal([[0, 0, 2, 0], [0, 0, 0, 0], [2, 0, 0, 0], [0, 0, 0, 1]]), [2, 2]); +``` + +`findSignal([[0, 3, 0, 0, 0], [0, 0, 0, 0, 2], [0, 0, 0, 0, 0], [4, 0, 0, 0, 0], [0, 0, 0, 0, 0]])` should return `[3, 4]`. + +```js +assert.deepEqual(findSignal([[0, 3, 0, 0, 0], [0, 0, 0, 0, 2], [0, 0, 0, 0, 0], [4, 0, 0, 0, 0], [0, 0, 0, 0, 0]]), [3, 4]); +``` + +`findSignal([[3, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 2, 0, 0, 0, 2]])` should return `[3, 3]`. + +```js +assert.deepEqual(findSignal([[3, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 2, 0, 0, 0, 2]]), [3, 3]); +``` + +# --seed-- + +## --seed-contents-- + +```js +function findSignal(grid) { + + return grid; +} +``` + +# --solutions-- + +```js +function findSignal(grid) { + const rows = grid.length; + const cols = grid[0].length; + + const towers = []; + for (let r = 0; r < rows; r++) { + for (let c = 0; c < cols; c++) { + if (grid[r][c] !== 0) towers.push([r, c, grid[r][c]]); + } + } + + function isValid(r, c, tr, tc, dist) { + const dr = Math.abs(r - tr); + const dc = Math.abs(c - tc); + return (dr === dist || dc === dist) && (dr === 0 || dc === 0 || dr === dc); + } + + for (let r = 0; r < rows; r++) { + for (let c = 0; c < cols; c++) { + if (grid[r][c] !== 0) continue; + if (towers.every(([tr, tc, dist]) => isValid(r, c, tr, tc, dist))) { + return [r, c]; + } + } + } +} +```