How to find a largest number in an array? - javascript

function myarray(min, max) {
var points = [];
for (var i = 0; i < 10; i++) {
points.push(Math.round(Math.random() * (1000 - 100 + 1) + 100));
points.join('<br>');
var largest = Math.max.apply(0, points);
}
return points
}
console.log(myarray());
My task is pretty simple, I want to create 10 random numbers from 1 to 1000 in an array and then print the highest one. I think I am pretty close but when I run this I get undefined.
How can I fix this? and what is undefined?

You can compare points to the largest number. Try the below snippet.
function myarray(min, max) {
var points = [];
var largest = 0;
for (var i = 0; i < 10; i++) {
points.push(Math.round(Math.random() * (1000 - 100 + 1) + 100));
if ( points[i] > largest ) {
var largest = points[i];
}
}
console.log(points);
console.log(largest);
}
myarray();
As per OP comment.
function myarray(min, max) {
var points = [ 521,338,761,834,561,842,177,862,173 ];
var largest = 0;
for (var i = 0; i < 10; i++) {
if ( points[i] > largest ) {
var largest = points[i];
}
}
console.log(points);
console.log(largest);
}
myarray();

All you need to do is move the call to Math.max.apply(0, points) outside the loop which is building the array and return that. Also, no need for the points.join line at all
function myarray(min, max) {
var points = [];
for (var i = 0; i < 10; i++) {
points.push(Math.round(Math.random() * (1000 - 100 + 1) + 100));
}
var largest = Math.max.apply(null, points);
return largest
}
console.log(myarray());

let arr = [1,2,3,5,25,35,43,75,100,35,3244,345,535,532]
let maxnum = arr.reduce((pre,cur) =>{
if(pre <= cur){
pre = cur
}
return pre
},0)

Because I love one-line solutions :)
console.log(Math.max(...Array.apply(null, Array(10)).map(
x=>Math.round(Math.random() * (1000 - 100 + 1) + 100)
)))

Related

Split a range of number to a specific number of intervals

I have an interval [0; max] and I want to split it into a specific number of sub-intervals. For this, i wrote a function called getIntervalls(max, nbIntervals) where max is the max element in my first interval and nbIntervals is the number of expected sub-intervals.
For example:
getIntervalls(3, 2) should return [[0,1], [2,3]],
getIntervalls(6, 2) should return [[0,3], [4,6]],
getIntervalls(8, 3) should return [[0,2], [3,5], [6,8]],
getIntervalls(9, 3) should return [[0,3], [4,7], [8,9]],
Here is my function:
function getIntervalls(max, nbIntervalls) {
var size = Math.ceil(max / nbIntervalls);
var result = [];
if (size > 1) {
for (let i = 0; i < nbIntervalls; i++) {
var inf = i + i * size;
var sup = inf + size < max ? inf + size: max;
result .push([inf, sup]);
}
} else {
result.push([0, max]);
}
return result;
}
console.log(JSON.stringify(getIntervalls(7, 2)));
It work properly, and shows this output:
[[0,4],[5,7]]
When I change the parameters to 7 and 3, it shows:
[[0,3],[4,7],[8,7]]
instead of
[[0,2],[3,5],[6,7]]
Would anyone can help me? Thank you in advance. An ES6 syntax will be appreciated! :)
You need to use Math.round() for take the nearest integer of the decimal number of the size of interval. Also, you need to descrease a one the max for size calculation to take account of the effective number of interval.
Here the modification of your code :
function getIntervalls(max, nbIntervalls) {
var size = Math.round((max-1) / nbIntervalls);
var result = [];
for (let i = 0; i < nbIntervalls; i++) {
var inf = i + i * size;
var sup = inf + size < max ? inf + size: max;
result.push([inf, sup]);
if(inf >= max || sup >= max)break;
}
return result;
}
Note that it respect the wanted number of interval, so some case of couple of number can result
[..., [n-2,n-1], [n,n]].
Hope this helps!
You could check if i is zero for first element and if next increment is larger then max for second element. Also you can check if first element is smaller then max.
function getIntervalls(max, nInt) {
const c = Math.floor(max / nInt);
const r = [];
for (var i = 0; i <= max; i += c) {
const a = i == 0 ? i : i += 1;
const b = i + c > max ? max : i + c;
if (a < max) r.push([a, b])
}
return r;
}
console.log(JSON.stringify(getIntervalls(3, 2)));
console.log(JSON.stringify(getIntervalls(6, 2)));
console.log(JSON.stringify(getIntervalls(8, 3)));
console.log(JSON.stringify(getIntervalls(9, 3)));
console.log(JSON.stringify(getIntervalls(7, 2)));
console.log(JSON.stringify(getIntervalls(7, 3)));
You need to change the size calculation from Math.ceil() to Math.floor(), because of ceil it takes size +1 than what you need.
I have made modification to your code, here it will work.
function getIntervalls(max, nbIntervalls) {
var size = Math.floor(max / nbIntervalls);
var result = [];
if (size > 0) {
for (let i = 0; i < nbIntervalls; i++) {
var inf = i + i * size;
var sup = inf + size < max ? inf + size : max;
result .push([inf, sup]);
if (sup >= max) {
break;
}
}
} else {
result.push([0, max]);
}
return result;
}
console.log(JSON.stringify(getIntervalls(10, 5)));
Hope this helps!
For me, this is the perfect function for that.
It allows you to get the intervals between two numbers, and the last interval always goes to the max.
function getIntervals(min, max, nbIntervals) {
let size = Math.floor((max - min) / nbIntervals);
let result = [];
if (size <= 0) return [min, max];
for (let i = 0; i < nbIntervals; i++) {
let inf = min + (i * size);
let sup = ((inf + size) < max) ? inf + size : max;
if (i === (nbIntervals - 1)) {
if (sup < max) sup = max;
}
result.push([inf, sup]);
if (sup >= max) break;
}
return result;
}

