What am i doing wrong? it wont run thru every condition - javascript

I'm trying to have someone guess a number from 1 to 6. I give them two tries if, by the end of the second try, they don't get it, then else will tell them what the number is but it just won't run. what am I doing wrong?
var number = Math.floor(Math.random() *6) +1;
var answer = false;
var guess = prompt('Take a guess, pick a number from 1 to 6');
if(parseInt(guess) === number) {
answer === true;
} else if (parseInt(guess) > number) {
var guessLess = prompt('To high! Guess less');
if (parseInt(guessLess) === number) {
answer === true;
} else if (parseInt(guess) < number) {
var guessMore = prompt('Guess more');
if(parseInt(guessMore) === number) {
answer = true;
}
}
}
if (answer) {
alert('You got it')
} else {
alert('No. The number was ' + number);
}
}

You are using comparison instead of assignment in the below segment
if (parseInt(guessLess) === number) {
answer === true;
Change it to
if (parseInt(guessLess) === number) {
answer = true;

Related

How to write a state machine to solve the Count the smiley faces?

I have solved the problem Count the smiley faces:
Given an array (arr) as an argument complete the function countSmileys that should return the total number of smiling faces.
Rules for a smiling face:
Each smiley face must contain a valid pair of eyes. Eyes can be marked as : or ;
A smiley face can have a nose but it does not have to. Valid characters for a nose are - or ~
Every smiling face must have a smiling mouth that should be marked with either ) or D
No additional characters are allowed except for those mentioned.
Valid smiley face examples: :) :D ;-D :~)
Invalid smiley faces: ;( :> :} :]
Example
countSmileys([':)', ';(', ';}', ':-D']); // should return 2;
countSmileys([';D', ':-(', ':-)', ';~)']); // should return 3;
countSmileys([';]', ':[', ';*', ':$', ';-D']); // should return 1;
Note
In case of an empty array return 0. You will not be tested with invalid input (input will always be an array). Order of the face (eyes, nose, mouth) elements will always be the same.
Then when I look through the solutions I find that many people use regexp. Then I want write a state machine to implement regexp and solve this problem. But I failed. This is my code:
function countSmileys(smileys) {
let state = smileyHasValidEye;
return smileys.filter(smiley => {
for (let s of [...smiley]) {
state = state(s);
}
return state === true;
}).length;
}
function smileyHasValidEye(s) {
if (s === ':' || s === ';') {
return smileyHasValidNose;
}
return smileyHasValidEye;
}
function smileyHasValidNose(s) {
if (s === '-' || s === '~') {
return smileyHasValidMouth;
}
return smileyHasValidMouth(s);
}
function smileyHasValidMouth(s) {
if (s === ')' || s === 'D') {
return true;
}
return;
}
console.log(countSmileys([':)', ';(', ';}', ':-D']));
And the error I get is:
state = state(s);
^
TypeError: state is not a function
Then I debugged my code I found the procedure doesn't enter the smileyHasValidNose function. Then I don't know the reason.
The problem is you don't really reset state in between smileys. So the next smiley state will be true which you can't call (it's not a function).
You could use a local variable for state that resets it to the first function (the first step).
function countSmileys(smileys) {
let firstStep = smileyHasValidEye;
return smileys.filter(smiley => {
let state = firstStep;
for (let s of [...smiley]) {
state = state(s);
}
return state === true;
}).length;
}
function smileyHasValidEye(s) {
if (s === ':' || s === ';') {
return smileyHasValidNose;
}
return smileyHasValidEye;
}
function smileyHasValidNose(s) {
if (s === '-' || s === '~') {
return smileyHasValidMouth;
}
return smileyHasValidMouth(s);
}
function smileyHasValidMouth(s) {
if (s === ')' || s === 'D') {
return true;
}
return;
}
console.log(countSmileys([':)', ';(', ';}', ':-D']));
This code however, will error if there's more on the string besides the smiley (or a partial of the smiley).
I would change smileyHasValidMouth to return false if it doesn't detect a smiley. Just to be more consistent here...
function smileyHasValidMouth(s) {
if (s === ')' || s === 'D') {
return true;
}
return false;
}
And adjust your loop to exit early if it finds a value that is not a function.
for (let s of [...smiley]) {
state = state(s);
if(typeof state !== 'function') return state;
}
function countSmileys(smileys) {
let firstStep = smileyHasValidEye;
return smileys.filter(smiley => {
let state = firstStep;
for (let s of [...smiley]) {
state = state(s);
if (typeof state !== 'function') return state;
}
}).length;
}
function smileyHasValidEye(s) {
if (s === ':' || s === ';') {
return smileyHasValidNose;
}
return smileyHasValidEye;
}
function smileyHasValidNose(s) {
if (s === '-' || s === '~') {
return smileyHasValidMouth;
}
return smileyHasValidMouth(s);
}
function smileyHasValidMouth(s) {
if (s === ')' || s === 'D') {
return true;
}
return false;
}
console.log(countSmileys([':~(', ':>', ':D', ':(', ':o>', ';)', ':)']));

I am currently reading Eloquent JavaScript and I'm trying to solve the recursion test, but my code keeps giving me an 'undefined' feedback

This is the sample of my code:
Function isEven(number) {
(number == 1) {
return false;
}
else if (number == 0) {
return true;
}
else {
number += 2;
return isEven(-number);
}
};
This is the result I keep getting:
Console.log(isEven(50)); // undefined
Try using;
function isEven(number) {
if(number == 1) {
return false;
}
else {
if (number == 0) {
return true;
}
else {
number -= 2;
return isEven(number);
}
}
}
console.log(isEven(50));
You had a lot of syntax error as well as logical error. Note this logic only works for positive number. Hope it helps.

Attempting to nest if/else statement in while loop

I'm setting up the following while loop to continue to print a message for each even number entered but print a different message for an odd number and stop:
userEnteredNumber = prompt("Please enter a number:");
while (userEnteredNumber%2 === 0) {
if (userEnteredNumber%2 === 0) {
document.write(userEnteredNumber + EVEN_MESSAGE);
} else if (userEnteredNumber%2 !== 0) {
document.write(userEnteredNumber + NOT_EVEN_MESSAGE);
}
userEnteredNumber = prompt("Please enter a number:");
console.log(userEnteredNumber);
}
Right now it will continue to print with even number entry and stop if an odd number is entered, but the odd number message won't print. Not really understanding why the odd message won't print. Hoping someone can help clarify it for me!
More like this:
while (true) {
userEnteredNumber = prompt("Please enter a number:");
if (userEnteredNumber == null) { // they clicked cancel
break;
}
if (userEnteredNumber%2 === 0) {
document.write(userEnteredNumber + EVEN_MESSAGE);
} else if (userEnteredNumber%2 !== 0) {
document.write(userEnteredNumber + NOT_EVEN_MESSAGE);
} else {
document.write(NOT_VALID_MESSAGE + userEnteredNumber);
}
console.log(userEnteredNumber);
}
From your code, you can change it a bit to look like this:
while (true) {
userEnteredNumber = prompt("Please enter a number:");
if (userEnteredNumber%2 === 0) {
document.write(userEnteredNumber + EVEN_MESSAGE);
} else if (userEnteredNumber%2 !== 0) {
document.write(userEnteredNumber + NOT_EVEN_MESSAGE);
break;
}
console.log(userEnteredNumber);
}

random number doesn't change in loop

The random number doesn't change using while loop. When I want to play again, the randomnumber is still the same.
Here's the code:
randomnumber=Math.floor(Math.random()*10);
while(true){
yourguess=prompt("Please Enter A Number Between 1-10");
if(randomnumber==yourguess){
alert("Good Job");
answer=prompt("Do You Want To Play More ? Y/N")
if(answer=="Y"){
}else{
break;
}
}else{
alert("Not Matched "+ randomnumber);
}
}
You should repeat the generation of the random number when a next game is requested:
var randomnumber = Math.floor(Math.random()*10);
while (true) {
var yourguess = prompt("Please Enter A Number Between 1-10");
if (randomnumber == yourguess) {
alert("Good Job");
var answer = prompt("Do You Want To Play More ? Y/N")
if (answer == "Y") {
randomnumber = Math.floor(Math.random()*10); //<---
} else {
break;
}
} else {
alert("Not Matched "+ randomnumber);
}
}
Make sure to declare your variables (with var, let or const).
You need to generate that randomnumber inside the while loop:
while(true){
var randomnumber=Math.floor(Math.random()*10);
yourguess=prompt("Please Enter A Number Between 1-10");
if(randomnumber==yourguess){
alert("Good Job");
answer=prompt("Do You Want To Play More ? Y/N")
if(answer=="Y"){
}else{
break;
}
}else{
alert("Not Matched "+ randomnumber);
}
}
If you want a different random number each time the loop is executed, you need to generate the randomnumber inside the while loop.
while (true) {
let randomnumber = Math.floor(Math.random() * 10);
yourguess = prompt("Please Enter A Number
Between 1 - 10");
if (randomnumber == yourguess) {
alert("Good Job");
answer = prompt("Do You Want To Play More ? Y/N")
if (answer == "Y") {
} else {
break;
}
} else {
alert("Not Matched " + randomnumber);
}
}
You could make randomnumber a function and call it on loop start. In addition your code snippet was changed a bit in order not to get stuck in a loop of un-closing prompt windows, what was missing is a small part that checks what happens when user does not provide an answer or clicks the cancel button.
var randomnumber = function() { return Math.floor(Math.random()*10); }
while(true){
let number = randomnumber();
yourguess=prompt("Please Enter A Number Between 1-10");
if(!yourguess) {
break;
}
if(number===parseInt(yourguess)){
alert("Good Job");
answer=prompt("Do You Want To Play More ? Y/N");
if(!RegExp("y","gi").test(answer) || !answer){
break;
}
}else{
alert("Not Matched "+ number);
}
}

Create a MR and MC in a javascript calculator

Idealy, I would like my little project to have the memory functions M-, M+, MR and MC.
I was thinking of separate functions and variables to hold the M- and M+.
Is this a normal approach or there is a better one ?
Any idea what might be wrong with my script ? if there is something wrong ?
the number-display ID is the actual calculator screen
the code is :
$(document).ready(function(){
var display = "";
var operators = ["/", "*", "-", "+"];
var decimalAdded = false;
$("button").click(function() {
var key = $(this).text();
//update screen by adding display string to screen with maximum 19 numbers viewable
function updateDisplay() {
if (display.length > 19) {
$("#number-display").html(display.substr(display.length - 19, display.length));
} else {
$("#number-display").html(display.substr(0, 19));
}
}
//clear all entries by resetting display and variables
if (key === "AC" || key === "ON" || key === "MC") {
decimalAdded = false;
display = "";
$("#number-display").html("0");
}
else if (key === "OFF") {
decimalAdded = false;
display = "";
$("#number-display").html("");
}
//clear previous character and reset decimal bool if last character is decimal
else if (key === "CE") {
if (display.substr(display.length - 1, display.length) === ".") {
decimalAdded = false;
}
display = display.substr(0, display.length - 1);
updateDisplay();
}
//add key to display if key is a number
else if (!isNaN(key)) {
display += key;
updateDisplay();
}
//check that . is the first in the number before adding and add 0. or just .
else if (key === ".") {
if (!decimalAdded) {
if(display > 0){
display += key;
}
else {
display += "0" + key;
}
decimalAdded = true;
updateDisplay();
}
}
//if key is basic operator, check that the last input was a number before inputting
else if (operators.indexOf(key) > -1) {
decimalAdded = false;
//first input is a number
if (display.length > 0 && !isNaN(display.substr(display.length - 1, display.length))) {
display += key;
updateDisplay();
}
// allow minus sign as first input
else if (display.length === 0 && key === "-") {
display += key;
updateDisplay();
}
}
// calculate square root of number
else if ( $(this).id === "sqrt") {
var tempStore = display.html();
$("#number-display").html(eval(Math.sqrt(tempStore)));
decimalAdded = false;
}
// change sign of number
else if ($(this).id === "plusmn") {
var newNum = display * -1;
$("#number-display").html(newNum);
}
// create memory plus and minus and calculate MR
else if (key === "M-") {
}
else if (key === "M+") {
}
// percentage function
else if (key === "%"){
}
else if (key == "=") {
//if last input is a decimal or operator, remove from display
if (isNaN(display.substr(display.length - 1, display.length))) {
display = display.substr(0, display.length - 1);
}
var calc = display;
calc = eval(calc);
display = String(calc);
if (display.indexOf('.')) {
decimalAdded = true;
} else {
decimalAdded = false;
}
$("#number-display").html(display);
}
});});
One alternative is a switch statement, which would look something like:
switch (key) {
case "M-":
// do stuff
break;
case "M+":
// do stuff
break;
case "%":
// do stuff
break;
case "=":
// do stuff
break;
}
More documentation on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

Categories

Resources