diff --git a/1-booleans-comparisons-conditionals/README.md b/1-booleans-comparisons-conditionals/README.md index 1ae3725..6f3dc6c 100644 --- a/1-booleans-comparisons-conditionals/README.md +++ b/1-booleans-comparisons-conditionals/README.md @@ -1,8 +1,4 @@ -# 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 +# Part I: Booleans, Comparisons & Conditionals (Solutions) ### Basic Requirements @@ -21,6 +17,7 @@ Before getting started on these exercises, please be certain that you've read th + 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. @@ -41,9 +38,37 @@ Before getting started on these exercises, please be certain that you've read th // => 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: @@ -56,10 +81,30 @@ Before getting started on these exercises, please be certain that you've read th 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, @@ -67,15 +112,61 @@ Before getting started on these exercises, please be certain that you've read th 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 @@ -101,14 +192,79 @@ Before getting started on these exercises, please be certain that you've read th // => 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) @@ -116,9 +272,28 @@ Before getting started on these exercises, please be certain that you've read th + `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. + + "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 071c13f..0b1f575 100644 --- a/2-logical-operators-advanced-conditionals/README.md +++ b/2-logical-operators-advanced-conditionals/README.md @@ -1,8 +1,4 @@ -# 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 +# Part II: Logical Operators & Advanced Conditionals (Solutions) ### Basic Requirements @@ -10,21 +6,23 @@ Before getting started on these exercises, please be certain that you've read th 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) - !(4 === 4) - !(5 !== 5) + !(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 - 5 < 5 || 75 < 74 + 1 > 2 || 2 > 2 || 3 > 2 // => true + 5 < 5 || 75 < 74 // => false ``` #### Conditionals: `else if` & `else` @@ -35,6 +33,18 @@ Before getting started on these exercises, please be certain that you've read th 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. @@ -47,9 +57,20 @@ Before getting started on these exercises, please be certain that you've read th + 'D' >= 60 + 'F' < 60 + **ANSWER:** ```js function scoreToGrade(score) { - // TODO: your code here + 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' @@ -58,6 +79,25 @@ Before getting started on these exercises, please be certain that you've read th 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 @@ -74,6 +114,29 @@ Before getting started on these exercises, please be certain that you've read th + **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 @@ -83,10 +146,63 @@ Before getting started on these exercises, please be certain that you've read th 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 @@ -95,16 +211,40 @@ Before getting started on these exercises, please be certain that you've read th 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) { - // your code here + 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-' @@ -114,8 +254,52 @@ Before getting started on these exercises, please be certain that you've read th 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 db98ed7..8ed6467 100644 --- a/3-variables/README.md +++ b/3-variables/README.md @@ -1,8 +1,4 @@ -# 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 +# Part III: Variables (Solutions) ### Basic Requirements @@ -20,6 +16,17 @@ Before getting started on these exercises, please be certain that you've read th 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. @@ -28,6 +35,13 @@ Before getting started on these exercises, please be certain that you've read th + 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 @@ -41,6 +55,11 @@ Before getting started on these exercises, please be certain that you've read th x; // => ??? ``` + **ANSWER:** + ```js + x; // => 5 + ``` + ```js var x = 17; x = (x + 1) / 2; @@ -48,6 +67,11 @@ Before getting started on these exercises, please be certain that you've read th x; // => ??? ``` + **ANSWER:** + ```js + x; // => 9 + ``` + ```js var x = 5; var y = 20; @@ -56,6 +80,11 @@ Before getting started on these exercises, please be certain that you've read th x; // => ??? ``` + **ANSWER:** + ```js + x; // => 20 + ``` + ```js var x = 10; var y = 5; @@ -65,12 +94,20 @@ Before getting started on these exercises, please be certain that you've read th 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() { - // TODO: your code here + count = count + 1; + return count; } counter(); // => 1 counter(); // => 2 @@ -81,6 +118,8 @@ Before getting started on these exercises, please be certain that you've read th **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.** @@ -115,14 +154,54 @@ Before getting started on these exercises, please be certain that you've read th 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* @@ -130,6 +209,25 @@ Before getting started on these exercises, please be certain that you've read th 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." @@ -141,60 +239,213 @@ Before getting started on these exercises, please be certain that you've read th + "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. -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; -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. + 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!"; + } -### Advanced + function randInt(n) { + return Math.floor(Math.random() * (n + 1)) + } + ``` -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: +6. Whenever a player wins, **increase the difficulty** by increasing the + `upperBound`; whenever a player loses, **decrease the difficulty** by + decreasing the `upperBound`. -1. Initialize the starting values: + **ANSWER:** + ```js + var upperBound = 5; + var randomNum = randInt(upperBound); + var guessCount = 0; + var guessLimit = 4; + var highScore = guessLimit + 1; - - *guess* as half of the *upperBound* - - *lowerBound* as 0 + 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)) + } + ``` -2. Execute *guessMyNumber* with *guess*: +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. - + 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. + **ANSWER:** + ```js + var upperBound = 5; + var randomNum = randInt(upperBound); + var guessCount = 0; + var guessLimit = 4; + var highScore = guessLimit + 1; -**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. + function guessMyNumber(n) { + var hint = ''; + guessCount = guessCount + 1; -Relative to *upperBound*, how many guesses does it take on average to -guess correctly? + if (n < randomNum) { + hint = 'Your guess was too low.'; + } else if (n > randomNum) { + hint = 'Your guess was too high.'; + } -Some recommendations: + 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; + } - + 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. + function randInt(n) { + return Math.floor(Math.random() * (n + 1)) + } + ``` diff --git a/README.md b/README.md index 4ae33f2..aaafb5e 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 may 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.