How to generate a random number only once, and reuse its output? - javascript

I'm learning programming starting with Javascript, and my instructor had us doing a random dice roll, a simple Math.ceil(6*Math.random())
I was trying to slightly gameify it and judge the result. So, if you roll a 7, you win, any other roll you lose. The ultimate result would be,
"You rolled a: 7
You win!"
However, I attempt to accomplish by saying approximately:
console.log("You rolled a: " + diceSum);
if (dicesum() == 7) {
console.log("You win!");
} else {
console.log("Aw... you lose. Better luck next time");
}
diceSum() function evaluates each time, so I may get "You rolled a: 7" and "Aw... you lose" because the first roll was a 7, but by the time the if statement came in, the diceSum was something different.
How do I generate a random number like a dice roll and then reuse its value over and over?
Here's my current code (there is far more than necessary because I'm trying to display the values so I know if it is returning the correct answer):
//Functions
//Generate a random single roll of a dice
var getDieRoll = function() {
return Math.ceil(6*Math.random());
};
//Sum up two dice rolls
var diceSum = function() {
var firstDie = getDieRoll();
var secondDie = getDieRoll();
return firstDie+secondDie;
};
//
//Variables
//Check to see if total sum of the roll is 7
var winMsg = "Winner!"
var loseMsg = "Aw... you lose. Better luck next time."
//
//Outputs
//show total sum to compare with message below
console.log(diceSum())
//Return a message stating the result
console.log("You rolled a " + diceSum())
//View true false status to compare with message returned below
console.log(diceSum()==7)
//If diceSum is a 7, give winning message, otherwise give losing message
if (diceSum()==7){
console.log(winMsg);
} else {
console.log(loseMsg);
}

You put the result in a variable, and use the variable:
var sum = diceSum();
//Outputs
//show total sum to compare with message below
console.log(sum);
//Return a message stating the result
console.log("You rolled a " + sum)
//View true false status to compare with message returned below
console.log(sum == 7);
//If diceSum is a 7, give winning message, otherwise give losing message
if (sum == 7){
console.log(winMsg);
} else {
console.log(loseMsg);
}
By the way, the way to calculate the random number is wrong. The random method is defined to return a value that is 0 <= n < 1, i.e. it can be zero, but it can never be one.
If you use Math.ceil, the effect is that the result will occasionally be zero, and the chance to get a six is slightly smaller than the other numbers.
Use Math.floor instead:
function getDieRoll() {
return Math.floor(6 * Math.random()) + 1;
};

Save it to a variable:
var sum = diceSum();
console.log("You rolled a " + sum);
if (sum == 7) {
console.log(winMsg);
} else {
console.log(loseMsg);
}
Or:
var sum = diceSum(),
msg = sum == 7 ? winMsg : loseMsg;
console.log("You rolled a " + sum);
console.log(msg);

Related

Calculator for test scores javascript

