This is my code:
<html>
<head>
<title>Temperature Information</title>
</head>
<body>
<script>
//declare variables
var BR = "<br />";
var ES = " ";
var counter;
var temp = [counter];
var max = 0;
var min = 0;
var tempTot;
var tempAve;
//loop
for (counter = 1; counter <= 5; counter++) {
tempTot = tempTot + temp[counter];
temp[counter] = prompt("Enter the temperature for noon on day #" + counter,ES);
temp[counter] = parseFloat(temp[counter]);
if (temp[counter] == temp[1]){
temp[counter] = max;
temp[counter] = min;
}else if (temp[counter + 1] > temp[counter] && temp[counter] != temp[1]){
temp[counter] = max;
}else if (temp[counter + 1] < temp[counter] && temp[counter] != temp[1]){
temp[counter] = min;
}
tempTot = tempTot + temp[counter];
}
tempAve = tempTot/4;
//display info
document.write("The average temperature is: " + tempAve + BR);
document.write("The maximum temperature is: " + max + BR);
document.write("The minimum temperature is: " + min + BR);
</script>
</body>
It is supposed to take info for the temperature for 5 days, display the average, max, and min. Everything seems to run fine, but it only displays the outcomes with a null. Am I doing something wrong? I feel like I am thinking too much about this.
There are a number of minor errors in your code. Using the browser's debugger or using console.log to check the state would help you figure out what is wrong. For example, your temp array's 0 element is undefined so when you do math on it, bad things happen ;). Also, it is easier to process your array once you have all of the elements instead doing it "on the fly". And finally, always check if the javascript library can do something for you (Math.min) instead of writing it....
oh, and I also put your code into its own function. If you look at your code in the debugger, you'll see that your variables are now all nicely contained in their own scope instead of co-mingling with the global scope.
<html>
<head>
<title>Temperature Information</title>
</head>
<body>
<script>
var tempInformation = function() {
var BR = "<br />";
var ES = " ";
var temp = [];
for (var counter = 0; counter < 5; counter++) {
var input = prompt("Enter the temperature for noon on day #" + (counter + 1), ES);
temp[counter] = parseFloat(input);
}
var sum = temp.reduce((previous, current) => current += previous);
var avg = sum / temp.length;
document.write("The average temperature is: " + avg + BR);
document.write("The maximum temperature is: " + Math.max.apply(null, temp) + BR);
document.write("The minimum temperature is: " + Math.min.apply(null, temp) + BR);
}
tempInformation();
</script>
</body>
Related
Created a lottery number guesser sort of program that takes a number 1-10 and has the user guess the number, a total of 3 times, to win a "prize". In the lottery part of the program, I was able to get no problem but can't get the program to count the number of guesses and display the correct prize amount.
Here is the code I have:
<script>
var randomNum1 = Math.floor((Math.random() * 9) + 1);
var randomNum2 = Math.floor((Math.random() * 9) + 1);
var randomNum3 = Math.floor((Math.random() * 9) + 1);
console.log(randomNum1);
console.log(randomNum2);
console.log(randomNum3);
console.log(x);
var firstNum = false;
var secondNum = false;
var thirdNum = false;
var x = 0;
var moneyWon = 0;
firstNum = parseInt(prompt("Guess the first number."));;
secondNum = parseInt(prompt("Guess the second number."));;
thirdNum = parseInt(prompt("Guess the third number."));;
if((firstNum == randomNum1) || (firstNum == randomNum2) || (firstNum == randomNum3))
{
firstNum == true;
}
if(firstNum == true)
{
moneyWon = 100;
x++;
}
else{
moneyWon = 0;
}
if((secondNum == randomNum2) || (secondNum == randomNum1) || (secondNum == randomNum3))
{
secondNum == true;
}
if(secondNum == true)
{
moneyWon = 200;
x++;
}
else{
moneyWon = 100;
}
if((thirdNum == randomNum2) || (thirdNum == randomNum1) || (thirdNum == randomNum3))
{
thirdNum == true;
}
if(thirdNum == true)
{
moneyWon = 500;
x++;
}
else{
moneyWon = 200;
}
alert("The computer's numbers are " + randomNum1 + " " + randomNum2 + " " + randomNum3 +
"\nYour guesses were " + firstNum + " " + secondNum + " " + thirdNum +
"\nYou got " + console.log(x) + " right" +
"\nYou've won $" + moneyWon);
</script>
First thing im noticing:
You got " + console.log(x) + " right" +
You dont want the console.log() here, just the x
The second thing, you dont want to set moneyWon every time in the ifs, but rather do moneyWon += amount, just like you are doing with the x
Also, in the else (indicating the guess was incorrect), you dont want to set nor add to the amount (I would suggest deleting these 3 elses altogether):
else{ moneyWon = 0; }
and a minor thing - give meaningful names to properties, ie
var firstNum = false should be more like (is)firstNumberGuessed (the is indicates that this is a boolean
I see you are on the right track re this, but its good to learn not to be lazy about this stuff asap
EDIT: you can also throw out assigning true to firstNum, secondNum, thirdNum and just have this:
if((firstNum == randomNum1) || (firstNum == randomNum2) || (firstNum == randomNum3))
{
moneyWon += 100;
x++;
}
Well, I don't need to tell you what are the errors and what are causing them, as my friend Dejan already included them in his answer. In my answer, I am trying to implement his answer as well as some useful javascript methods which may make your work a lot more easier and faster as well.
First of all, arrays are your friend. I have made arrays for user inputs as well as random numbers and populating them using a for loop.
Next, as we are using arrays, we can use the includes() method to find the values among the random numbers. It reduces your if else conditions.
Next, I am using string interpolation to get the output message.
let randoms = [];
let nums = [];
let numbers = ["first", "second", "third"];
let winPrize = [100, 200, 500];
let losePrize = [0, 100, 200];
for(let i=0; i<3; i++){
randoms.push(Math.floor((Math.random() * 9) + 1));
nums.push(parseInt(prompt(`Guess the ${numbers[i]} number.`)));
}
let x = 0;
let moneyWon = 0;
for(let i=0; i<3; i++){
if(randoms.includes(nums[i])){
x++;
moneyWon+=winPrize[i];
}else{
moneyWon+=losePrize[i];
}
}
alert(`The computer's numbers are ${randoms[0]}, ${randoms[1]} and ${randoms[2]}. \nYour guesses were ${nums[0]}, ${nums[1]} and ${nums[2]}. \nYou got ${x} right. \nYou've won $${moneyWon}`);
I believe that if we follow such practices, our code will remain short as well as easily readable and maintainable.
How can I add into this program to find the highest and lowest numbers? I have tried a few different things but it just keeps giving me the last number I enter as both.
<meta charset="UTF-8">
<title>Laskenta</title>
<script>
var yht=0; //sum
var luku=0; //number
var laske; //count
laske=Number(prompt("how many numbers would you like to add?"))
for (var i=0; i<laske; i++){luku = Number(prompt("give number", "number"));
yht=yht+luku;
}
while(i<laske);
document.write("the sum of the numbers you entered is " ,yht, "<br>");
document.write (" and the average is o " + yht/laske);
Ive translated most of it from Finnish and put next to what is still in Finnish the meanings next to it.
Any help would be greatly appreciated.
Thanks
The first set of operations addresses your desired to do these tasks in a loop, but you don't really need a traditional loop to do these tasks. The new spread operator along with Math.max and the Array.prototype.reduce() method can easily get you the max value, the sum or the average.
var result = null;
var nums = [];
// Remember, a propmt will always return a string, you must convert that
// to a number if you want to do math with it.
var count = parseInt(prompt("How many numbers do you want to work with?"), 10);
// Build up the input values into an array:
for(var i = 0; i < count; ++i){
nums.push(parseInt(prompt("Enter number " + (i + 1)),10));
}
// The "traditional" way to get the max value from a loop would be to
// compare the value that you are iterating and the next value in the
// array and store the higehr one:
var max = null;
var sum = 0;
for(var x = 0; x < nums.length-1; ++x){
max = (nums[x] > nums[x + 1]) ? nums[x] : nums[x + 1];
sum += nums[x];
}
console.log("Max number is: " + max);
var sum = 0;
for(var y = 0; y < nums.length; ++y){
sum += nums[y];
}
console.log("Sum is: " + sum);
console.log("Average is: " + sum / nums.length);
// *******************************************************************************
// But, we have much better ways of doing these jobs:
console.log("Max number is: " + Math.max(...nums));
result = nums.reduce(function(accumulator, currentValue, currentIndex, array) {
return accumulator + currentValue;
});
console.log("The sum is: " + result);
console.log("The average is: " + result / nums.length);
var yht=0; //sum
var luku=0; //number
var laske; //count
var highest;
var lowest;
laske=Number(prompt("how many numbers would you like to add?"))
for (var i=0; i<laske; i++){luku = Number(prompt("give number", "number"));
if (i == 0) {
highest = luku;
lowest = luku;
}
else {
if (luku > highest) highest = luku;
if (luku < lowest) lowest = luku;
}
yht=yht+luku;
}
while(i<laske);
document.write("the sum of the numbers you entered is " ,yht, "<br>");
document.write (" and the average is o " + yht/laske);
document.write("<br />Highest value="+highest);
document.write("<br />Lowest value="+lowest);
Add two variables in the code to track highest and lowest values entered. Set the first number entered to both highest and lowest. Then when a new low is encountered, replace lowest. When a new high value is encountered replace highest.
Fiddle: https://jsfiddle.net/zhaem/po12voLL/1/
I wrote a script that lets me specific the number of random numbers I want to display, and the max value any of those numbers can be. Like so:
var randomLimit = 100000
var numberCount = 20
var counter = 0;
document.write("<h1>" + numberCount + " random numbers. Max value of " + randomLimit + "</h1>" );
function randomNumber(limit) {
return Math.floor( Math.random() * limit ) + 1;
}
while ( counter < numberCount ) {
document.write(randomNumber(randomLimit) + "<br>");
counter++;
}
I'm trying to figure out how I can evaluate all these numbers and identify the largest one (and make that line item bold).
I tried to do it by checking if the current "randomNum" is greater than the others, but doesn't work and doesn't seem like quite the right approach anyway as it seems like it needs to wait for all the numbers to be generated before picking the biggest? Would love any ideas.
while ( counter < numberCount ) {
var randomNum = randomNumber(randomLimit)
if (this.randomNum > randomNum) {
document.write("<strong>" + randomNum + "</strong>" + " ");
} else {
document.write(randomNum + " ");
}
counter++;
}
You can have a variable that keeps track of the largest number and update it if the current number is greater than the largest number. When you're done generating all the random numbers, find that number and bold it.
var randomLimit = 100000
var numberCount = 20
var counter = 0;
var largestNumber = -1;
document.write("<h1>" + numberCount + " random numbers. Max value of " + randomLimit + "</h1>" );
function randomNumber(limit) {
return Math.floor( Math.random() * limit ) + 1;
}
while ( counter < numberCount ) {
var currNumber = randomNumber(randomLimit);
document.write("<span>" + currNumber + "</span><br>");
if (currNumber > largestNumber)
largestNumber = currNumber;
counter++;
}
var list = document.getElementsByTagName("span");
for (var i = 0; i < list.length; i++) {
if (list[i].innerHTML == largestNumber) {
list[i].innerHTML = "<strong>" + largestNumber + "</strong>";
}
}
<body>
<div id="layer1">
</div>
<script src="randomNum.js"></script>
</body>
Generate all numbers in a array, find the max, then write them all as in this code.
It is not not the best solution, because it need 3 iterations over the array (one for generate, one for find the max, and the last one print the numbers) but I think it is clear, and I always err to readability over performance.
You can not resolve this problem with less than 2 iterations, because you can never know if the next value (being random) will be larger than the previous.
var randomLimit = 100000
var numberCount = 20
var counter = 0;
document.write("<h1>" + numberCount + " random numbers. Max value of " + randomLimit + "</h1>" );
function randomNumber(limit) {
return Math.floor( Math.random() * limit ) + 1;
}
// Generate random numbers
var randomNumbers = []
for( counter = 0; counter < numberCount; counter++ )
randomNumbers.push(randomNumber(randomLimit))
// Find max value
var maxValue = Math.max.apply(this, randomNumbers)
// Write values
randomNumbers.forEach(function(value) {
str = value;
if(value == maxValue) str = "<strong>" + value + "</strong>";
document.write(str + "<br />");
})
Depending on your application, and how lazy you feel you could generate the big number from a higher set and randomly insert it. Not random.
Otherwise the Mozilla Developer Network says use Math.max.apply or the 'spread operator'. Spread operator as per example.
var randomNums = []
while ( counter < numberCount ) {
randomNums.push(randomNumber(randomLimit));
counter++;
}
var maxIs = Math.max(...randomNums), i;
for (i=0; i<numberCount; ++i) {
var num = randomNums[i];
if (num == maxIs) {
document.write('<b>' + num + '</b><br/>');
} else {
document.write(num + '<br/>')
}
}
I'd like to get some help on my javascript code. I made a grade statistics calculator that shows results on:
Min – Max student grade
Min – Max student average
Min – Max course grade
Min – Max course average grade
You can access it live here --> http://jsbin.com/qirefe/edit?html,css,js,output and press the "Show Results" button to see my output. (You can change the names and the grades to get a different output)
My problem is that I cannot figure out why it doesn't show the correct course names on the Min - Max course grade, although it displays the grades right. Also I cannot figure out why it calculates wrongly the min and max course average grade and displays the corresponding courses name wrong..
Any help will be very appreciated :)
The .js code:
var Course0 = Array(6);
var Course1 = Array(6);
var Course2 = Array(6);
var Student = Array(6);
var CMap = [Course0, Course1, Course2];
var NMap = ["Course0", "Course1", "Course2"];
var showResults = function () {
var Rows = document.getElementsByClassName("srow");
for (var i = 1; i < Rows.length - 1; i++) {
var values = Rows[i].getElementsByTagName("input");
Student[i - 1] = values[0].value;
for (var j = 1; j < values.length; j++) {
CMap[j - 1][i - 1] = values[j].value;
}
}
var MinID = MaxID = AvgMinID = AvgMaxID = 0;
var Min = Max = AvgMin = AvgMax = undefined;
for (var i = 0; i < Student.length; i++) {
var c0 = Course0[i];
var c1 = Course1[i];
var c2 = Course2[i];
var lessonMin = Math.min(c0, c1, c2);
var lessonMax = Math.max(c0, c1, c2);
if ((lessonMin <= Min) || (typeof Min === "undefined")) {
MinID = i;
Min = lessonMin;
}
if ((lessonMax >= Max) || (typeof Max === "undefined")) {
MaxID = i;
Max = lessonMax;
}
var Avg = Math.avg(c0, c1, c2);
if ((Avg < AvgMin) || (typeof AvgMin === "undefined")) {
AvgMinID = i;
AvgMin = Avg;
}
if ((Avg > AvgMax) || (typeof AvgMax === "undefined")) {
AvgMaxID = i;
AvgMax = Avg;
}
}
var Wrapper = document.getElementById("student-results");
Wrapper.innerHTML = "";
Wrapper.innerHTML += "<span>The Student with lower grade is: " + Student[MinID] + ", Equals To " + Min + "</span>";
Wrapper.innerHTML += "<span>The Student with higher grade is: " + Student[MaxID] + ", Equals To " + Max + "</span>";
Wrapper.innerHTML += "<hr />";
Wrapper.innerHTML += "<span>The Student with lower average grade is: " + Student[AvgMinID] + ", Equals To " + AvgMin + "</span>";
Wrapper.innerHTML += "<span>The Student with higher average grade is: " + Student[AvgMaxID] + ", Equals To " + AvgMax + "</span>";
var CourseMin = CourseMinID = CourseMax = CourseMaxID = CourseAvgMin = CourseAvgMinID = CourseAvgMax = CourseAvgMaxID = 0;
CourseMin = CourseMax = CourseAvgMin = CourseAvgMax = undefined;
for (var i = 0, j = 0; i < Student.length; i++, j += .5) {
var c0 = Course0;
var c1 = Course1;
var c2 = Course2;
var CheckMin = Math.min(c0[i], c1[i], c2[i]);
if (CourseMin > CheckMin || (typeof CourseMin === "undefined")) {
CourseMin = CheckMin;
CourseMinID = i;
}
var CheckMax = Math.max(c0[i], c1[i], c2[i]);
if (CourseMax < CheckMax || (typeof CourseMax === "undefined")) {
CourseMax = CheckMax;
CourseMaxID = parseInt(j);
}
var Avg = Math.avg(c0[i], c1[i], c2[i]);
if (Avg < CourseAvgMin || (typeof CourseAvgMin === "undefined")) {
CourseAvgMin = Avg;
CourseAvgMinID = j;
}
if (Avg > CourseAvgMax || (typeof CourseAvgMax === "undefined")) {
CourseAvgMax = Avg;
CourseAvgMaxID = parseInt(j);
}
}
console.log(CourseMaxID);
Wrapper.innerHTML += "<hr />";
Wrapper.innerHTML += "<span>The Course with lower grade have: " + NMap[CourseMinID] + ", Equals To " + CourseMin + "</span>";
Wrapper.innerHTML += "<span>The Course with higher grade have: " + NMap[CourseMaxID] + ", Equals To " + CourseMax + "</span>";
Wrapper.innerHTML += "<hr />";
Wrapper.innerHTML += "<span>The Course with lower average grade have: " + NMap[CourseAvgMinID] + ", Equals To " + CourseAvgMin + "</span>";
Wrapper.innerHTML += "<span>The Course with higher average grade have: " + NMap[CourseAvgMaxID] + ", Equals To " + CourseAvgMax + "</span>";
return null;
};
Math.avg = function () {
var Avg = 0;
var table = arguments;
for (var i = 0; i < table.length; i++) {
Avg += parseFloat(table[i]);
}
return parseFloat(Avg / table.length);
};
After examining the output of CourseMaxID and CourseMinID in the console, CourseMinID has an index of 3, but NMap only has 3 values (indexed as 0, 1, 2). So I believe this is why, for example, you are seeing:
"The Course with lower grade have: " + NMap[CourseMinID] + ", Equals To " + CourseMin; is undefined -- because the index is out of bounds.
Here's a fix for your issues with CourseMinID and CourseMaxID:
Change the definition of CourseMinID to Math.floor(j)-1;
And change CourseMaxID to be equal to Math.ceil(j);
Your call to parseInt() on a float value didn't appear to be having the intended consequence.
I'm not entirely sure why you're choosing to increment j by 0.5 each time, but from observation I noticed that for CourseMax/CourseMinID, you wanted to use the computations I noted above.
Another note, for the course average values, you are in fact outputting the student's averages. So you will want to change your logic there. It looks to me like you are giving the horizontal row of grades as parameters to the average function:
var Avg = Math.avg(c0[i], c1[i], c2[i]);
That's not what you want to parse in to Avg for course average grades. I would define another Avg function (let's call it newAvg() here) that takes as input a single array (not multiple arguments), and then call Math.Min/Math.Max on newAvg(c0), newAvg(c1), newAvg(c2).
Here's an updated jsbin link with working functionality for course averages. Overview of changes: newAvg() has been defined to take in and operate on one parameter. Keep track of indices of CourseAvgMax and CourseAvgMin. Note that I've removed some of the other operations you had earlier in this jsbin link to make it easier for me to isolate what I was working on. Hope you find it useful!
This question already has answers here:
Determine whether an array contains a value [duplicate]
(18 answers)
Closed 7 years ago.
So I'm writing some code that will generate a random number between 1 and 20 ten times, add it to an array, then display it in a table. If a number occurs more than once, it will display red in the table. I'm having trouble creating the function that would evaluate the random number to determine if it is random or not and turn it red. Any help is greatly appreciated
var i;
var myarray = new Array();
document.writeln("<table>");
document.writeln("<th> Index </th>");
document.writeln("<th> Number </th>");
for (i = 1; i <= 10; i++){
//numberExists();
var min = 1;
var max = 20;
var randomnum = Math.floor(Math.random() * (max - min + 1)) + min;
var mynum = parseInt (randomnum );
myarray[i] = mynum;
document.writeln("<tr>");
document.writeln("<td>" + i + "</td>");
document.writeln("<td>" + myarray[i] + "</td>");
document.writeln("</tr>");
}
document.writeln("</table>");
//function numberExists(mynum, myarray){
// Can't figure out the code that goes here
//}
Here is how to you could test if mynum is already in myarray and change the color accordingly:
var i;
var myarray = new Array();
document.writeln("<table>");
document.writeln("<th> Index </th>");
document.writeln("<th> Number </th>");
for (i = 1; i <= 10; i++){
var min = 1;
var max = 20;
var randomnum = Math.floor(Math.random() * (max - min + 1)) + min;
var mynum = parseInt (randomnum );
var color="black";
if(myarray.indexOf(mynum) > -1){
color="red";
}
myarray[i] = mynum;
document.writeln("<tr>");
document.writeln("<td>" + i + "</td>");
document.writeln("<td><font color="+color+">" + myarray[i] + "</td>");
document.writeln("</tr>");
}
document.writeln("</table>");
EDIT: If you're looking for a pragmatic solution, use indexOf as suggested in the comments. If you're looking for the proper algorithmic way of doing it (that won't require linear lookup-time and result in an asymptotically faster algorithm, the follow my original advice below:
Store the number as the key in an object.
var myNumbers = {};
...
myNumbers[mynum] = true; // add it to the object
if (myNumbers[mynum]) {
console.log("The number has already been added");
} else {
console.log("This is a new number");
}