I need to make an array of 15 random integers. I have a function but dont want numbers to repeat

I'm working on a project for school. I need to generate an array of 15 random integers between 1 & 50. I have a function, but I would not like for the numbers to repeat. (for example, if the number 3 is located at index 0, I would not like for it to show up again in the array.) If I could get some help on not getting repeat numbers, that would be great.
Thank you for any help!
var arr;
function genArray() {
//generates random array
arr = [];
for (var i = 0; i < 15; i++) {
var min = 1;
var max = 50;
var arrayValue = Math.floor(Math.random() * (max - min + 1)) + min;
arr.push(arrayValue);
}
arr.sort(function(a, b) {
return a - b
});
console.log(arr);
}
In the loop generate a new random number while the number is in the array. In other words only continue when the new number is not in the array already.
var arr;
function genArray() {
//generates random array
arr = [];
for (var i = 0; i < 15; i++) {
var min = 1;
var max = 50;
do
{
var arrayValue = Math.floor(Math.random() * (max - min + 1)) + min;
}while(arr.includes(arrayValue))
arr.push(arrayValue);
}
arr.sort(function(a, b) {
return a - b
});
console.log(arr);
}
genArray();
You can make a function in which check the number if its already in array than regenrate the number else push the number in array
var arr;
function genArray() {
//generates random array
arr = [];
for (var i = 0; i < 15; i++) {
var min = 1;
var max = 50;
var arrayValue = Math.floor(Math.random() * max) + min;
if(checkno(arrayValue)==true)
arr.push(arrayValue);
}
arr.sort(function(a, b) {
return a - b
});
console.log(arr);
}
function checkno(var no)
{
for(var i=0;i<arr.length;i++)
{
if(arr[i]==no)
return false;
else
return true;
}
}
An alternate solution involves the Set object, sets only have unique elements, multiple elements of the same value are ignored.
Example of the set object implemented for this use:
var temp = new Set();
while (temp.size < 15) {
var min = 1;
var max = 50;
temp.add(Math.floor(Math.random()*(max-min+1))+min);
}
This approach uses Arrow functions, forEach and includes functions.
let LENGTH = 15;
let numbers = new Array(LENGTH).fill();
let findRandomNumber = (i) => {
let rn;
while (numbers.includes((rn = Math.floor(Math.random() * 50) + 1))) {}
numbers[i] = rn;
};
numbers.forEach((_, i) => findRandomNumber(i));
console.log(numbers.sort((a, b) => a - b));
.as-console-wrapper {
max-height: 100% !important
}
You do not need to check the resulting array and regenerate the number. It is not efficient.
Please take a look at the following snippet:
function get_N_rand(N = 15, min = 1, max = 50) { // set default values
var N_rand = [], range = [];
for (var i = min; i <= max;) range.push(i++); // make array [min..max]
while (N_rand.length < N) { // cut element from [min..max] and put it into result
var rand_idx = ~~(Math.random() * range.length);
N_rand.push(range.splice(rand_idx, 1)[0]);
}
return N_rand;
}
console.log(JSON.stringify( get_N_rand() )); // run with defaults
console.log(JSON.stringify( get_N_rand(6, 10, 80) )); // run with arbitraries