I'd like to create an average calculator for test scores. Have the user enter numbers. They can enter as many as they want. Once they enter “-1”, end the program. Display the lowest test score, the highest test score, the sum of all test scores, and the average of all test scores.
The following is my code. I've already figured out how to do the sum of the scores. However, I don't know how I can turn ALL my inputs into a string - possibly output the lowest (Math.min), highest (Math.max) and average of the test score.
I tried joining strings together but in the end I couldn't figure out how to work!
while (true) {
var itemGrade = parseFloat(prompt("Enter a grade!\n\n(enter -1 to quit)"));
var item = itemGrade + ", "
total += itemGrade;
if (itemGrade == -1) {
break;
}
}
document.write("Total: " + total)
Here is a short piece of code that should do the job. The syntax ${variable} with ` allows variables to become strings. Total score is how you've written it. Lowest and highest simply checks if the new score entered is a higher or lower number and replaces the variable as the new lowest/highest. A count is added to calculate the average of all scores.
var total_score = 0.0;
var average_score = 0.0;
var lowest_score = Infinity;
var highest_score = 0.0;
var count = 0.0;
while (true) {
var itemGrade = parseFloat(prompt("Enter a grade!\n\n(enter -1 to quit)"));
if (itemGrade == -1) {
break;
}
total_score += itemGrade;
if (lowest_score > itemGrade){
lowest_score = itemGrade;
}
if (highest_score < itemGrade){
highest_score = itemGrade;
}
count++;
}
average_score = total_score/count;
document.write("Total Score: " + `${total_score}`);
document.write("Average Score: " + `${average_score}`);
document.write("Lowest Score: " + `${lowest_score}`);
document.write("Highest Score: " + `${highest_score}`);
var item = []
item.push(itemGrade)
You can create an empty array and use push() inside the while loop to add value to end of an array or use unshift() in case you want to add in starting position of the array

How to get a JavaScript factorial programs' loop to show the working used?

Hello there I have been challenged to write a program in JavaScript despite not really knowing much about it that asks the user for a number and then calculates the factorial of that number. I used already asked questions and managed to get the calculation to work but couldn't get the required output. I have to get it in the following output without using any fancy libraries or extra variables/arrays (which I can't think of how to do) :
(assuming user input is 5):
The factorial of 5 is 5*4*3*2*1=120
OR
5! is 5*4*3*2*1=120
Here is the code I've got so far:
//prompts the user for a positive number
var number = parseInt(prompt("Please enter a positive number"));
console.log(number);
//checks the number to see if it is a string
if (isNaN(number)) {
alert("Invalid. Please Enter valid NUMBER")
}
//checks the number to see if it is negaive
else if (number < 0) {
alert("Please Enter valid positive number");
}
//if a positive integer is entered a loop is started to calculate the factorial of the number the user entered
else {
let factorial = 1;
for (count = 1; count <= number; count++) {
factorial *= count;
}
//Sends the inital number back to the user and tells them the factorial of that number
alert("The factorial of " + number + " is " + factorial + ".");
}
I know there are many similar questions to this as I looked around and used them to help me get this far but it is getting the output into the required format that I'm struggling with. I am told it is possible with a loop but don't know where to begin implementing that and I'm only allowed to use that solution.
Unfortunately this is part of a larger program in the challenge and I can only use the following variables:
Number (variable initialised as 0 to hold user input)
Factorial (variable initialised to 1 to hold value of calculated factorial)
Count (variable to hold number of times loop is executed for performing factorial calculation)
Probably you just need to build a string in that loop (on top of calculating the actual value):
let input=parseInt(prompt("Number?"));
let output="";
let result=1;
for(let i=input;i>1;i--){
result*=i;
output+=i+"*";
}
console.log(input+"! is "+output+"1="+result);
The "no-array clause" in your task presumably means that you are not supposed to build an array and use join() on it, like
let arr=[1,2,3,4,5];
console.log(arr.join("*"));
I have updated your code mainly here, Also make sure you are using the same variable num in your code and not number:
let factorials = [];
let result = 1;
for (count = num; count >= 1; count--) {
result *=count;
factorials.push(count);
}
//prompts the user for a positive number
var num = parseInt(prompt("Please enter a positive number"));
console.log(num);
//checks the number to see if it is a string
if (isNaN(num))
{
alert("Invalid. Please Enter valid NUMBER")
}
//checks the number to see if it is negaive
else if (num < 0)
{
alert("Please Enter valid positive number");
}
//if a positive integer is entered a loop is started to calculate the factorial of the number the user entered
else {
let factorials = [];
let result = 1;
for (count = num; count >= 1; count--) {
result *=count;
factorials.push(count);
}
//Sends the inital number back to the user and tells them the factorial of that number
alert("The " + num + "! is " + factorials.join('*') + " is " + result + ".");
}

JavaScript says 10 is lower then 9

I'm trying to learn JavaScript and when I started the MDN Tutorial, I tried to do the first exercise alone, which worked okay so far. But there is one really weird situation.
The Game generates a Random number from 1 - 100 and the User has 10 guesses to find out that number.
I simplified the game to 1 - 10 for this purpose.
When the random number is a 9 and i guess 10, the code says my input was too low. I don't understand why that is. In every other situation, it works exactly as expected.
For debugging reasons, the random number will be shown in the dialog after the first guess.
This is my code:
var number = 0;
var turns = 0;
var guess = 0;
var won = false;
playGame();
function playGame() {
won = false;
number = (Math.random() * 10).toFixed(0);
guess = prompt("Guess a number from 1 to 10");
turns = 0;
while(turns < 10) {
console.log(number + " " + guess);
if(guess < number) {
turns++;
guess = prompt("Number is " + number + ".\n\nYou guessed " + turns + " Times already.\n\nYour guess was to low! Guess again:");
won = false;
} else if(guess > number) {
turns++;
guess = prompt("Number is " + number + ".\n\nYou guessed " + turns + " Times already.\n\nYour guess was to high! Guess again:");
won = false;
} else if(guess === number) {
alert("You got it!");
won = true;
break;
}
}
if(confirm("Wanna play again?")){
playGame()
} else {
alert("kkbye!");
}
}
Thanks in advance. If you see something in my code you'd like to comment, I'd love to hear feedback and become better, even if it isn't directly related to this ;)
The problem is, that you are working with Strings, if you compare two strings with < it will only compare as many characters as it has to until it finds a character that is smaller (smaller being it's Integer representation) than another:
console.log("10" < "9");
Here it will only compare "1" to "9", meaning char code 49 to char code 57.
49 is less than 57, meaning the whole expression is true. You can learn more about the ASCII char codes here.
You should use Numbers instead:
console.log(Number("10") < Number("9"));
You are only dealing with Strings, since both prompt() and Number.toFixed() return Strings. If you encapsulate those in Number() calls your game works:
var number = 0;
var turns = 0;
var guess = 0;
var won = false;
playGame();
function playGame() {
won = false;
number = Number((Math.random() * 10).toFixed(0));
guess = Number(prompt("Guess a number from 1 to 10"));
turns = 0;
while(turns < 10) {
console.log(number + " " + guess);
if(guess < number) {
turns++;
guess = prompt("Number is " + number + ".\n\nYou guessed " + turns + " Times already.\n\nYour guess was too low! Guess again:");
won = false;
} else if(guess > number) {
turns++;
guess = prompt("Number is " + number + ".\n\nYou guessed " + turns + " Times already.\n\nYour guess was too high! Guess again:");
won = false;
} else if(guess === number) {
alert("You got it!");
won = true;
break;
}
}
if(confirm("Wanna play again?")){
playGame()
} else {
alert("kkbye!");
}
}
The Javascript Prompt returns a string. In fact, input text box always returns string. So when you enter 10 it returns "10" and toFixed() will also return string.
So you need to correct two lines from your code
number = parseInt((Math.random() * 10).toFixed(0));
guess = prompt("Guess a number from 1 to 10");
guess = parseInt(guess);
Also you need to check for NAN condition to be on safer side.

Whats wrong with my code? - dice rolling

I am trying to log to the console a message saying : Gratz! You gained 5 points!' after you rolled two the same numbers after each other.
can someone explain me what is wrong with my code?
<script>
var d1 = Math.floor(Math.random()*6) +1;
var diceRolls = [];
function rollDice() {
var die1 = document.getElementById("die1");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random()*6) +1;
console.log("You rolled "+d1+".");
diceRolls.push(d1);
}
if(diceRolls[diceRolls.length - 1] === d1) {
console.log("You won 5 points!");
}
</script>
The problem with your code is that you're checking outside the function, and the condition is not correct. First you need to make sure that the dice has been rolled at least two times, then you compare the two last values. And as #Bergi noted, you also need to call the function, although I guess you're already doing that. Below is the correct solution:
var diceRolls = [];
var totalDiceRolls = 0;
// you set this to whatever you want the limit to be
var maxDiceRolls = 10;
function rollDice() {
if (++totalDiceRolls > maxDiceRolls)
{
alert(maxDiceRolls + " dice rolls allowed at max!");
return;
}
var die1 = document.getElementById("die1");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random()*6) +1;
console.log("You rolled "+d1+".");
diceRolls.push(d1);
if(diceRolls.length > 1 && diceRolls[diceRolls.length - 2] == d1) {
console.log("You won 5 points!");
}
}
You never loop the result, and you assign d1 with a random number, but do nothing with it.
You need to roll the dice and each time, loop the array to find if 2 numbers are the same, at the moment you don't loop, so there is no way to know if 2 numbers are equals.

Nested if/else in While loop

I'm trying to make a program that determines if a grade entered is passing or failing. It stops when the user enters -1. Once the user does enter -1, it has to print out the average of the passing scores and the total amount of scores. It's not really working correctly though. What am I doing wrong?
var countTotal=0; //variable to store total grades.
var countPassing=0; //variable to store total passing scores.
var x= 0; //variable to contain sum of all passing scores.
var grade=parseInt(prompt("Please enter a grade."));
while (grade != (-1*1))
{
if (grade > 65) {
grade=parseInt(prompt("Please enter a grade."));
document.write(grade + " is passing.<br>");
x=x+grade;
countPassing++;
}
else {
grade=parseInt(prompt("Please enter a grade."));
document.write(grade + " is failing.<br>");
}
countTotal++;
}
//Loop ends
document.write("Total # of grades: " + countTotal); //Prints out total # of passing scores.
document.write("Passing average: " + ((x)/(countPassing))); //Prints out average of all passing scores.
Try working through it by hand. The user enters the very first grade. Then the loop starts. Immediately, you ask for a new grade, discarding the first one. If you move the prompt down to the end of the loop, it should work. Like this:
while (grade != (-1*1))
{
if (grade > 65) {
document.write(grade + " is passing.<br>");
x=x+grade;
countPassing++;
}
else {
document.write(grade + " is failing.<br>");
}
grade=parseInt(prompt("Please enter a grade."));
countTotal++;
}

Categories