From 92cc1a183292e8b5ca82b2f3f1e4a7de254a5ec5 Mon Sep 17 00:00:00 2001 From: Tyler Lambe Date: Mon, 6 Jan 2020 12:11:08 -0500 Subject: [PATCH 1/3] initial solutions commit --- 1-booleans-comparisons-conditionals/README.md | 125 +---------- .../README.md | 122 +---------- 3-variables/README.md | 201 +----------------- README.md | 60 +----- 4 files changed, 8 insertions(+), 500 deletions(-) diff --git a/1-booleans-comparisons-conditionals/README.md b/1-booleans-comparisons-conditionals/README.md index 1ae3725..090bae0 100644 --- a/1-booleans-comparisons-conditionals/README.md +++ b/1-booleans-comparisons-conditionals/README.md @@ -1,124 +1 @@ -# Part I: Booleans, Comparisons & Conditionals - -Before getting started on these exercises, please be certain that you've read the primary `README.md` [file](../README.md) in this repository for all of the necessary context. - -## Exercises - -### Basic Requirements - -#### Comparison Operators - -1. Type the two boolean values -- `true` and `false` -- into your console. - -2. Use the console to accomplish the following: - - + Write an expression using `>` that will evaluate to `false` - + Write an expression using `>` that will evaluate to `true` - + Write an expression using `<` that will evaluate to `false` - + Write an expression using `<` that will evaluate to `true` - + Write an expression using two numbers and `===` that will evaluate to `true` - + Write an expression using two numbers and `===` that will evaluate to `false` - + Write an expression using two strings and `===` that will evaluate to `true` - + Write an expression using two strings and `===` that will evaluate to `false` - -3. Fill in the `???` with the following operators or values to make the statements - output the expected Boolean value. - - ```js - 12 ??? 78 - // => true - - 24 ??? 16 - // => false - - 45 !== ??? - // => true - - "45" ??? 45 - // => false - - "6" ??? "six" - // => true - ``` - -4. Write a function `oldEnoughToDrink` that takes an `age` as an argument and - returns `true` if the person with that age is old enough to drink. - -5. There's an easy way to figure out how long a string is by adding `.length` to - the end of it. Try this out in the console: - - ```js - "hello".length; - "".length; - "John Doe".length; - ``` - - Write a function `sameLength` that accepts two strings as arguments, and - returns `true` if those strings have the same length, and `false` otherwise. - -6. Write a function `passwordLongEnough` that accepts a "password" as a - parameter and returns `true` if that password is *long enough* -- you get to - decide what constitutes *long enough*. - -#### Conditionals: `if` - -1. Write a function `bouncer` that accepts a person's name and age as arguments, - and returns either "Go home, NAME.", or "Welcome, NAME!" (where NAME is the - parameter that represents the person's name) depending on whether or not the - person is old enough to drink. - -2. Write a function `max` that takes two numbers as arguments, and returns the - larger one. - -3. Write a function `min` that takes two numbers as arguments, and returns the - smaller one. - -4. Write functions `larger` and `smaller` that each accept two strings as - arguments, and return the *larger* and *smaller* strings, respectively. - -### More Practice - -1. Fill in the `???` with the following operators or values to make the statements - output the expected Boolean value. - - ```js - 106 ??? 12 - // => false - - "wiz" ??? "wiz" - // => true - - 7 * 7 ??? 49 - // => true - - 12 ??? (24 / 2) - // => false - - (20 % 2) <= ??? - // => true - - (9 / 3) + (5 * 5) === ??? - // => true - ``` - -2. Write the following functions that each accept a single number as an - argument: - - + `even`: returns `true` if its argument is even, and `false` otherwise. - + `odd`: the opposite of the above. - + `positive`: returns `true` if its argument is positive, and `false` otherwise. - + `negative`: the opposite of the above. - -3. A couple of other useful built-in mathematical functions are `Math.random`, - `Math.floor` and `Math.ceil`. Look these functions up on - [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math) - to learn how they work, and use them to implement the following functions: - - + `randInt`: Should accept a single numeric argument (`n`), and return a - number from `0` to `n`. - + `guessMyNumber`: Should accept a single numeric argument and compare it to - a random number between `0` and `5`. It should return one of the following - strings: - - - "You guessed my number!" if the argument matches the random number. - - "Nope! That wasn't it!" if the argument did not match the random number. +# Part I: Booleans, Comparisons & Conditionals (Solutions) diff --git a/2-logical-operators-advanced-conditionals/README.md b/2-logical-operators-advanced-conditionals/README.md index 071c13f..12b7d3c 100644 --- a/2-logical-operators-advanced-conditionals/README.md +++ b/2-logical-operators-advanced-conditionals/README.md @@ -1,121 +1 @@ -# Part II: Logical Operators & Advanced Conditionals - -Before getting started on these exercises, please be certain that you've read the primary `README.md` [file](../README.md) in this repository for all of the necessary context. - -## Exercises - -### Basic Requirements - -#### Logical Operators - -1. Is the `!` operator a *unary* operator, or *binary* operator? - -2. Evaluate each of the following expressions first on a whiteboard, and then in - a console: - - ```js - !(2 >= 2) - !(4 === 4) - !(5 !== 5) - ``` - -3. Evaluate each of the following expressions first on a whiteboard, and then in a - console: - - ```js - 1 > 2 || 2 > 2 || 3 > 2 - 5 < 5 || 75 < 74 - ``` - -#### Conditionals: `else if` & `else` - -1. This guy named "Joe" keeps blacking out at the bar that your function, - `bouncer` (from the previous module), is in charge of; thus, management has - decided to add him to the "blacklist" -- modify the `bouncer` function from - the previous section so that the person named "Joe" is rejected with an - appropriate message, regardless of his age. - -2. Write a function called `scoreToGrade` that accepts a *number* as a parameter - and returns a *string* representing a letter grade corresponding to that - score. - - For example, the following grades should be returned given these scores: - - + 'A' >= 90 - + 'B' >= 80 - + 'C' >= 70 - + 'D' >= 60 - + 'F' < 60 - - ```js - function scoreToGrade(score) { - // TODO: your code here - } - scoreToGrade(95); // => 'A' - scoreToGrade(72); // => 'C' - ``` - -3. Modify the `scoreToGrade` function so that it returns `'INVALID SCORE'` if - the score is greater than `100` or less than `0`. - -### More Practice - -1. Think of at least three activities that you enjoy doing outdoors and the - range of temperatures and weather patterns (*e.g* sunny, windy, snowy, rainy, - etc.) that are best for these activities. Write a function `whatToDoOutside` - that accepts a *temperature* and *condition* as parameters and outputs a - string of the format: "The weather is ideal for: ACTIVITY" (where ACTIVITY is - an actual activity). Make sure to include an `else` that indicates what - should be done if the conditions do not match any activities. If you're short - on inspiration, here are some ideas: - - + **Snow Sports:** snowboarding, skiing - + **Water Sports:** surfing, sailing, paddle boarding, swimming - + **Team Sports:** basketball, baseball, football (American or everywhere - else), etc. - -2. The `guessMyNumber` function from the **Booleans & Conditionals** module - (**More Practice** section) accepts a guess `n` and checks it against a - random number from `0` to `5` -- if the guess `n` is greater than `5`, output - a different message indicating that the guess is out of bounds. - - - **NOTE:** It will be helpful to *first* write a `randInt` function that - accepts a number `n` and computes a random integer from `0` to `n`; then, - you can use this function in `guessMyNumber`. - -3. Modify the `scoreToGrade` function so that it returns `'A+/A-'` for - scores of 98-100/90-92 respectively. Apply the same logic for all other - letter grades. - -### Advanced - -1. The bar that employs our `bouncer` function has decided to do live music on - Friday and Saturday nights, and will be admitting those that are over 18 to - the bar on those nights; the catch however, is that all who are 21 or older - will need to be given a wristband to distinguish them from the minors. Modify - your `bouncer` function to handle this situation. - -2. You should have noticed a large amount of repetitive code when modifying - `scoreToGrade` to accommodate `+` or `-` grades. When we do lots of repetitive - things, that's a clear signal that there's a better way. Write a helper function - `letterGrade` that accepts two arguments, *letter* and *score*, and works as - follows: - - ```js - function letterGrade(letter, score) { - // your code here - } - // These are examples of what a *working* function would output. - letterGrade('A', 95); // => 'A' - letterGrade('A', 91); // => 'A-' - letterGrade('B', 88); // => 'B+' - letterGrade('monkey', 160); // => 'monkey-' - ``` - - Finally, use `letterGrade` to remove the repetition in `scoreToGrade`. - -3. It turns out that we can write logical *and* and logical *or* in terms of each - other and logical *not* using De Morgan's Laws. - - + Write a function `or` that works like `||`, but only uses `!` and `&&`. - + Write a function `and` that works like `&&`, but only uses `!` and `||`. +# Part II: Logical Operators & Advanced Conditionals (Solutions) diff --git a/3-variables/README.md b/3-variables/README.md index db98ed7..8384014 100644 --- a/3-variables/README.md +++ b/3-variables/README.md @@ -1,200 +1 @@ -# Part III: Variables - -Before getting started on these exercises, please be certain that you've read the primary `README.md` [file](../README.md) in this repository for all of the necessary context. - -## Exercises - -### Basic Requirements - -1. Fix each of the following variable declarations in a console -- some are - syntactically invalid, some are disobey style guidelines, and some are just - weird. - - ```js - var "animal" = "monkey"; - var "monkey" = animal; - var x= 15; - var y =10; - var var = "huh?"; - var true = false; - var isTenEven = 10 % 2 = 0; - ``` - -2. Perform the following in the console: - - + Create a variable `firstName` and assign your first name to it. - + Create another variable, `lastName`, and assign your last name to it. - + Have a middle name? If so, repeat the process. - + Now, create a variable `fullName` and assign your full name to it by using - the above variables. - - -3. For each of the following code blocks, **use a whiteboard (or a piece of paper)** to reason about - what the value of `x` is supposed to be on the last line. Once you have - arrived at a conclusion that you are comfortable with, enter the lines into a - console and check your answer. Was your hypothesis correct? If not, ensure - that you understand why (talk with a classmate, or ask for help). - - ```js - var x = 5; - x + 10; - x; // => ??? - ``` - - ```js - var x = 17; - x = (x + 1) / 2; - x * 4; - x; // => ??? - ``` - - ```js - var x = 5; - var y = 20; - x = y; - y = y + 7; - x; // => ??? - ``` - - ```js - var x = 10; - var y = 5; - x = (x * 4) - 3; - x + 17; - x = x + y; - x; // => ??? - ``` - -4. Write a function called `counter` that, when invoked, always returns a number - that is *one more* than the previous invocation. For instance: - - ```js - function counter() { - // TODO: your code here - } - counter(); // => 1 - counter(); // => 2 - counter(); // => 3 - // etc. - ``` - - **HINT:** You'll need a variable for this. *Where* should the variable be - declared? - -### More Practice - -**All of the following exercises involve augmenting the `guessMyNumber` function.** - -1. In a previous module you wrote a function called `guessMyNumber` that - simulated a guessing game: the idea is that the function picks a random - number between `0` and `5`, and you invoke the function with your guess -- if - you and the function are thinking of the same number, you win! Otherwise, the - function informs you that your guess was incorrect. A version of this game - might look like this (the `randInt` function is included for convenience): - - ```js - function guessMyNumber(n) { - if (n > 5) { - return "Out of bounds! Please try a number between 0 and 5."; - } else if (n === randInt(5)) { - return "You guessed my number!"; - } - return "Nope! That wasn't it!"; - } - - function randInt(n) { - return Math.floor(Math.random() * (n + 1)) - } - ``` - - Read and test both of the functions in your console and - affirm that you understand how they work; then, answer the following - questions: - - + At present, the guess should be between `0` and `5`. We can think of `5` as - the *upper bound* of the guess. How many times is the *upper bound* - repeated? What if we wanted to change the upper bound to `6`? How many - changes would be required? - + Create a variable called `upperBound` to hold the upper bound, and then - reference **it** instead of the number `5`. If you were asked to change the - upper bound to some other number (*e.g.* `7`), you should only have to make - *one* change. - + Modify `guessMyNumber` so that if the guess is incorrect, `guessMyNumber` - includes the correct guess in its output, *e.g.* `"Nope! The correct number - was: X"` (where `X` would have been the correct number). - - -2. At present, the guessing game picks a new random number every time it is - "played" (invoked). Now that you know how to make information *persistent* - between function invocations, change the guessing game so that it picks a - random number **once** and allows you to guess until you get the correct - answer. - -3. It would be really cool if, after the answer was guessed, the message - included the number of guesses it had taken to find the answer; for example, - "You guessed my number in 3 guesses." - - + **Tangent Problem:** What happens if you get the number right on the - first try? Does it say, "You guessed my number in 1 guesses."? If so, - perhaps the wording should be different? Some better ideas are: - - + "You guessed my number in 1 guess." - + "Congratulations! You guessed my number on the first try!" - - -4. Implement a way to **limit** the number of guesses that can be made so that a - player loses after exceeding the limit. - -5. Keep track of a **high score** (the lowest number of guesses) between games, - and, when the correct number has been guessed in a record number of times, - include in the message something that indicates that a new high score has - been set. - -6. Whenever a player wins, **increase the difficulty** by increasing the - `upperBound`; whenever a player loses, **decrease the difficulty** by - decreasing the `upperBound`. - -7. Implement a **high/low hinting system** to tell the the user that the guess - is either too high or too low. You may want to increase the `upperBound` on - the guess. - -### Advanced - -There is an optimal way to play this game that works like this, given -*upperBound* as the upper bound, *lowerBound* as the lower bound, and *guess* as -the guess: - -1. Initialize the starting values: - - - *guess* as half of the *upperBound* - - *lowerBound* as 0 - - -2. Execute *guessMyNumber* with *guess*: - - + If the guess was **too high**, repeat (2) where: - - the new *guess* is half of the difference of *guess* and *lowerBound* - - the new *upperBound* is *guess* - + If the guess was **too low**, repeat (2) where: - - The new *guess* is half of the difference of *upperBound* and *guess* - - The new *lowerBound* is *guess* - + If the guess was **correct** stop. - -**Your task** is to write a function that implements the above algorithm -to play the game on your behalf. The first thing that you will need to -do is create another version of `guessMyNumber` that returns output that -will be easier for another function to work with, *e.g.* use `1` for too -high, `-1` for too low, `0` for correct. - -Relative to *upperBound*, how many guesses does it take on average to -guess correctly? - -Some recommendations: - - + Make use of a whiteboard. - + Play the existing game yourself using the above steps to get an - idea of how the algorithm works. - + Work with a partner. - + Read about `console.log` on - [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Console/log) - and use it to help with debugging. +# Part III: Variables (Solutions) diff --git a/README.md b/README.md index 4ae33f2..2da4a83 100644 --- a/README.md +++ b/README.md @@ -1,59 +1,9 @@ -# [Hack Reactor](http://www.hackreactor.com): JavaScript 201 Workshop +# [Hack Reactor](https://www.hackreactor.com): JavaScript 201 Workshop (Solutions) -## Overview +Hey there! Welcome to the `solutions` branch of this workshop. Here you will find reference solutions to the practice exercises for Hack Reactor's JavaScript 201 workshop. -#### Scheduled Length: 3 Hours +Much like the `master` branch of this repository, solutions are grouped by section. Please navigate into the respective section's folder on this branch to find its exercise solutions. -Hey there! Ready to get your hands dirty with some code? This is the practice exercise repository for Hack Reactor's JavaScript 201 workshop. JavaScript 201 is the second lesson in our free, four-part Introductory JavaScript Series (101, 201, 301 and 401). We're excited to have you. +**IMPORTANT:** Please do not refer to these solutions until you've given each exercise set a valiant effort. Please also note that only the `Basic Requirements` portions for each section have solutions included. -In order to complete these exercises, open [repl.it](https://repl.it/), choose JavaScript, and then write your code in the left-hand panel. You can run your code using the "Run" button. - -**EXPECTATION:** You will be expected to fully engage during lecture periods. Accordingly, please wait until the designated times during this live workshop to explore the exercises. You will be given 10-15 minutes per section, so please pace yourself accordingly. - -**NEED HELP?** Practice developing your autonomy as a programmer. Use [Google Search](https://www.google.com) or [Stack Overflow](https://www.stackoverflow.com), peruse documentation at [mdn.io](https://www.mdn.io), or talk to your friendly neighbor. If you're utterly stuck, flag down your instructor for guidance. - -**_DISCLAIMER:_** _Completion of this workshop is no guarantee of admission into the Hack Reactor immersive program, nor does it have any influence in the admissions process._ - -## Slides - -The slide deck for this workshop can be found [here](https://docs.google.com/presentation/d/e/2PACX-1vT5IXcwwWbyWo1olk5B-nSa4FiRE0e1Q3ONjM0Zci_Rsd-CbczCSrklEBqbgiKFis69UXdAHCgQBoeH/pub?start=false&loop=false&delayms=3000). - -## Exercises - -Each lecture in this workshop will be followed by a set of self-guided practice exercises. The exercises are divided by section and are housed in their respective folders within this Github repository. - -Each section of practice exercises has a `Basic Requirements` portion. Some sections may also contain additional sections for advanced practice. During the live workshop, you are only expected to complete the `Basic Requirements` sections and may complete the remainder as homework. - -_For your ease of access – click the following links for each section's practice exercises._ - -- Part I: [Booleans, Comparisons & Conditionals](./1-booleans-comparisons-conditionals) -- Part II: [Logical Operators & Advanced Conditionals](./2-logical-operators-advanced-conditionals) -- Part III: [Variables](./3-variables) - -## Exercise Solutions - -You may find reference solutions for this workshop's exercises on the `solutions` [branch](blob/solutions/README.md) of this repository. Please do not refer to the solutions until you've given each problem set a valiant effort. - -## Thinking about JavaScript - -##### Reasoning Methods - -As you embark on your learning journey, a sound method for thinking about JavaScript will be to consider each line of code as a discrete instruction being provided to your computer. - -- What is each line of code intended to do individually? -- How about when combined together? - -It will be beneficial for your growth as a sophisticated programmer to think deeply about the intentions of your code so you can predict and understand the behavior your program produces. - -- _What_ is the expected output of the code? -- _Why_ will the code produce the output that I expect? - -Thinking about each line of code can take many shapes: -- How is this line of code structured and why? -- What syntax rules is this line of code following? Not following? -- Where is this line of code located contextually within the program? -- What references is this line of code making to other parts of the program? Are such references sound? - -##### Vocabulary Development - -Developing your vocabulary as a programmer is as important as learning to write code. To accelerate your conversational capabilities, we recommend partnering with a neighbor to discuss your code at every opportunity. The more opportunities you have to explain yourself, the better. Don't worry – with time, the ambiguity with which you presently speak about code will transform into eloquent prose. +**On Semantics:** Perfectly valid solutions can be written in a different style than the ones you find here. Please don't feel like your solutions need to have the exact same structure as those found herein; there are often numerous ways to solve the same problem in programming. From a087921c9feac0baa9774bf852fa115c6074eb8f Mon Sep 17 00:00:00 2001 From: Tyler Lambe Date: Mon, 6 Jan 2020 12:37:04 -0500 Subject: [PATCH 2/3] solutions added --- 1-booleans-comparisons-conditionals/README.md | 298 ++++++++++++ .../README.md | 304 ++++++++++++ 3-variables/README.md | 450 ++++++++++++++++++ 3 files changed, 1052 insertions(+) diff --git a/1-booleans-comparisons-conditionals/README.md b/1-booleans-comparisons-conditionals/README.md index 090bae0..6f3dc6c 100644 --- a/1-booleans-comparisons-conditionals/README.md +++ b/1-booleans-comparisons-conditionals/README.md @@ -1 +1,299 @@ # Part I: Booleans, Comparisons & Conditionals (Solutions) + +### Basic Requirements + +#### Comparison Operators + +1. Type the two boolean values -- `true` and `false` -- into your console. + +2. Use the console to accomplish the following: + + + Write an expression using `>` that will evaluate to `false` + + Write an expression using `>` that will evaluate to `true` + + Write an expression using `<` that will evaluate to `false` + + Write an expression using `<` that will evaluate to `true` + + Write an expression using two numbers and `===` that will evaluate to `true` + + Write an expression using two numbers and `===` that will evaluate to `false` + + Write an expression using two strings and `===` that will evaluate to `true` + + Write an expression using two strings and `===` that will evaluate to `false` + + +3. Fill in the `???` with the following operators or values to make the statements + output the expected Boolean value. + + ```js + 12 ??? 78 + // => true + + 24 ??? 16 + // => false + + 45 !== ??? + // => true + + "45" ??? 45 + // => false + + "6" ??? "six" + // => true + ``` + + **POTENTIAL ANSWERS**: + ```js + 12 < 78 + // => true + + 24 > 16 + // => false + + 45 !== 46 + // => true + + "45" === 45 + // => false + + "6" !== "six" + // => true + ``` + +4. Write a function `oldEnoughToDrink` that takes an `age` as an argument and + returns `true` if the person with that age is old enough to drink. + + **ANSWER:** + ```js + function oldEnoughToDrink(age) { + if (age >= 21) { + return true; + } + return false; + } + ``` + +5. There's an easy way to figure out how long a string is by adding `.length` to + the end of it. Try this out in the console: + + ```js + "hello".length; + "".length; + "John Doe".length; + ``` + + Write a function `sameLength` that accepts two strings as arguments, and + returns `true` if those strings have the same length, and `false` otherwise. + + **ANSWER:** + ```js + function sameLength(string1, string2) { + if (string1.length === string2.length) { + return true; + } + return false; + } + ``` + +6. Write a function `passwordLongEnough` that accepts a "password" as a + parameter and returns `true` if that password is *long enough* -- you get to + decide what constitutes *long enough*. + + **ANSWER:** + ```js + function passwordLongEnough(password) { + if (password.length >= 8) { + return true; + } + return false; + } + ``` + +#### Conditionals: `if` + +1. Write a function `bouncer` that accepts a person's name and age as arguments, + and returns either "Go home, NAME.", or "Welcome, NAME!" (where NAME is the + parameter that represents the person's name) depending on whether or not the + person is old enough to drink. + + **ANSWER:** + ```js + function bouncer(name, age) { + if (age >= 21) { + return 'Welcome, ' + name + '!'; + } + return 'Go home, ' + name + '.'; + } + ``` + +2. Write a function `max` that takes two numbers as arguments, and returns the + larger one. + + **ANSWER:** + ```js + function max(num1, num2) { + if (num1 > num2) { + return num1; + } + return num2; + } + ``` + +3. Write a function `min` that takes two numbers as arguments, and returns the + smaller one. + + **ANSWER:** + ```js + function min(num1, num2) { + if (num1 < num2) { + return num1; + } + return num2; + } + ``` + +4. Write functions `larger` and `smaller` that each accept two strings as + arguments, and return the *larger* and *smaller* strings, respectively. + + **ANSWER:** + ```js + function larger(string1, string2) { + if (string1.length > string2.length) { + return string1; + } + return string2; + } + + function smaller(string1, string2) { + if (string1.length < string2.length) { + return string1; + } + return string2; + } + +### More Practice + +1. Fill in the `???` with the following operators or values to make the statements + output the expected Boolean value. + + ```js + 106 ??? 12 + // => false + + "wiz" ??? "wiz" + // => true + + 7 * 7 ??? 49 + // => true + + 12 ??? (24 / 2) + // => false + + (20 % 2) <= ??? + // => true + + (9 / 3) + (5 * 5) === ??? + // => true + ``` + + **POTENTIAL ANSWERS**: + ```js + 106 <= 12 + // => false + + "wiz" === "wiz" + // => true + + 7 * 7 === 49 + // => true + + 12 !== (24 / 2) + // => false + + (20 % 2) <= 10 + // => true + + (9 / 3) + (5 * 5) === 28 + // => true + ``` + +2. Write the following functions that each accept a single number as an + argument: + + + `even`: returns `true` if its argument is even, and `false` otherwise. + + **ANSWER:** + ```js + function even(num) { + // The number is even if it can be divided by 2 with no remainder + if (num % 2 === 0) { + return true; + } + return false; + } + ``` + + + `odd`: the opposite of the above. + + **ANSWER:** + ```js + function odd(num) { + // The number is odd if it cannot be divided by 2 with no remainder + if (num % 2 !== 0) { + return true; + } + return false; + } + ``` + + `positive`: returns `true` if its argument is positive, and `false` otherwise. + + **ANSWER:** + ```js + function positive(num) { + if (num >= 0) { + return true; + } + return false; + } + ``` + + + `negative`: the opposite of the above. + + **ANSWER:** + ```js + function negative(num) { + if (num < 0) { + return true; + } + return false; + } + ``` + +3. A couple of other useful built-in mathematical functions are `Math.random`, + `Math.floor` and `Math.ceil`. Look these functions up on + [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math) + to learn how they work, and use them to implement the following functions: + + + `randInt`: Should accept a single numeric argument (`n`), and return a + number from `0` to `n`. + + **ANSWER:** + ```js + function randInt(n) { + return Math.floor(Math.random() * (n + 1)); + } + ``` + + + `guessMyNumber`: Should accept a single numeric argument and compare it to + a random number between `0` and `5`. It should return one of the following + strings: + + + "You guessed my number!" if the argument matches the random number. + + "Nope! That wasn't it!" if the argument did not match the random number. + + **ANSWER:** + ```js + function guessMyNumber(guess) { + var randomNum = Math.floor(Math.random() * 6); + if (guess === randomNum) { + return "You guessed my number!"; + } + return "Nope! That wasn't it!"; + } + ``` diff --git a/2-logical-operators-advanced-conditionals/README.md b/2-logical-operators-advanced-conditionals/README.md index 12b7d3c..0b1f575 100644 --- a/2-logical-operators-advanced-conditionals/README.md +++ b/2-logical-operators-advanced-conditionals/README.md @@ -1 +1,305 @@ # Part II: Logical Operators & Advanced Conditionals (Solutions) + +### Basic Requirements + +#### Logical Operators + +1. Is the `!` operator a *unary* operator, or *binary* operator? + + **ANSWER:** It is a unary operator, because it has only one operand. + +2. Evaluate each of the following expressions first on a whiteboard, and then in + a console: + + ```js + !(2 >= 2) // => false + !(4 === 4) // => false + !(5 !== 5) // => true + ``` + +3. Evaluate each of the following expressions first on a whiteboard, and then in a + console: + + ```js + 1 > 2 || 2 > 2 || 3 > 2 // => true + 5 < 5 || 75 < 74 // => false + ``` + +#### Conditionals: `else if` & `else` + +1. This guy named "Joe" keeps blacking out at the bar that your function, + `bouncer` (from the previous module), is in charge of; thus, management has + decided to add him to the "blacklist" -- modify the `bouncer` function from + the previous section so that the person named "Joe" is rejected with an + appropriate message, regardless of his age. + + **ANSWER:** + ```js + function bouncer(name, age) { + if (name === 'Joe') { + return 'Go home, ' + name + '. You are banned from the bar.'; + } else if (age >= 21) { + return 'Welcome, ' + name + '!'; + } + return 'Go home, ' + name + '.'; + } + ``` + +2. Write a function called `scoreToGrade` that accepts a *number* as a parameter + and returns a *string* representing a letter grade corresponding to that + score. + + For example, the following grades should be returned given these scores: + + + 'A' >= 90 + + 'B' >= 80 + + 'C' >= 70 + + 'D' >= 60 + + 'F' < 60 + + **ANSWER:** + ```js + function scoreToGrade(score) { + if (score >= 90) { + return 'A'; + } else if (score >= 80) { + return 'B'; + } else if (score >= 70) { + return 'C'; + } else if (score >= 60) { + return 'D'; + } else { + return 'F'; + } + } + scoreToGrade(95); // => 'A' + scoreToGrade(72); // => 'C' + ``` + +3. Modify the `scoreToGrade` function so that it returns `'INVALID SCORE'` if + the score is greater than `100` or less than `0`. + + **ANSWER:** + ```js + function scoreToGrade(score) { + if (score > 100 || score < 0) { + return 'INVALID SCORE'; + } else if (score >= 90) { + return 'A'; + } else if (score >= 80) { + return 'B'; + } else if (score >= 70) { + return 'C'; + } else if (score >= 60) { + return 'D'; + } else { + return 'F'; + } + } + ``` + +### More Practice + +1. Think of at least three activities that you enjoy doing outdoors and the + range of temperatures and weather patterns (*e.g* sunny, windy, snowy, rainy, + etc.) that are best for these activities. Write a function `whatToDoOutside` + that accepts a *temperature* and *condition* as parameters and outputs a + string of the format: "The weather is ideal for: ACTIVITY" (where ACTIVITY is + an actual activity). Make sure to include an `else` that indicates what + should be done if the conditions do not match any activities. If you're short + on inspiration, here are some ideas: + + + **Snow Sports:** snowboarding, skiing + + **Water Sports:** surfing, sailing, paddle boarding, swimming + + **Team Sports:** basketball, baseball, football (American or everywhere + else), etc. + + **ANSWER:** + ```js + function whatToDoOutside(temperature, condition) { + var activity = ''; + + if (temperature >= 80 && condition === 'sunny') { + activity = 'swimming'; + } else if (temperature >= 80 && condition === 'windy') { + activity = 'sailing'; + } else if (temperature >= 60 && condition === 'sunny') { + activity = 'basketball'; + } else if (temperature >= 60 && condition === 'windy') { + activity = 'hiking'; + } else if (temperature < 60 && condition === 'snowy') { + activity = 'skiing'; + } else { + activity = 'building a bonfire'; + } + + return 'The weather is ideal for: ' + activity + '.'; + } + ``` + +2. The `guessMyNumber` function from the **Booleans & Conditionals** module + (**More Practice** section) accepts a guess `n` and checks it against a + random number from `0` to `5` -- if the guess `n` is greater than `5`, output + a different message indicating that the guess is out of bounds. + + - **NOTE:** It will be helpful to *first* write a `randInt` function that + accepts a number `n` and computes a random integer from `0` to `n`; then, + you can use this function in `guessMyNumber`. + + **ANSWER:** + ```js + function randInt(n) { + return Math.floor(Math.random() * (n + 1)); + } + + function guessMyNumber(n) { + var randomNum = randInt(5); + + if (n > 5) { + return "Your guess is out bounds." + } else if (n === randomNum) { + return "You guessed my number!"; + } + return "Nope! That wasn't it!"; + } + ``` + +3. Modify the `scoreToGrade` function so that it returns `'A+/A-'` for + scores of 98-100/90-92 respectively. Apply the same logic for all other + letter grades. + + **ANSWER:** + ```js + function scoreToGrade(score) { + if (score > 100 || score < 0) { + return 'INVALID SCORE'; + } else if (score >= 98) { + return 'A+'; + } else if (score >= 93) { + return 'A'; + } else if (score >= 90) { + return 'A-'; + } else if (score >= 88) { + return 'B+'; + } else if (score >= 83) { + return 'B'; + } else if (score >= 80) { + return 'B-'; + } else if (score >= 78) { + return 'C+'; + } else if (score >= 73) { + return 'C'; + } else if (score >= 70) { + return 'C-'; + } else if (score >= 68) { + return 'D+'; + } else if (score >= 63) { + return 'D'; + } else if (score >= 60) { + return 'D-'; + } else { + return 'F'; + } + } + ``` + +### Advanced + +1. The bar that employs our `bouncer` function has decided to do live music on + Friday and Saturday nights, and will be admitting those that are over 18 to + the bar on those nights; the catch however, is that all who are 21 or older + will need to be given a wristband to distinguish them from the minors. Modify + your `bouncer` function to handle this situation. + + **ANSWER:** + ```js + function bouncer(name, age, day) { + if (name === 'Joe') { + return 'Go home, ' + name + '. You are banned from the bar.'; + } else if ((day === 'Friday' || day === 'Saturday') && age >= 21) { + return 'Welcome, ' + name + '! Here is your wristband.' + } else if ((day === 'Friday' || day === 'Saturday') && age >= 18) { + return 'Welcome, ' + name + '! You can come in but no drinking.' + } else if (age >= 21) { + return 'Welcome, ' + name + '!'; + } + return 'Go home, ' + name + '.'; + } + ``` + +2. You should have noticed a large amount of repetitive code when modifying + `scoreToGrade` to accommodate `+` or `-` grades. When we do lots of repetitive + things, that's a clear signal that there's a better way. Write a helper function + `letterGrade` that accepts two arguments, *letter* and *score*, and works as + follows: + + **ANSWER:** + ```js + function letterGrade(letter, score) { + if (score % 10 >= 8) { + return letter + '+'; + } else if (score % 10 >= 3) { + return letter; + } else { + return letter + '-'; + } + } + + // These are examples of what a *working* function would output. + letterGrade('A', 95); // => 'A' + letterGrade('A', 91); // => 'A-' + letterGrade('B', 88); // => 'B+' + letterGrade('monkey', 160); // => 'monkey-' + ``` + + Finally, use `letterGrade` to remove the repetition in `scoreToGrade`. + + **ANSWER:** + ```js + function scoreToGrade(score) { + if (score > 100 || score < 0) { + return 'INVALID SCORE'; + } else if (score === 100) { + return 'A+'; + } else if (score >= 90) { + return letterGrade('A', score); + } else if (score >= 80) { + return letterGrade('B', score); + } else if (score >= 70) { + return letterGrade('C', score); + } else if (score >= 60) { + return letterGrade('D', score); + } else { + return 'F'; + } + } + ``` + +3. It turns out that we can write logical *and* and logical *or* in terms of each + other and logical *not* using De Morgan's Laws. + + + Write a function `or` that works like `||`, but only uses `!` and `&&`. + + **ANSWER:** + ```js + function or(a, b) { + return !(!a && !b); + } + + or(true, false); // => true + or(true, true); // => true + or(false, false); // => false + ``` + + + Write a function `and` that works like `&&`, but only uses `!` and `||`. + + **ANSWER:** + ```js + function and(a, b) { + return !(!a || !b); + } + + and(true, false); // => false + and(true, true); // => true + and(false, false); // => false + ``` diff --git a/3-variables/README.md b/3-variables/README.md index 8384014..8ed6467 100644 --- a/3-variables/README.md +++ b/3-variables/README.md @@ -1 +1,451 @@ # Part III: Variables (Solutions) + +### Basic Requirements + +1. Fix each of the following variable declarations in a console -- some are + syntactically invalid, some are disobey style guidelines, and some are just + weird. + + ```js + var "animal" = "monkey"; + var "monkey" = animal; + var x= 15; + var y =10; + var var = "huh?"; + var true = false; + var isTenEven = 10 % 2 = 0; + ``` + + **FIXED:** + ```js + var animal = "monkey"; + var monkey = animal; + var x = 15; + var y = 10; + var variable = "huh?"; + var truth = false; + var isTenEven = 10 % 2 === 0; + ``` + +2. Perform the following in the console: + + + Create a variable `firstName` and assign your first name to it. + + Create another variable, `lastName`, and assign your last name to it. + + Have a middle name? If so, repeat the process. + + Now, create a variable `fullName` and assign your full name to it by using + the above variables. + + **ANSWER:** + ```js + var firstName = 'Michael'; + var lastName = 'Jordan'; + var middleName = 'Jeffrey'; + var fullName = firstName + ' ' + middleName + ' ' + lastName; + ``` + +3. For each of the following code blocks, **use a whiteboard (or a piece of paper)** to reason about + what the value of `x` is supposed to be on the last line. Once you have + arrived at a conclusion that you are comfortable with, enter the lines into a + console and check your answer. Was your hypothesis correct? If not, ensure + that you understand why (talk with a classmate, or ask for help). + + ```js + var x = 5; + x + 10; + x; // => ??? + ``` + + **ANSWER:** + ```js + x; // => 5 + ``` + + ```js + var x = 17; + x = (x + 1) / 2; + x * 4; + x; // => ??? + ``` + + **ANSWER:** + ```js + x; // => 9 + ``` + + ```js + var x = 5; + var y = 20; + x = y; + y = y + 7; + x; // => ??? + ``` + + **ANSWER:** + ```js + x; // => 20 + ``` + + ```js + var x = 10; + var y = 5; + x = (x * 4) - 3; + x + 17; + x = x + y; + x; // => ??? + ``` + + **ANSWER:** + ```js + x; // => 42 + ``` + +4. Write a function called `counter` that, when invoked, always returns a number + that is *one more* than the previous invocation. For instance: + + ```js + var count = 0; + + function counter() { + count = count + 1; + return count; + } + counter(); // => 1 + counter(); // => 2 + counter(); // => 3 + // etc. + ``` + + **HINT:** You'll need a variable for this. *Where* should the variable be + declared? + + **ANSWER:** Declaring the variable outside of the function (in global scope) allows the program to properly track how many times the counter() function has been called. The value of the count variable is persistent. + +### More Practice + +**All of the following exercises involve augmenting the `guessMyNumber` function.** + +1. In a previous module you wrote a function called `guessMyNumber` that + simulated a guessing game: the idea is that the function picks a random + number between `0` and `5`, and you invoke the function with your guess -- if + you and the function are thinking of the same number, you win! Otherwise, the + function informs you that your guess was incorrect. A version of this game + might look like this (the `randInt` function is included for convenience): + + ```js + function guessMyNumber(n) { + if (n > 5) { + return "Out of bounds! Please try a number between 0 and 5."; + } else if (n === randInt(5)) { + return "You guessed my number!"; + } + return "Nope! That wasn't it!"; + } + + function randInt(n) { + return Math.floor(Math.random() * (n + 1)) + } + ``` + + Read and test both of the functions in your console and + affirm that you understand how they work; then, answer the following + questions: + + + At present, the guess should be between `0` and `5`. We can think of `5` as + the *upper bound* of the guess. How many times is the *upper bound* + repeated? What if we wanted to change the upper bound to `6`? How many + changes would be required? + + **ANSWER:** Changes would be needed each time the number 5 is used. For the function above, that would be 3 changes in total. + + + Create a variable called `upperBound` to hold the upper bound, and then + reference **it** instead of the number `5`. If you were asked to change the + upper bound to some other number (*e.g.* `7`), you should only have to make + *one* change. + + **ANSWER:** + ```js + function guessMyNumber(n) { + var upperBound = 5; + + if (n > upperBound) { + return "Out of bounds! Please try a number between 0 and " + upperBound + "."; + } else if (n === randInt(upperBound)) { + return "You guessed my number!"; + } + return "Nope! That wasn't it!"; + } + + function randInt(n) { + return Math.floor(Math.random() * (n + 1)) + } + ``` + + + Modify `guessMyNumber` so that if the guess is incorrect, `guessMyNumber` + includes the correct guess in its output, *e.g.* `"Nope! The correct number + was: X"` (where `X` would have been the correct number). + + **ANSWER:** + ```js + function guessMyNumber(n) { + var upperBound = 5; + var randomNum = randInt(upperBound); + + if (n > upperBound) { + return "Out of bounds! Please try a number between 0 and " + upperBound + "."; + } else if (n === randomNum)) { + return "You guessed my number!"; + } + return "Nope! That wasn't it! The correct answer was: " + randomNum; + } + + function randInt(n) { + return Math.floor(Math.random() * (n + 1)) + } + ``` + +2. At present, the guessing game picks a new random number every time it is + "played" (invoked). Now that you know how to make information *persistent* + between function invocations, change the guessing game so that it picks a + random number **once** and allows you to guess until you get the correct + answer. + + **ANSWER:** + ```js + var upperBound = 5; + var randomNum = randInt(upperBound); + + function guessMyNumber(n) { + if (n > upperBound) { + return "Out of bounds! Please try a number between 0 and " + upperBound + "."; + } else if (n === randomNum) { + return "You guessed my number!"; + } + return "Nope! That wasn't it!"; + } + + function randInt(n) { + return Math.floor(Math.random() * (n + 1)) + } + ``` + +3. It would be really cool if, after the answer was guessed, the message + included the number of guesses it had taken to find the answer; for example, + "You guessed my number in 3 guesses." + + + **Tangent Problem:** What happens if you get the number right on the + first try? Does it say, "You guessed my number in 1 guesses."? If so, + perhaps the wording should be different? Some better ideas are: + + + "You guessed my number in 1 guess." + + "Congratulations! You guessed my number on the first try!" + + **ANSWER:** + ```js + var upperBound = 5; + var randomNum = randInt(upperBound); + var guessCount = 0; + + function guessMyNumber(n) { + guessCount = guessCount + 1; + + if (n > upperBound) { + return "Out of bounds! Please try a number between 0 and " + upperBound + "."; + } else if (n === randomNum && guessCount === 1) { + return "Congratulations! You guessed my number on the first try!"; + } else if (n === randomNum) { + return "You guessed my number! It took you " + guessCount + ' guesses.'; + } + return "Nope! That wasn't it!"; + } + + function randInt(n) { + return Math.floor(Math.random() * (n + 1)) + } + ``` + +4. Implement a way to **limit** the number of guesses that can be made so that a + player loses after exceeding the limit. + + **ANSWER:** + ```js + var upperBound = 5; + var randomNum = randInt(upperBound); + var guessCount = 0; + var guessLimit = 4; + + function guessMyNumber(n) { + guessCount = guessCount + 1; + + if (guessCount > guessLimit) { + randomNum = randInt(upperBound); + return "You have exceeded the maximum number of guesses. You lose!"; + } else if (n > upperBound) { + return "Out of bounds! Please try a number between 0 and " + upperBound + "."; + } else if (n === randomNum && guessCount === 1) { + randomNum = randInt(upperBound); + return "Congratulations! You guessed my number on the first try!"; + } else if (n === randomNum) { + randomNum = randInt(upperBound); + return "You guessed my number! It took you " + guessCount + ' guesses.'; + } + return "Nope! That wasn't it!"; + } + + function randInt(n) { + return Math.floor(Math.random() * (n + 1)) + } + ``` + +5. Keep track of a **high score** (the lowest number of guesses) between games, + and, when the correct number has been guessed in a record number of times, + include in the message something that indicates that a new high score has + been set. + + **ANSWER:** + ```js + var upperBound = 5; + var randomNum = randInt(upperBound); + var guessCount = 0; + var guessLimit = 4; + var highScore = guessLimit + 1; + + function guessMyNumber(n) { + guessCount = guessCount + 1; + + if (guessCount > guessLimit) { + guessCount = 0; + randomNum = randInt(upperBound); + return "You have exceeded the maximum number of guesses. You lose!"; + } else if (n > upperBound) { + return "Out of bounds! Please try a number between 0 and " + upperBound + "."; + } else if (n === randomNum && guessCount === 1 && guessCount < highScore) { + highScore = guessCount; + guessCount = 0; + randomNum = randInt(upperBound); + return "Congratulations! You guessed my number on the first try! And you set a new high score!"; + } else if (n === randomNum && guessCount < highScore) { + var guesses = guessCount; + highScore = guessCount; + guessCount = 0; + randomNum = randInt(upperBound); + return "You guessed my number! It took you " + guesses + ' guesses, which is a new high score!'; + } else if (n === randomNum) { + var guesses = guessCount; + guessCount = 0; + randomNum = randInt(upperBound); + return "You guessed my number! It took you " + guesses + ' guesses.'; + } + return "Nope! That wasn't it!"; + } + + function randInt(n) { + return Math.floor(Math.random() * (n + 1)) + } + ``` + +6. Whenever a player wins, **increase the difficulty** by increasing the + `upperBound`; whenever a player loses, **decrease the difficulty** by + decreasing the `upperBound`. + + **ANSWER:** + ```js + var upperBound = 5; + var randomNum = randInt(upperBound); + var guessCount = 0; + var guessLimit = 4; + var highScore = guessLimit + 1; + + function guessMyNumber(n) { + guessCount = guessCount + 1; + + if (guessCount > guessLimit) { + guessCount = 0; + upperBound = upperBound - 1; + randomNum = randInt(upperBound); + return "You have exceeded the maximum number of guesses. You lose!"; + } else if (n > upperBound) { + return "Out of bounds! Please try a number between 0 and " + upperBound + "."; + } else if (n === randomNum && guessCount === 1 && guessCount < highScore) { + highScore = guessCount; + guessCount = 0; + upperBound = upperBound + 1; + randomNum = randInt(upperBound); + return "Congratulations! You guessed my number on the first try! And you set a new high score!"; + } else if (n === randomNum && guessCount < highScore) { + var guesses = guessCount; + highScore = guessCount; + guessCount = 0; + upperBound = upperBound + 1; + randomNum = randInt(upperBound); + return "You guessed my number! It took you " + guesses + ' guesses, which is a new high score!'; + } else if (n === randomNum) { + var guesses = guessCount; + guessCount = 0; + upperBound = upperBound + 1; + randomNum = randInt(upperBound); + return "You guessed my number! It took you " + guesses + ' guesses.'; + } + return "Nope! That wasn't it!"; + } + + function randInt(n) { + return Math.floor(Math.random() * (n + 1)) + } + ``` + +7. Implement a **high/low hinting system** to tell the the user that the guess + is either too high or too low. You may want to increase the `upperBound` on + the guess. + + **ANSWER:** + ```js + var upperBound = 5; + var randomNum = randInt(upperBound); + var guessCount = 0; + var guessLimit = 4; + var highScore = guessLimit + 1; + + function guessMyNumber(n) { + var hint = ''; + guessCount = guessCount + 1; + + if (n < randomNum) { + hint = 'Your guess was too low.'; + } else if (n > randomNum) { + hint = 'Your guess was too high.'; + } + + if (guessCount > guessLimit) { + guessCount = 0; + upperBound = upperBound - 1; + randomNum = randInt(upperBound); + return "You have exceeded the maximum number of guesses. You lose!"; + } else if (n > upperBound) { + return "Out of bounds! Please try a number between 0 and " + upperBound + "."; + } else if (n === randomNum && guessCount === 1 && guessCount < highScore) { + highScore = guessCount; + guessCount = 0; + upperBound = upperBound + 1; + randomNum = randInt(upperBound); + return "Congratulations! You guessed my number on the first try! And you set a new high score!"; + } else if (n === randomNum && guessCount < highScore) { + var guesses = guessCount; + highScore = guessCount; + guessCount = 0; + upperBound = upperBound + 1; + randomNum = randInt(upperBound); + return "You guessed my number! It took you " + guesses + ' guesses, which is a new high score!'; + } else if (n === randomNum) { + var guesses = guessCount; + guessCount = 0; + upperBound = upperBound + 1; + randomNum = randInt(upperBound); + return "You guessed my number! It took you " + guesses + ' guesses.'; + } + return "Nope! That wasn't it! " + hint; + } + + function randInt(n) { + return Math.floor(Math.random() * (n + 1)) + } + ``` From 558681eba84336ce7d6b66a2f99aad5c92030ecc Mon Sep 17 00:00:00 2001 From: Tyler Lambe Date: Mon, 6 Jan 2020 14:41:19 -0500 Subject: [PATCH 3/3] updates expectations --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2da4a83..aaafb5e 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,6 @@ Hey there! Welcome to the `solutions` branch of this workshop. Here you will fin Much like the `master` branch of this repository, solutions are grouped by section. Please navigate into the respective section's folder on this branch to find its exercise solutions. -**IMPORTANT:** Please do not refer to these solutions until you've given each exercise set a valiant effort. Please also note that only the `Basic Requirements` portions for each section have solutions included. +**IMPORTANT:** Please do not refer to these solutions until you've given each exercise set a valiant effort. Please also note that only the `Basic Requirements` portions for each section may have solutions included. **On Semantics:** Perfectly valid solutions can be written in a different style than the ones you find here. Please don't feel like your solutions need to have the exact same structure as those found herein; there are often numerous ways to solve the same problem in programming.