Counting duplicate random numbers from a for loop

I am trying to create a score predictor based on a teams goal difference (football). I am new to JavaScript, and I have managed to get this far.
I want it to be like spinning a ten-sided dice 20 times + the team's goal difference. I have got this bit sorted I think. With my code now I have a list of random numbers logged in the console which is what I wanted. Now I would like to choose a number (e.g., 2) and see how many times this occurs in the list. I'd like to save this in a new variable called homeFinalScore (So if '2' occurs three times in the list of random numbers, the homeFinalScore variable should be 3). I've tried several things but have been unable to sort it yet!
Any help would be extremely helpful. Thank you in advance!
var homeFinalScore = 0;
function calculateScore(){
var homeTeam = document.getElementById("HomeTeam").value;
var awayTeam = document.getElementById("AwayTeam").value;
var homeGd = parseInt(document.getElementById("HomeGD").value);
var awayGd = parseInt(document.getElementById("AwayGD").value);
var homeGd = 20 + homeGd;
var awayGd = 15 + awayGd;
for (i = 0; i < homeGd; i++) {
var randNum = Math.floor(Math.random() * 11);
console.log(randNum);
}
}
You can create an array, use Array.prototype.push() to push randNum to the array, then use Array.prototype.filter(), .length to determine how many occurrences of a value are present within array.
var homeGd = 20 + 2;
var awayGd = 15 + 2;
var arr = [];
function countOccurrences(n, arr) {
return arr.filter(function(value) {
return value === n
}).length;
}
for (i = 0; i < homeGd; i++) {
var randNum = Math.floor(Math.random() * 11);
arr.push(randNum);
}
console.log(arr);
console.log(countOccurrences(2, arr));
Alternatively, you can increment a variable when randNum is equal to a value.
var homeGd = 20 + 2;
var awayGd = 15 + 2;
var n = 0;
var num = 2;
for (i = 0; i < homeGd; i++) {
var randNum = Math.floor(Math.random() * 11);
console.log(randNum);
if (randNum === num) {
++n
}
}
console.log("occurrences of 2:", n);
const homeGd = 10;
const randomNumbers = []; // array of random numbers
for (i = 0; i < homeGd; i++) {
randomNumbers.push(Math.floor(Math.random() * 11));
}
const countBy = randomNumbers.reduce((acc, current) => {
acc[current] = (acc[current] || 0) + 1;
return acc;
}, {});
console.log(countBy);

Javascript: Keep count of even and odd random numbers and get the sum of each

When I run this program I am only getting the even number count and the odd sum. The odd count and even sum just gives me 0 every time.
Does anyone have any idea what I am missing? Thanks!
I am trying to generate 100 random numbers and keep count of the evens/odds and then get the sum of each.
var min = 1;
var max = 1000;
var randomNumArray = []
var oddCount = []
var evenCount = []
var oddSum = []
var evenSum = []
function isEven(x){
if (x % 2 == 0)
return true;
else
return false;
}
function sumOfArray(evenSum){
for(i = 0; i< evenSum.length; i++){
if (isEven){
return(evenSum);
}
else{
return (oddSum);
}
}
}
for( i = 0; i < 100; i++){
var randNumber = Math.floor(min + (Math.random() * max));
randomNumArray.push(randNumber);
}
for( i = 0; i< randNumber.length; i++){
if (isEven(evenCount[i])){
return evenCount;
}
else{
return oddCount;
}
}
console.log('Even Number Count: ' + evenCount);
console.log('Odd Number Count: ' + oddCount);
console.log('Sum Even: ' + evenSum);
console.log('Sum Odd: ' + oddSum);
I would just use 1 function to check if its even or odd and then decide to add the sum by the number itself and the count by 1. You are making it way more complicated and I'm wondering why u are using arrays.
Try something like this:
for( i = 0; i < 100; i++){
var randNumber = Math.floor(min + (Math.random() * max));
if(isEven(randNum)){
evenSum = evensum+randNum;
evenCount ++;
}else{
oddSum= oddSum+randNum;
oddSum++;
}
}
var oddCount = 0
var evenCount = 0
for(i=0; i<randomNumArray.length; i++) {
if(randomNumArray[i] % 2 == 0) {
evenCount++
} else {
oddCount++
}
};
Something like that should work?

