Javascript function to determine if array element already exists [duplicate] - javascript

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");
}

Related

Best approach to random 10 numbers between 1 and 100 no dupes in javascript? [duplicate]

This question already has answers here:
Generate unique random numbers between 1 and 100
(32 answers)
Closed 4 years ago.
This has been asked dozens of times, but somehow, after reading many answers, I'm not convinced. I'm not cleared about the best way to do it, performance and code simplicity.
Should I set the list [1.. 100] and keep picking random (it will run 10 times) from there to another array, avoiding searching for it every new random?
Should I develop and run 10 times (at least) a random function to return a 1.. 100, checking if it is not a dupe and put it into an array?
Some Javascript function that I'm missing?
Thanks
You can use a while loop to generate random numbers with Math.random() and add the numbers to a Set which contains only unique values.
var randoms = new Set();
while(randoms.size<10){
randoms.add(1 + Math.floor(Math.random() * 100));
}
console.log([...randoms.values()]);
You can also just use an Array and check if the generated random number already exists in it before pushing it to the Array.
var randoms = [];
while(randoms.length<10){
var random = Math.ceil(1 + Math.floor(Math.random() * 100));
if(randoms.indexOf(random)==-1){
randoms.push(random);
}
}
console.log(randoms);
For a more generic function, you can use this:
function generateRandoms(min, max, numOfRandoms, unique){
/*min is the smallest possible generated number*/
/*max is the largest possible generated number*/
/*numOfRandoms is the number of random numbers to generate*/
/*unique is a boolean specifying whether the generated random numbers need to be unique*/
var getRandom = function(x, y){
return Math.floor(Math.random() * (x - y + 1) + y);
}
var randoms = [];
while(randoms.length<numOfRandoms){
var random = getRandom(min, max);
if(randoms.indexOf(random)==-1||!unique){
randoms.push(random);
}
}
return randoms;
}
function generateRandoms(min, max, numOfRandoms, unique){
var getRandom = function(x, y){
return Math.floor(Math.random() * (x - y + 1) + y);
}
var randoms = [];
while(randoms.length<numOfRandoms){
var random = getRandom(min, max);
if(randoms.indexOf(random)==-1||!unique){
randoms.push(random);
}
}
return randoms;
}
console.log(generateRandoms(1, 100, 10, true));
This technique creates N1 numbers (the total range) and shuffles them, then picks the top N2 number (how many we actually want), we'll use Fisher-Yates shuffle.
const n1 = 100;
const n2 = 10;
let pool = [...Array(n1).keys()];
var result = [];
while (result.length < n2) {
let index = Math.floor(Math.random() * pool.length);
result = result.concat(pool.splice(index, 1));
}
console.log(result);
var randomArray = [];
while(randomArray.length < 10) {
var random = Math.round(Math.random() * 100);
if(randomArray.indexOf(random) === -1) {
randomArray.push(random);
}
}
console.log(randomArray);
#2 would be the most efficient.
var nums = []
while(nums.length < 10) {
var n = Math.round(Math.random()*100);
if (!nums.includes(n)) nums.push(n);
}
console.log(nums);
You could also use Set in a newer browser, which would be a little faster than manually checking for existence:
var nums = new Set();
while(nums.size < 10) {
var n = Math.round(Math.random()*100);
nums.add(n);
}
console.log([...nums.values()]);
This function adds all numbers from betweenStart to betweenEnd, randomizes them over randomRuns loops and returns a list with amount entries:
function randomNumbersBetweenXAndY(betweenStart, betweenEnd, amount, randomRuns) {
if (betweenStart === void 0) { betweenStart = 0; }
if (betweenEnd === void 0) { betweenEnd = 100; }
if (amount === void 0) { amount = 10; }
if (randomRuns === void 0) { randomRuns = 1; }
//Verify parameters
var maxPossibleCandidates = Math.abs(betweenStart - betweenEnd) + 1;
if (amount > maxPossibleCandidates) {
console.warn("You cannot get more unique numbers between " + betweenStart + " and " + betweenStart + " than " + maxPossibleCandidates + ". " + amount + " is too many!");
amount = maxPossibleCandidates;
}
//array to return
var list = [];
//fill array
for (var index = betweenStart; index <= betweenEnd; index++) {
list.push(index);
}
//Randomize
while (randomRuns--) {
for (var index = 0; index < list.length; index++) {
var randomIndex = Math.floor(Math.random() * list.length);
var tmp = list[index];
list[index] = list[randomIndex];
list[randomIndex] = tmp;
}
}
//Return data
return list.slice(0, amount);
}
//TEST
console.log(randomNumbersBetweenXAndY(1, 100, 10));

How to find the highest and lowest numbers from a loop in javascript

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.

Identify the largest value from a bunch of random numbers

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/>')
}
}

Create a random array of numbers excluding 0

I am trying to randomize numbers 1-6.
I have the following code already:
for (var a=[],i=0;i<6;++i) a[i]=i;
function shuffle(array) {
var tmp, current, top = array.length;
if(top) while(--top) {
current = Math.floor(Math.random() * (top + 1));
tmp = array[current];
array[current] = array[top];
array[top] = tmp;
}
return array
}
a = shuffle(a);
console.log(shuffle(a));
However, in my console this includes the number 0 and excludes 6.
Is there a way to make these numbers range from 1 - 6 instead of 0-5?
You have done
for (var a=[],i=0;i<6;++i)
a[i-1]=i;
Instead you could have done
for (var a=[],i=1;i<=6;++i)
a[i-1]=i;
In one line
var random = Math.floor(Math.random() * 6) + 1;
alert(random);
that should be
var temp = [];
for(i=0; i<=6; i++){
var random = Math.floor(Math.random() * 6) + 1;
temp[i] = random;
}
console.log(temp);
Fiddle
try following:
Math.floor((Math.random() * 6) + 1);
plus one must be done after random ;)

Javascript - adding random numbers generated in for loop

I'm trying to find the sum of all variables, dieRoll outputted in for loop after the images are displayed. Thanks in advance.
var out = '';
for(var i = 0; i < userSelect; i++){
dieRoll = Math.floor((Math.random() * 6) + 1);
out += "<img src=\"_images/die" + dieRoll + ".jpg\">";
}
return out;
var sum = 0;
var out = '';
for(var i = 0; i < userSelect; i++){
dieRoll = Math.floor((Math.random() * 6) + 1);
sum += dieRoll;
out += "<img src=\"_images/die" + dieRoll + ".jpg\">";
}
Based on the return statement in your example, your function is currently returning just HTML text. You may wish to refactor the code so that one function returns an array of integer die rolls, another function returns the sum of the array, and another function returns the desired HTML text.

Categories