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/>')
}
}
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.
I have this code that displays 100 random numbers, then adds a break for every 10 numbers. How would I ensure that these 100 random numbers do not have repeats? I know maybe there's something to do with more if statements?
Thanks,
J
<!DOCTYPE html>
<html>
<h1><font color = "blue">Random Numbers and Breaks (for loops)</font></h1>
<p><font color="red">This will display 100 numbers and insert a break in 10-number intervals:</font></p>
<div id="demo"> </div>
<body>
<script>
var text= '';
var i = 0;
var counter = 0;
for (; i < 100; i++ , counter++) {
var numbers = Math.floor((Math.random() * 100) + 1);
text += numbers + " " + "<br>";
if (i % 10 === 9) {
text += "<br>";
}
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
How would I ensure that these 100 random numbers do not have repeats?
You need to save returned values (by random number generator) so that same value is not returned again.
function randomNumberGenerator( min, max )
{
var returnedValues = [];
return function()
{
var num = null;
while( num == null || returnedValues.indexOf( num ) != -1 )
{
num = Math.floor((Math.random() * (max-min)) + min);
}
return num;
}
}
Now you can call this n number of times ( n < (max - min) )
var nRandomNumbers = 10;
var randomNumArr = [];
var ran1 = randomNumberGenerator(1,100); //initialize the randomNumberGenerator
for( var counter = 0; counter < nRandomNumbers; counter++ )
{
randomNumArr.push( ran1() );
}
You can use Fischer yates algorithm for shuffling an array and shuffle an array from 1 to 100.
// Returns num size random array from 1 to num
function getRandomArray(num) {
const arr = [];
for (let i = 0; i < num; i++) {
arr.push(i+1);
}
let temp, rIndex;
// swap random element
for (i = num - 1; i >= 0; i--) {
rIndex = Math.floor(Math.random()*i);
temp = arr[i];
arr[i] = arr[rIndex];
arr[rIndex] = temp;
}
return arr;
}
let text = '';
getRandomArray(100).forEach(function(item, index){
text += item + " <br />";
text += (index + 1)%10 === 0 ? "<br />" : "";
});
document.getElementById("demo").innerHTML = text;
I think this is what you want, if you don't know what something does, please research it. Do not simply copy and paste.
var text= '';
var i = 0;
var counter = 0;
var nums = []; // Created array
var numbers;
for (; i < 100; i++ , counter++) {
numbers = Math.floor((Math.random() * 100) + 1);
while (nums.includes(numbers))
numbers = Math.floor((Math.random() * 100) + 1);
// While nums array includes numbers, reroll.
nums.push(numbers); // Push the number to the array
text += numbers + " " + "<br>";
if (i % 10 === 9) text += "<br>"
// If the rightmost digit is a 9, add the br tag
}
document.getElementById("demo").innerHTML = text;
<!DOCTYPE html>
<html>
<h1><font color = "blue">Random Numbers and Breaks (for loops)</font></h1>
<p><font color="red">This will display 100 numbers and insert a break in 10-number intervals:</font></p>
<div id="demo"> </div>
<body>
</body>
</html>
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.
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");
}
Javascript:
var arrayLength = prompt("Enter how many elements you want?");
if(isNaN(arrayLength) || arrayLength < 1){
arrayLength = 50;
}
var array = [];
var list = "<ul>";
var totalSum = 0;
var totalOddSum = 0;
var totalEvenSum = 0;
var lowestNum = 0;
var highestNum = 0;
for(i = 1; i <= arrayLength; i++){
array[i] = parseInt(Math.random() * 15);
list += "<li>" + array[i] + "</li>";
totalSum += array[i];
if(array[i] % 2 == 0){
totalEvenSum += array[i];
}
else{
totalOddSum += array[i];
}
}
list += "</ul>";
document.getElementById("div1").innerHTML += list;
document.getElementById("div2").innerHTML += "Total Sum: " + totalSum + "<br>";
document.getElementById("div2").innerHTML += "Total Even Sum: " + totalEvenSum + "<br>";
document.getElementById("div2").innerHTML += "Total Odd Sum: " + totalOddSum + "<br>";
document.getElementById("div2").innerHTML += "Lowest Number: " + lowestNum + "<br>";
document.getElementById("div2").innerHTML += "Highest Number: " + highestNum + "<br>";
HTML:
<div id="div1">
</div>
<div id="div2">
</div>
As the title says, I want to be able to able to find the lowest and highest numbers that my array generates. What do I need to implement inside my loop in order to find the highest and lowest numbers Math.random() generates?
Thanks guys.
First of all, the initial values for minimum and maximum are wrong:
var lowestNum = 0;
var highestNum = 0;
The minimum value should be initialised as +Inf and maximum value as -Inf.
var lowestNum = Infinity, highestNum = -Infinity;
Then, add a simple condition that updates the lowest and highest found so far.
if (array[i] < lowestNum) {
lowestNum = array[i];
}
if (array[i] > highestNum) {
highestNum = array[i];
}
At the end of your loop, the variables will represent the lowest and highest number in the whole array.
You can use Math.max() and Math.min() to find the highest or lowest values in an array:
var highest = Math.max.apply(Math, array);
var lowest = Math.min.apply(Math, array);
There is no need to do your own looping. This works because both Math.max() and Math.min() will take an arbitrary number of arguments and operate on all of them, so if you use .apply() to pass the array as a series of arguments, it will evaluate the entire array in one function call.