How to store results of an iteration in a variable - javascript

For educational reasons, I am working through a simple algorithm that randomly generates two numbers and then asks for the addition of generated numbers, tells you if you are right or wrong on response, and tracks results out of 100. I would like to include function that reports something like the following: "You have gotten 80/100 correct" But am held up with syntax, I think. I can't get my score variable to count up with correct answers.
Here is my code as it stands..
do{
var firstnum = Math.floor(Math.random()*10);
var secondnum = Math.floor(Math.random()*10);
var result = firstnum+secondnum;
var score=0;
var answer = prompt("what is "+firstnum + "+" + secondnum);
if(answer < result || answer > result){alert("Wrong! " + "The correct answer
is " + result)};
if(answer == result){alert("you are correct!"), score++};
alert("Awesome, You have gotten " + score + " correct so far!!!");}
while(score<100);
Just get me over the hump. I am hopeful that I can really get my head wrapped around more concepts if I can get through this little guy.

You reset score in every loop to zero. Move the declaration and initialization to top.
Some hints:
no need for semicolons after a block statement { /* code */ },
convertion of strinn to number with unary plus +
use a single if statement with else block for the opposite of the check.
// declare all variables at top
var firstnum,
secondnum,
result,
score = 0,
answer;
do {
firstnum = Math.floor(Math.random() * 10);
secondnum = Math.floor(Math.random() * 10);
result = firstnum + secondnum;
// covert input string to number with unary plus
answer = +prompt("what is " + firstnum + "+" + secondnum);
// ^
// just check the result and omit a second if clause,
// because it is just the opposite check
// take the more easy/shorter check first
if (answer === result ) {
alert("you are correct!");
score++;
} else {
alert("Wrong! " + "The correct answer is " + result)
}
alert("Awesome, You have gotten " + score + " correct so far!!!");
} while (score < 2) // take a small number for scoring check

Related

How do I convert my stopwatch time to a time?

The question may be a little confusing so let me clarify a bit more. I am doing a stop watch so when you start then stop it logs your time. I put that time into an array. When I try to do things like Math.min(array) or Math.max(array) I got NaN (not a number). The stop watch time for example is like 00:00:15.91. Obviously that doesn’t register as a legit number, is there a way to get around this?
In more simpler words: I put a “time” (like 00:00:15.91) into an array, is there a way to still retrieve the largest number or smallest number?
I’m doing this all in javascript, no libraries.
Note: I believe I don’t need to show my code for this, but if you need any, I will be happy to provide it.
else{
let displayTime = displayHours + ":" + displayMinutes + ":" + displaySeconds + "." + displayMilliseconds;
let intTime = displayHours + displayMinutes + displaySeconds + displayMilliseconds;
let times = document.getElementById("times");
window.clearInterval(interval);
status = "stopped";
if (status = "stopped") {
times.innerHTML += displayTime + "<img src='https://img.icons8.com/windows/32/000000/xbox-x.png'/><br/>";
allTimes.push(Number(intTime));
if (allTimes.length == "0") {
document.getElementById("bestTime").innerHTML = "none";
document.getElementById("worstTime").innerHTML = "none";
document.getElementById("average").innerHTML = "none";
document.getElementById("stats").innerHTML = "none";
}
if (allTimes.length != "0") {
document.getElementById("bestTime").innerHTML = Math.min(...allTimes);
}
}
}
edit: I added my code
You can find min and max values ​​by comparing string values. Is type conversion necessary?
const list = ['00:00:23.90', '01:00:00.00', '00:00:23.89', '00:01:00.00']
list.sort()
const min = list(0) // -> "00:00:23.89"
const max = list(list.length-1) // -> "01:00:00.00"

Declaring variable within functions

Ok, so I I'm having this strange behaviour that I cannot explain. Look at the following:
$("#completeData").on("click", function() {
var toUpdate = {};
var toUpdateCount = 0;
var ratios = {};
This.calculateGradePerSize();
//1) Select all sizes that are equal to NA or are Equal to 0 (means its a new one)
$.each(This.logements, function(key, l) {
if (l.sizeMyId === "NA" || l.sizeMyId === 0) {
toUpdate[l.rueNum] = l;
toUpdateCount++;
} else { //else init the ratios because it means they are actually present
/**
//My problem is this variable,
I want it to be equal to an empty object
But for reasons I cannot seem to understand,
it takes in account the latter modification in the code
that happens to this variables
*/
ratios[l.sizeMyId] = {};
}
});
console.log(toUpdate);
console.log(ratios);
console.log(This.sizeRatio);
//2) Calculate Ratios and build the ratios function of the toUpdate
$.each(This.sizeRatio, function(sizeMyId, count) {
if (sizeMyId !== "NA" && sizeMyId != 0) {
console.log("COUNT SIZE: " + count + " COUNT LOGEMENT: " + This.countLogement + " toUpdateCount: " + toUpdateCount + " SizeMyId: " + sizeMyId);
console.log("Calculation: " + count / This.countLogement * toUpdateCount);
ratios[sizeMyId].count = Math.ceil(count / This.countLogement * toUpdateCount);
console.log("Calculation WITH CEIL: " + Math.ceil(count / This.countLogement * toUpdateCount));
ratios[sizeMyId].grade = This.sizeGrade[sizeMyId];
ratios[sizeMyId].sizeMyId = sizeMyId;
}
});
console.log(ratios);
});
As explained in the multiline comment, my problem is the ratio variable. I tried declaring the variable without var prefix, so that JS doesn't know its existence but still, I want it to be empty object. In fact, the problem has stronger roots than simply that, I cannot update it. Each change I make to the ratios var are not registered, but I wanna start with the beginning how can I make sure that this variable is empty at the beginning of the function.
I don't know if this question is really worth. Thinking about deleting it. My bug was that the count variable in the each function as well as the ratio definition were the same hence not registering.
As for the variable not being an empty one at function start. It simply how the JS engine works. If there is something not working, more likely than not, there is something wrong in your code.
$.each(This.sizeRatio, function (sizeMyId, count) {
if (sizeMyId !== "NA" && sizeMyId != 0) {
console.log("COUNT SIZE: " + count + " COUNT LOGEMENT: " + This.countLogement + " toUpdateCount: " + toUpdateCount + " SizeMyId: " + sizeMyId);
console.log("Calculation: " + count / This.countLogement * toUpdateCount);
//HERE ratios[sizeMyId].count IS THE SAME than the anonymous function.
ratios[sizeMyId].count = Math.ceil(count / This.countLogement * toUpdateCount);
console.log("Calculation WITH CEIL: " + Math.ceil(count / This.countLogement * toUpdateCount));
ratios[sizeMyId].grade = This.sizeGrade[sizeMyId];
ratios[sizeMyId].sizeMyId = sizeMyId;
}
});

How to make computer guess a number and return number of guesses (Javascript)?

I'm currently working on a mini-project that I find interesting.
The basic idea is to have the user enter a number between 1 - 5, and have the computer guess that number, showing the number of guesses it took to guess it.
Here is my code so far ...
<html>
<head>
<title>Computer Guessing Game</title>
</head>
<body>
<p>How many fingers are you holding up?</p>
<input type = "text" id= "myNumber">
<button id="guess">Guess!</button>
<script type="text/javascript">
document.getElementById("guess").onclick = function() {
var myNumber = document.getElementById("myNumber").value;
var gotIt = false;
while (gotIt == false) {
var guess = Math.random();
guess = guess * 6;
guess = Math.floor(guess);
if (guess == myNumber) {
gotIt = true;
alert ("Got it! It was a " + guess + ". It took me " + /*number of guesses */ + " guesses.");
} else {
//computer should keep randomly guessing until it guessed correctly
}
}
}
</script>
</body>
As you can see, I can not figure out how to make the computer keep guessing the numbers and then print out to the user the number of guesses it took. I think that it's some sort of loop, but then again, I'm not sure.
Any help is appreciated (excuse me if I'm not writing the question clearly enough, I'm quite new to SO and will get better with time!).
I think you are pretty close to what you want. You can add a variable
var howManyGuesses = 0;
before the while loop, and increment this variable each time you calculate a new random number.
while(gotIt == false){
howManyGuesses = howManyGuesses + 1; //increment the amount of guesses
//your logic
alert ("Got it! It was a " + guess + ". It took me " + howManyGuesses + " guesses.");
}
To prevent it to loop forever you can do something like
var myNumber = document.getElementById("myNumber").value;
if (myNumber < 1 || myNumber > 5) {
alert('Please insert a number between 1 and 5');
return;
}

Javascript - Need to ask the user What is "x" times "y" where x and y are random numbers

So I am completely new to JavaScript and am having a hard time understanding what to do.
I need to ask the user to multiply 2 numbers between 1-10 that are randomly generated.
function Number(1, 10) {
return Math.random() * (10 - 1) + 1;
So how do I then write a function that uses the randomly generated numbers and puts the text in-between it and then checks the answer against the correct answer after it has been input?
I don't want someone to just do it but perhaps point me in the right direction.
The arguments to a function must be variables, not numbers. Also, Javascript already has a global function Number (it's the constructor for the Number object type), you shouldn't redefine it.
function randomNumber(low, high) {
return Math.random() * (high - low) + 1;
}
You can get two numbers with:
var number1 = randomNumber(1, 10);
var number2 = randomNumber(1, 10);
Then you use concatenation to show them in the message to the user:
var answer = parseInt(prompt("What is " + number1 + " times " + number2 + "?"), 10);

Javascript While Loop Returning Strange Results

I apologize in advance if there are several things wrong with my code; I'm still very new to this.
I made a simple little RNG betting game, which follows:
var funds = 100;
var betting = true;
function roll_dice() {
var player = Math.floor(Math.random() * 100);
var com = Math.floor(Math.random() * 100);
var bet = prompt("How much do you bet? Enter a number between 1 and " + funds + " without the $ sign.");
if (player === com) {
alert("tie.");
}
else if (bet > funds) {
alert("You don't have that much money. Please try again");
roll_dice();
}
else if (player > com) {
funds += bet;
alert("Your roll wins by " + (player - com) + " points. You get $" + bet + " and have a total of $" + funds + ".");
}
else {
funds -= bet;
alert("Computer's roll wins by " + (com - player) + " points. You lose $" + bet + " and have a total of $" + funds + ".");
}
}
while (betting) {
var play = prompt("Do you wish to bet? Yes or no?");
if (funds <= 0) {
alert("You have run out of money.");
betting = false;
}
else if (play === "yes") {
roll_dice();
}
else {
alert("Game over.");
betting = false;
}
}
The code deals with losing (i.e. subtraction) just fine, but can't seem to handle the addition part. If you bet, say, 50 and win, you'll wind up with 10050. Aside from never seeking out a job as a gambling software programmer, what should I do?
prompt returns a string. Adding a number to a string results in a string:
> "12" + 13
"1213"
While subtraction results in an integer, as only string concatenation is done with a plus sign:
> "12" - 13
-1
You need to convert your user's input into an integer:
var bet = parseInt(prompt("How much do you bet? Enter a number between 1 and " + funds + " without the $ sign."), 10);

Categories

Resources