Unique Random Number Generator Javascript

I'm trying to make a bingo game for fun. I've looked in a lot of places for a unique generator but I can't seem to find one. I've tried to make my own,but once it actually hits a number that's the same it does an infinite loop. I've tried a simple code that in theory should work but for some reason things pass through. What can I do!?
var bc = [];
for (var i = 0; i < 5; i++) {
var r = Math.floor(Math.random()*20+1) + 0;
if(!(r in bc)){
bc.push(r);
}
else
{
i--;
}
}
____________________________________________
____________________________________________
____________________________________________
b1=0;
b2=0;
b3=0;
b4=0;
b5=0;
var bc = [b1,b2,b3,b4,b5]
var bnc = function(){
var n = Math.floor(Math.random() * 5+1)+0;
var n2 = Math.floor(Math.random() * 5+1)+0;
b1 = n;
var a1 = true;
var as = false;
while(a1){
var c = n;
if(c===b1||c===0 ||as!==false){
c = n2;
as=true;
}
if(c===b1||c===0&&as===true){
c = n;
as=false;
}
if(c!=b1){
b2 = c;
a1 = false;
a2 = true;
}
}
};
bnc();
console.log("new1");
console.log(b1,b2,b3,b4,b5);
//_______________________________________
var bnc2 = function(){
var n = Math.floor(Math.random() * 5+1)+0;
var n2 = Math.floor(Math.random() * 5+1)+0;
var a1 = true;
var as = false;
while(a1){
var c = n;
if(c===b1||c===b2||c===0&&as===false){
c = n2;
as=true;
}
if(c===b1||c===b2||c===0&&as===true){
c = n;
as=false;
}
if(c!=b1&&c!=b2){
b3 = c;
console.log("made it 1");
a1 = false;
}
}
};
bnc2();
console.log("new2");
console.log(b1,b2,b3,b4,b5);
once it actually hits a number that's the same
It never should. Such algorithms take longer the longer they run. You should take a different approach:
Put all possible numbers into a pool. Once you draw a number, remove it from the pool. Just like it's done in real life.
var pool = [1, 2, 3, 4, 5];
var getNumber = function () {
if (pool.length == 0) {
throw "No numbers left";
}
var index = Math.floor(pool.length * Math.random());
var drawn = pool.splice(index, 1);
return drawn[0];
};
I would rather do it with something like this:
http://jsfiddle.net/YC58s/
generate = function(length)
{
var arr = [];
var n;
for(var i=0; i<length; i++)
{
do
n = Math.floor(Math.random()*20+1);
while(arr.indexOf(n) !== -1)
arr[i] = n;
}
return arr;
}
This can handle generating upto 20 digit UNIQUE random number
JS
var generatedNumbers = [];
function generateRandomNumber(precision) { // precision --> number precision in integer
if (precision <= 20) {
var randomNum = Math.round(Math.random().toFixed(precision) * Math.pow(10, precision));
if (generatedNumbers.indexOf(randomNum) > -1) {
if (generatedNumbers.length == Math.pow(10, precision))
return "Generated all values with this precision";
return generateRandomNumber(precision);
} else {
generatedNumbers.push(randomNum);
return randomNum;
}
} else
return "Number Precision shoould not exceed 20";
}
generateRandomNumber(1);
JsFiddle
window.onload = unRanNumGen(20, 1, 12);
//above, we need 12 random numbers between 20 (included) and 1(included)
function unRanNumGen(max, min, limit){
//max = maximum number [inclued] (range of numbers)
//min = minimum number [included] (range of numbers)
//limit = number of random numbers (how many numbers do you want?)
var pool = [genRan(max, min)];
for(i=0; i<limit; i++){
for(n = 0; n <i; n++){
if(pool[n] !== genRan(max, min)){
pool.push(genRan(max, min));
break;
}
}
}
function genRan(max, min){
var genRan = Math.floor(Math.random() * (max - min) + min);
return genRan;
}
alert(pool.join('\n')); //to display the array of random numbers
}

Categories