How to display average from list using javascript? - javascript

I just want to show their average from the list when the user stored a value in the list
But I try to use document.write(); but it's doesn't work for me
I want to show the average below the list
function listtable()
{
var score;
var scoreArray = [];
var scoreOutput;
var slenght;
var sum = 0;
do
{
score = prompt("Please enter score and Enter -1 to stop
entering");
score = parseInt(score);
if (score >=0 )
{
scoreArray[scoreArray.length] = score;
}
} while (score != -1);
scoreOutput = "<ul>";
for (i = 0; i < scoreArray.length; i++)
{
scoreOutput += "<li>" + scoreArray[i] + "</li>";
}
scoreOutput += "</ul>";
for (i = 0; i < scoreArray.Length; i++)
{
sum += parseInt(score[i]);
}
var avarage = sum/scoreArray.length;
document.getElementById("display").innerHTML = scoreOutput;
document.write("The Avarage Score is: " + average);
}

You have a couple of typos in your code:
parseInt(score[i]) should be parseInt(scoreArray[i])
i < scoreArray.Length should be scoreArray.length with a lowercase l
The variable should be average not avarage
function listtable() {
var score;
var scoreArray = [];
var scoreOutput;
var slenght;
var sum = 0;
do {
score = prompt("Please enter score and Enter -1 to stop entering ");
score = parseInt(score);
if (score >= 0) {
scoreArray[scoreArray.length] = score;
}
}
while (score != -1);
scoreOutput = "<ul>";
for (i = 0; i < scoreArray.length; i++) {
scoreOutput += "<li>" + scoreArray[i] + "</li>";
}
scoreOutput += "</ul>";
for (i = 0; i < scoreArray.length; i++) {
sum += parseInt(scoreArray[i]);
}
var average = sum / scoreArray.length;
document.getElementById("display").innerHTML = scoreOutput;
document.write("The Avarage Score is: " + average);
}
listtable()
<span id="display" />
(Please search how to debug javascript code using degbugger; and dev tools. You can avoid trivial errors)

Try this:
function listtable() {
var score;
var scoreArray = [];
var scoreOutput;
var slenght;
var sum = 0;
var i;
do {
score = prompt("Please enter score and Enter -1 to stop entering");
score = parseInt(score);
if (score >=0 ) {
scoreArray[scoreArray.length] = score;
}
} while (score != -1);
scoreOutput = "<ul>";
for (i = 0; i < scoreArray.length; i++) {
console.log(scoreArray[i])
sum += parseInt(scoreArray[i]);
scoreOutput += "<li>" + scoreArray[i] + "</li>";
}
scoreOutput += "</ul>";
var average = sum / scoreArray.length;
document.getElementById("display").innerHTML = scoreOutput;
document.write("The Average Score is: " + average);
}
listtable();
<div id="display"></div>
I have made the following changes in your code:
You have used 2 for loop which is not needed, I have added the code in the single for loop. (Optimized, Not an issue)
The variable name is defined as average but you used avarage in the document.write.
You didn't define the var i in your code and directly initializing it in the loop.

There are multiple issue in your code,
You need to store elements in an array with incremental counter instead of storing it in an array length i.e Intested of scoreArray[scoreArray.length] = score; you need to store value at particular index.
Like.
var index = 0;
do
{
score = prompt("Please enter score and Enter -1 to stop
entering");
score = parseInt(score);
if (score >=0 )
{
scoreArray[index++] = score;
//Use index with incremental operator
}
} while (score != -1);
While calculating sum you need to read value from scoreArray not from score. In your code scoreArray is an array not score variable.
correct code,
for (i = 0; i < scoreArray.Length; i++)
{
sum += parseInt(scoreArray[i]);
//Use scoreArray instead of score
}
Now calculate average and print in HTML DOM
Like,
document.write("The Avarage Score is: " + avg);
Here is sample piece of code to print average.
//Declaration of variables
var scoreArray = [1, 2, 3, 4, 5];
var i, index = 0, sum = 0;
//Calculate sum
for(i = 0; i < scoreArray.length; i++)
sum += scoreArray[i];
//Calculate average
var avg = sum/scoreArray.length;
document.write("The Avarage Score is: " + avg);

Related

Unlimited 6 sided dice roller

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>

while loop. can't hardcode the while statement

function start() {
var output = "";
var index = 0;
var total = 0;
var average = 0;
var arr = []
while(arr.length < 12){
var randomnumber = Math.ceil(Math.random()*20)
if(arr.indexOf(randomnumber) > -1) continue;
arr[arr.length] = randomnumber;
}
output = output + "List of all values in the array: " + arr;
output = output + "<br/>" + "Total number of values in the array: " + arr.length + "<br/>";
while(index < arr.length) {
total = total + arr[index];
index++;
}
average = total / index;
output = output + "Total of all values: " + total + "<br/>";
output = output + "Average of all values: " + average;
document.getElementById("msg").innerHTML = output;
}
I was told I am not allowed to hardcode the statement, how to I go about changing the 'while' statement so I am not hardcoding?
Probably they mean
var arr = new Array(12);
var randIndex=0;
while(randIndex < arr.length){
var randomnumber = Math.ceil(Math.random()*20)
if(arr.indexOf(randomnumber) > -1) continue;
arr[randIndex] = randomnumber;
randIndex++;
}
Looks like a school assignment. If you are not supposed to hardcode the number of elements in array (currently 12) then you will need to get that number from user in some way. Or alternatively use a random number as shown below.
Note: there is a catch if you let the user specify the number of elements. I'll keep it for you to explore and fix.
function start(len) {
var output = "";
var index = 0;
var total = 0;
var average = 0;
var arr = []
while(arr.length < len){
var randomnumber = Math.ceil(Math.random()*20)
if(arr.indexOf(randomnumber) > -1) continue;
arr[arr.length] = randomnumber;
}
output = output + "List of all values in the array: " + arr;
output = output + "<br/>" + "Total number of values in the array: " + arr.length + "<br/>";
while(index < arr.length) {
total = total + arr[index];
index++;
}
average = total / index;
output = output + "Total of all values: " + total + "<br/>";
output = output + "Average of all values: " + average;
document.getElementById("msg").innerHTML = output;
}
// start(10); // you can get the number of elements in array from user and pass it here. I'm passing hardcoded 10 for now.
start(Math.ceil(Math.random()*20)); // alternatively passing a random number
<div id='msg'>
</div>

Finding the factorial using a loop in javascript

I need to use a loop to find the factorial of a given number. Obviously what I have written below will not work because when i = inputNumber the equation will equal 0.
How can I stop i reaching inputNumber?
var inputNumber = prompt('Please enter an integer');
var total = 1;
for (i = 0; i <= inputNumber; i++){
total = total * (inputNumber - i);
}
console.log(inputNumber + '! = ' + total);
here is an error i <= inputNumber
should be i < inputNumber
var inputNumber = prompt('Please enter an integer');
var total = 1;
for (i = 0; i < inputNumber; i++){
total = total * (inputNumber - i);
}
console.log(inputNumber + '! = ' + total);
you can keep this:
i <= inputNumber
and just do this change:
total = total * i;
then the code snippet would look like this:
var inputNumber = prompt('Please enter an integer');
var total = 1;
for (i = 1; i <= inputNumber; ++i){
total = total * i;
}
console.log(inputNumber + '! = ' + total);
var inputNumber = prompt('Please enter an integer');
var total = 1;
for (i = 0; i < inputNumber; i++){
total = total * (inputNumber - i);
}
alert(inputNumber + '! = ' + total);
You could use the input value and a while statement with a prefix decrement operator --.
var inputNumber = +prompt('Please enter an integer'),
value = inputNumber,
total = inputNumber;
while (--value) { // use value for decrement and checking
total *= value; // multiply with value and assign to value
}
console.log(inputNumber + '! = ' + total);
Using total *= i; will set up all of your factorial math without the need of extra code. Also, for proper factorial, you'd want to count down from your input number instead of increasing. This would work nicely:
var inputNum = prompt("please enter and integer");
var total = 1;
for(i = inputNum; i > 1; i--){
total *= i;
}
console.log(total);
function factorialize(num) {
var result = num;
if(num ===0 || num===1){
return 1;
}
while(num > 1){
num--;
result =num*result;
}
return result;
}
factorialize(5);

Basic JavaScript Sort Above Mean and Below

I am trying to write a JavaScript code that will take a users input and find the mean. Then it should put the numbers above the mean in a list and the numbers below the mean. Everything is working except for the sorting of the numbers below and above the mean. Than you for your help.
function getNums()
{
var nums = new Array();
var numAmt = prompt("How many data values do you have?");
numAmt = parseInt(numAmt);
var i = 0;
for (i = 0; i<= numAmt - 1; i++)
{
nums[i]= prompt("Enter the data value number " + (i + 1));
}
var sum = 0;
for(i = 0; i < nums.length; i++)
{
sum += parseInt(nums[i]);
var avg = sum/nums.length;
}
var big = 0;
var small = 0;
for (i = 0; i < nums.length; i++)
{
if (nums[i] > avg)
big += parseInt(numbers[i]);
else
small += parseInt(numbers[i]);
document.getElementById('numbers').innerHTML = "Your data: " + nums;
document.getElementById('average').innerHTML =("The mean(average) of these numbers is: " + avg.toFixed(2) +".<br>");
document.getElementById('bigger').innerHTML = "Your data: " + big;
document.getElementById('smaller').innerHTML = "Your data: " + small;
}
}
I would personally break this into two functions, one focused on "find the mean of this array", and another on "sort this array around a pivot."
function mean(arr) {
var sum = arr.reduce(function (prev, curr) {
return prev + curr;
});
return sum / arr.length;
}
function pivotSort(arr, pivot) {
var sorted = [];
arr.forEach(function (val) {
if (val >= pivot)
sorted.push(val);
else
sorted.unshift(val);
});
}
The pivot sort is not even close to optimized, but heck, v8 is pretty quick nowadays.

Javascript Loto Game

How can I check for matching numbers in this script, stuck here, I need to compare the array of user numbers with the array of lotto numbers and display how many numbers they got correct if any along with their prize value.
function numbers() {
var numbercount = 6;
var maxnumbers = 40;
var ok = 1;
r = new Array(numbercount);
for (var i = 1; i <= numbercount; i++) {
r[i] = Math.round(Math.random() * (maxnumbers - 1)) + 1;
}
for (var i = numbercount; i >= 1; i--) {
for (var j = numbercount; j >= 1; j--) {
if ((i != j) && (r[i] == r[j])) ok = 0;
}
}
if (ok) {
var output = "";
for (var k = 1; k <= numbercount; k++) {
output += r[k] + ", ";
}
document.lotto.results.value = output;
} else numbers();
}
function userNumbers() {
var usersNumbers = new Array(5);
for (var count = 0; count <= 5; count++) {
usersNumbers[count] = window.prompt("Enter your number " + (count + 1) + ": ");
}
document.lotto.usersNumbers.value = usersNumbers;
}
Here is a lotto numbers generator and a scoring system. I'm going to leave it to you to validate the user input.
function lottoGen(){
var lottoNumbers = [];
for(var k = 0; k<6; k++){
var num = Math.floor(Math.random()*41);
if(lottoNumbers.indexOf(num) != -1){
lottoNumbers.push(num);
}
}
return lottoNumbers;
}
function scoreIt(){
var usersNumbers = document.getElementsByName('usersNumbers').item(0);
usersNumbers = String(usersNumbers)
usersNumbers = usersNumbers.split(' ');
var matches = 0;
for(var i = 0; i<6; i++){
if(lottoNumbers.indexOf(usersNumbers[i]) != -1){matches++;}
}
return matches;
}
Hi I'm new to this and trying to learn off my own back so obviously I'm no expert but the code above makes a lot of sense to me, apart from the fact I can't get it to work.. I tried to console.log where it says RETURN so I could see the numbers but it just shows an empty array still. I assumed this was to do with it being outside the loop..
I've tried various ways but the best I get is an array that loops the same number or an array with 6 numbers but some of which are repeated..
function lottoGen(){
var lottoNumbers = [];
for(var k = 0; k<6; k++){
var num = Math.floor(Math.random()*41);
if(lottoNumbers.indexOf(num) != -1){
lottoNumbers.push(num);
}
}
return lottoNumbers;
}
Lotto JS: CODEPEN DEMO >> HERE <<
(function(){
var btn = document.querySelector("button");
var output = document.querySelector("#result");
function getRandom(min, max){
return Math.round(Math.random() * (max - min) + min);
}
function showRandomNUmbers(){
var numbers = [],
random;
for(var i = 0; i < 6; i++){
random = getRandom(1, 49);
while(numbers.indexOf(random) !== -1){
console.log("upps (" + random + ") it is in already.");
random = getRandom(1, 49);
console.log("replaced with: (" + random + ").");
}
numbers.push(random);
}
output.value = numbers.join(", ");
}
btn.onclick = showRandomNUmbers;
})();

Categories

Resources