Reputation:
I need to create a two arrays. One with 24 random numbers between 5 and 20. The second with 24 random numbers between 1 and 10. I think I'm on the right track with creating the arrays but can't get the minimum of 5 & 1 to stick. Here's my code:
function getRandomNumber(min, max)
{
return Math.floor(Math.random() * max) + min;
}
var volts = [];
var amps = [];
for(var i = 0; i < 24; i++) {
volts.push(getRandomNumber(5, 20));
}
for(var i = 0; i < 24; i++) {
amps.push(getRandomNumber(1, 10));
}
var power = 0;
for(var i=0; i < volts.length; i++){
power = (volts[i]*amps[i]);
}
console.log(volts);
console.log(amps);
console.log(power);
How would I add a third loop that performs an equation of volts multiplied by amps? Each iteration would multiply the random elements produced by each array
Upvotes: 0
Views: 799
Reputation: 1
function getRandomArray(length, min, max){
let arr = [];
for (let i = 0; i < length; i++){
arr.push((Math.random() * (max - min) + min).toFixed());;
}
return arr;
}
console.log(getRandomArray(24, 5, 20));
Upvotes: 0
Reputation: 590
Solution:
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var volts = [];
var amps = [];
for(var i = 0; i < 24; i++) {
volts.push(getRandomNumber(5, 20);
}
for(var i = 0; i < 24; i++) {
amps.push(getRandomNumber(1, 10);
}
console.log(volts);
console.log(amps);
Also in case you would like to use ES6 you can try this code:
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const volts = Array.from({length: 24}, () => getRandomNumber(5, 20);
const amps = Array.from({length: 24}, () => getRandomNumber(1, 10);
console.log(volts);
console.log(amps);
UPDATE [06/09/2018]
If you need to multiply these two arrays you could just create a third loop:
result = [];
for(var i = 0; i < 24; i++) {
result.push(amps[i] * volts[i]);
}
console.log(result)
Upvotes: 0
Reputation: 10096
To get a min/max random number between 5 and 20,
you'd use Math.floor(Math.random() * (20 - 5 + 1)) + 5
, from the MDN docs:
// Returns a random integer between min (include) and max (include)
Math.floor(Math.random() * (max - min + 1)) + min;
You can then use Array.from
to create the array smoothly:
function randomBetween(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
let volts = Array.from({length: 24}, () => randomBetween(5, 20));
let amps = Array.from({length: 24}, () => randomBetween(1, 10));
console.log(volts, amps);
Upvotes: 1