I'm fairly new to coding and have this practice that I can't figure out the last part of it.
I'm rolling three dice and supposed to count how many combined value of sevens I get at 1000th roll.
Do I have to create an array? the hint given to me was to create a counter variable. But I can't find any solution. I know it must be something simple. I need your guidance!
var getRandomInt = function(x) {
var result = 0;
result = Math.floor((Math.random() * x) + 1);
return result;
};
//variables I need
var diceOne = 0;
var diceTwo = 0;
var diceThree = 0;
var diceSum = 0;
var roll = 0;
var average = 0;
for (var i = 1; i <= 1000; i++) {
//Simulate a Dice Roll
diceOne = getRandomInt(6);
diceTwo = getRandomInt(6);
diceThree = getRandomInt(6);
roll = roll + 1;
diceSum = diceOne + diceTwo + diceThree;
average += diceSum / 1000;
console.log("Roll #" + roll);
console.log("Value of Dice 1 is " + diceOne);
console.log("Value of Dice 2 is " + diceTwo);
console.log("Value of Dice 3 is " + diceThree);
console.log("The Sum of the Dice is " + diceSum);
// Announce average and count of 7s
if (i == 1000) {
console.log("The Average is " + average);
}
}
If you need to count the times the 3 dice add up to 7, you can create a variable to keep track of this.
Inside your loop, you increase this by one everytime diceSum is 7.
var getRandomInt = function(x) {
var result = 0;
result = Math.floor((Math.random() * x) + 1);
return result;
};
//variables I need
var diceOne = 0;
var diceTwo = 0;
var diceThree = 0;
var diceSum = 0;
var roll = 0;
var average = 0;
var sevenCount = 0;
for (var i = 1; i <= 1000; i++) {
//Simulate a Dice Roll
diceOne = getRandomInt(6);
diceTwo = getRandomInt(6);
diceThree = getRandomInt(6);
roll = roll + 1;
diceSum = diceOne + diceTwo + diceThree;
average += diceSum / 1000;
console.log("Roll #" + roll);
console.log("The Sum of the Dice is " + diceSum);
if(diceSum === 7){
sevenCount = sevenCount + 1;
}
// Announce average and count of 7s
if (i == 1000) {
console.log("The Average is " + average);
console.log("The seven count is " + sevenCount);
}
}
They're teaching you something that's actually really good to know.
You don't have to remember all values in order to calculate the average or number of 7s. You only have to count how many 7s you've seen and keep another variables that's the sum of all the values you've seen.
Edit: if you want to count the number of 7s you've seen, you need to create a variable, say count_7s and every time you see a 7, you increment count_7s = count_7s + 1.
You need no roll count, because you loop the same amount, and you need a counter for sevens. An you could take a variable for sum and calculate later the average. This is better in terms of numerical precision.
At the end show the result of average and count of sevens.
var getRandomInt = function(x) {
return Math.floor((Math.random() * x) + 1);
},
sum = 0,
average = 0,
sevens = 0;
for (var i = 1; i <= 1000; i++) {
let diceSum = getRandomInt(6) + getRandomInt(6) + getRandomInt(6);
sevens += diceSum === 7;
sum += diceSum;
}
average = sum / 1000;
console.log("The Average is " + average);
console.log("The Count of Sevens " + sevens);
Related
So I'm fairly new to JavaScript but I cannot seem to find the average in my code. I want to understand why my average is not working. Any help you guys?
function getEvenOdd() {
var oddSum = 0;
var evenSum = 0;
var num = 0;
var evenAvg = 0;
var oddAvg = 0;
while (true) {
num = parseInt(prompt("Enter a number(-1 to exit)"));
if (num == -1) {
break;
}
if (num % 2 == 0) {
evenSum += num;
} else {
oddSum += num;
}
evenAvg = evenSum / num;
oddAvg = oddSum / num;
}
alert("Sum of all even numbers is: " + evenSum);
alert("Sum of all odd numbers is: " + oddSum);
alert("Average of all even numbers is : " + evenAvg);
alert("Average of all odd numbers is: " + oddAvg);
}
On your code, to calculate the oddAvg and evenAvg, you have divided evenSum and oddSum by num variable (which is input from prompt).
And as you know, average = total sum / total count, so it's not right to divide the sum by the input number variable.
Instead of that, you need to calculate the count of odd and even numbers and divide the even and odd sum by the even and odd number counts as follows.
function getEvenOdd() {
var oddSum = 0;
var evenSum = 0;
var num = 0;
var evenAvg = 0;
var oddAvg = 0;
var evenCount = 0;
var oddCount = 0;
while (true) {
num = parseInt(prompt("Enter a number(-1 to exit)"));
if (num == -1) {
break;
}
if (num % 2 == 0) {
evenSum += num;
evenCount ++;
} else {
oddSum += num;
oddCount ++;
}
}
evenAvg = evenSum / evenCount;
oddAvg = oddSum / oddCount;
alert("Sum of all even numbers is: " + evenSum);
alert("Sum of all odd numbers is: " + oddSum);
alert("Average of all even numbers is : " + evenAvg);
alert("Average of all odd numbers is: " + oddAvg);
}
getEvenOdd();
These operations are dividing the evenSum or oddSum by the last input num.
evenAvg = evenSum / num;
oddAvg = oddSum / num;
You should divide the sum by the number of even or odd inputs.
Instead of evenSum / num use evenSum/Count of Numbers entered.
How about this solution? It is aiming to store odd and even numbers into oddList and evenList.
function getEvenOdd() {
var evenAvg = 0;
var oddAvg = 0;
var oddList = [];
var evenList = [];
var num = 0;
while (true) {
num = parseInt(prompt("Enter a number(-1 to exit)"));
if (num == -1) {
break;
}
if (num % 2 == 0) {
evenList.push(parseInt(num));
} else {
oddList.push(parseInt(num));
}
evenAvg = evenList.reduce((p, c) => p + c, 0) / evenList.length;
oddAvg = oddList.reduce((p, c) => p + c, 0) / oddList.length;
}
alert("Sum of all even numbers is: " + evenList.length);
alert("Sum of all odd numbers is: " + oddList.length);
alert("Average of all even numbers is : " + evenAvg);
alert("Average of all odd numbers is: " + oddAvg);
}
getEvenOdd();
Need help with a JavaScript assignment from School but don't know how I should do it and was hoping for some tips?
We're supposed to create a 6 sided dice roller program and the user will have the option to choose between how many dices should be rolled, min 1 and max 5 dices.
The sum of the amount of dices used should always be displayed on the page. But if a number 6 is thrown, then this should make the program disregard it to the sum and instead throw two new dices, there should be an error message displaying this when it happens.
When all the dices are thrown the total sum of all the dices should be displayed and how many times you threw the dices.
I've managed to create this so far but I'm not sure how I should do regarding the number 6 or even if I'm on the right path here?
JS
function rollDice() {
var numDice = document.getElementById("diceNum").value;
var container = document.getElementById("dieContainer");
container.innerHTML = "";
for (var i = 0; i < numDice; i++) {
var diceRoll = Math.floor(Math.random() * 6) + 1;
container.innerHTML += '<div class="dice">' + diceRoll + '</div>';
};
var x, text;
x = document.getElementById("diceNum").value;
if (isNaN(x) || x < 1 || x > 5) {
window.alert('Input not valid');
document.getElementById("dieContainer").style.display = "none";
} else {
document.getElementById("dieContainer").style.display = "block";
}
};
EDIT
I updated it to this now
let diceThrows = numDice;
let sum = 0;
while(diceThrows > 0) {
var diceRoll = Math.floor(Math.random() * 6) + 1;
if(diceRoll == 6) {
diceThrows += 2;
console.log("You got a 6 och two new dices were thrown");
document.getElementById("msg").innerHTML = "You got a 6 och two new dices were thrown";
} else {
sum += diceRoll;
console.log(sum);
document.getElementById("msg").innerHTML = "Result: " + sum;
}
container.innerHTML += '<div class="dice">' + diceRoll + '</div>';
diceThrows -= 1;
}
I managed to display the results, but wondering now if there is a way display the results without them getting reset every time you use the function?
Replace loop for by loop while:
let diceThrows = 6;
let sum = 0;
while(diceThrows > 0) {
var diceRoll = Math.floor(Math.random() * 6) + 1;
if(diceRoll == 6) {
diceThrows += 2;
} else {
sum += diceRoll;
}
container.innerHTML += '<div class="dice">' + diceRoll + '</div>';
diceThrows -= 1;
}
You can do something like this:
function rollDice() {
var numDice = Number(document.getElementById("diceNum").value);
if (isNaN(numDice) || numDice < 1 || numDice > 5) {
window.alert('Input not valid');
return
}
var container = document.getElementById("dieContainer");
container.innerHTML = "";
var total = 0
for (var i = 0; i < numDice; i++) {
var diceRoll = Math.floor(Math.random() * 6) + 1;
container.innerHTML += '<div class="dice">' + diceRoll + '</div>';
if(diceRoll === 6) {
//Increase the maximum by 1 (because ignore 6: -1; add two: +2)
numDice++
//Decrease the current by 1 (to ignore the 6)
i--
continue
}
total += diceRoll
};
document.getElementById("diceTotal").innerText = total
document.getElementById("diceCount").innerText = numDice
}
<input type="number" id="diceNum">
<button onclick="rollDice()" >Roll Dice</button><br>
Total (without 6s): <span id="diceTotal" ></span><br>
Count of rolls (without 6s): <span id="diceCount" ></span><br>
<div id="dieContainer" ></div>
I am writing a program to display total test grades and avg with a loop. however when I try to test it, I cant get the final message "Good Job" to show up and I am getting a error for unbalanced tree and undefined "Avg" variable. I dont see how "avg" is undefined when it works during the loop just not after
var Testscore = 0;
var Testcount = 0;
var Total = 0;
var Avg = 0;
do {
Testscore = prompt("Enter the test score ", 0);
Testcount = (Testcount + 1);
Total = parseFloat(Testscore) + parseFloat(Total);
Avg = (Total / Testcount);
document.write("Total test score is " + Total + "<br>");
document.write("Average test score is " + Avg + "<br>" + "<br>");
} while (Testcount < 4)
Avg = (Total / Testcount);
if (avg > 80) {
document.write("Good Job!");
} else {
documet.write("Try harder..");
}
You just had a few typos in your code!
avg and Avg are different, as variables are case sensitive.
Additionally, there's a documet instead of document
var Testscore = 0;
var Testcount = 0;
var Total = 0;
var Avg = 0;
do
{
Testscore = prompt("Enter the test score ",0);
Testcount = (Testcount + 1);
Total = parseFloat(Testscore) + parseFloat(Total);
Avg = (Total / Testcount);
document.write("Total test score is " + Total + "<br>");
document.write("Average test score is " + Avg + "<br>" + "<br>");
} while (Testcount < 4)
Avg = (Total / Testcount);
if (Avg > 80)
{
console.log("Good Job!");
}
else
{
console.log("Try harder..");
}
Here's the problem:
Create a sum program that calculates the sum of all odd numbers between 1 and the number entered by the user. For example if the user enters in the number 7 the program would calculate 1 + 3 + 5 + 7. The total and the expression should be displayed on the document. The answer would be 16.
My code so far
//declare the variables
var sternum = prompt("enter a number");
var tantalum = 1;
var increase = 1;
var expression = "+";
//finding the sum
document.write(" the sum of all numbers are: ");
do {
if(sternum % 2 == 0) {
}
else{
document.write(increase + expression);
increase = increase + 1;
tantalum = tantalum + increase;
}
}while(increase < sternum);
document.write(sternum + " = " + tantalum);
You have created an infinite loop. Make sure you increment increase every iteration:
var sternum = prompt("enter a number");
var tantalum = 0;
var increase = 1;
var expression = "+";
//finding the sum
document.write(" the sum of all numbers are: ");
do {
if(increase % 2 == 0) {
}
else{
document.write(increase + expression);
tantalum = tantalum + increase;
}
increase = increase + 1;
}while(increase <= sternum);
document.write(" = " + tantalum);
To make it more efficient you could change increase = increase + 1; to increase = increase + 2;. No need to process even numbers. Also tantalum should be set to 0 to start.
This is probably embarrassingly obvious but I can't seem to figure it out: I've researched what all of these operators mean and commented out what I think they're doing. Apparently total = 55. I thought it would = 11. Where am I going wrong? Thanks a lot.
var total = 0;
var count = 1;
while (count <= 10) { // while "count" is less than or equal to 10 do...
total += count; // total = total + count (total = 0 + count)
count += 1; // count = 1 + 1 (adding 1 to count every loop until count is equal to 11)
};
console.log(total); -> 55
// total is 0 + count
// when the program ends count = 11
// 0 + 11 = 11
Like others have stated in the comments. You are incrementing your count and total. Do one or the other.
Here's what your code is currently doing:
var total = 0;
var count = 1;
var iteration = 0;
var div = document.getElementById("div");
while (count <= 10) {
total += count;
count += 1;
iteration++;
div.innerHTML += "Iteration " + iteration + ": ";
div.innerHTML += "count = " + count + "; ";
div.innerHTML += "total = " + total + ";<br /><br />"
};
<div id="div"></div>
There's several ways you can do this.
One way would be to just increment the count and total by one at each iteration:
var total = 0;
var count = 1;
while (count <= 10) { // while "count" is less than or equal to 10 do...
total++ // Increase the total by 1
count++ // Increase the count by 1
};
document.getElementById("result").innerHTML = total
<div id="result"></div>
but this only gives you a result of 10 because your count is starting at 1
Another way would be to just increment your count, then assign your count to your total outside of the loop:
var total = 0;
var count = 1;
while (count <= 10) { // while "count" is less than or equal to 10 do...
count++ // Increase the count by 1
};
total = count;
document.getElementById("result").innerHTML = total
<div id="result"></div>
Or, remove count altogether:
var total = 0;
while (total <= 10) {
total++;
};
document.getElementById("result").innerHTML = total
<div id="result"></div>
Or, my preferred method, would be to change your loop from a while to a for loop
var total = 0;
for (var i = 0; i <= 10; i++) {
total++;
}
document.getElementById("result").innerHTML = total
<div id="result"></div>
To understand what is happening, try to write:
console.log(total);
console.log(count);
Inside of the while loop body.
You will see how it behaves on every iteration.
count += 1;
means:
count = count + 1;