Print a random integer number between 1 and 42 (both inclusive) to the console [duplicate] - javascript

This question already has answers here:
Generating random integer in range that doesn't start at zero
(4 answers)
Closed 3 days ago.
I have a question in a exercise to print a random integer number between 1 and 42, but im getting an error in my console "Are you doing the multiplication inside the ceil() method call?"
My code is this one.
var someRandomNumber = Math.random();
var wholeRandomNumber = Math.ceil(someRandomNumber);
console.log(Math.ceil(Math.random() * 42));
I dont know what im doing wrong, honestly if someone can help me! :)

You should try this
function generateRandom(min = 0, max = 1000) {
// find diff
let difference = max - min;
// generate random number
let rand = Math.random();
// multiply with difference
rand = Math.floor( rand * difference);
// add with min value
rand = rand + min;
return rand;
}
console.log(generateRandom(min=1,max=42));

Related

Math random add subtract counter limited between a range of numbers [duplicate]

This question already has answers here:
Generating random whole numbers in JavaScript in a specific range
(40 answers)
Closed 2 years ago.
can you help me out on how to limit the below to stay within a min and max range eg 3 - 10
<div id="number">3</div>
setInterval(function(){
random = (Math.floor((Math.random()*1)+1));
var plusOrMinus = Math.random() < 0.5 ? -1 : 1;
random = random * plusOrMinus;
currentnumber = document.getElementById('number');
document.getElementById('number').innerHTML = parseInt(currentnumber.innerHTML) + random;
}, 1000);
See Mozilla Docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#getting_a_random_number_between_two_values
Getting a random integer between two values This example returns a random integer between the specified values. The value is no lower
than min (or the next integer greater than min if min isn't an
integer), and is less than (but not equal to) max.
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
}
By Mozilla Contributors, licensed under CC-BY-SA 2.5.

Why isn't this code working to find the sum of multiples of 3 and 5 below the given number?

I've started with some problems on HackerRank, and am stuck with one of the Project Euler problems available there.
The problem statement says: Find the sum of all the multiples of 3 or 5 below N
I've calculated the sum by finding sum of multiple of 3 + sum of multiples of 5 - sum of multiples of 15 below the number n
function something(n) {
n = n-1;
let a = Math.trunc(n / 3);
let b = Math.trunc(n / 5);
let c = Math.trunc(n / 15);
return (3 * a * (a + 1) + 5 * b * (b + 1) - 15 * c * (c + 1)) / 2;
}
console.log(something(1000)); //change 1000 to any number
With the values of num I've tried, it seems to work perfectly, but with two out of five test cases there, it returns a wrong answer (I can't access the test cases).
My question is what is the problem with my code? as the logic seems to be correct to me at least.
Edit: Link to problem page
Some of the numbers in the input are probably larger than what javascript can handle by default. As stated in the discussion on the hackkerrank-site, you will need an extra library (like: bignumber.js) for that.
The following info and code was posted by a user named john_manuel_men1 on the discussion, where several other people had the same or similar problems like yours
This is how I figured it out in javascript. BigNumber.js seems to store the results as strings. Using the .toNumber() method shifted the result for some reason, so I used .toString() instead.
function main() {
var BigNumber = require('bignumber.js');
var t = new BigNumber(readLine()).toNumber();
var n;
for(var a0 = 0; a0 < t; a0++){
n = new BigNumber(readLine());
answer();
}
function answer() {
const a = n.minus(1).dividedBy(3).floor();
const b = n.minus(1).dividedBy(5).floor();
const c = n.minus(1).dividedBy(15).floor();
const sumThree = a.times(3).times(a.plus(1)).dividedBy(2);
const sumFive = b.times(5).times(b.plus(1)).dividedBy(2);
const sumFifteen = c.times(15).times(c.plus(1)).dividedBy(2);
const sumOfAll = sumThree.plus(sumFive).minus(sumFifteen);
console.log(sumOfAll.toString());
}
}

get always 10 numbers from randoms - Javascript [duplicate]

This question already has answers here:
Want to produce random numbers between 1-45 without repetition
(4 answers)
Closed 4 years ago.
I need help with my code. I want to get 10 random numbers every time it rolls and it can't have duplicated, this is my code:
for(let j = 1; j <= 21; j++) {
const number = (Math.floor((Math.random() * j) + 1))
const genNumber = array.indexOf(number);
if (genNumber === -1) {
array.push(number);
}
}
I have no idea how I can get exactly 10 numbers every time, anyway it can be written with js or jquery it doesnt metter for me. Hope I can get help here.
I don't really understand what your code is intended to do, but to get exactly 10 unique random numbers I'd use a Set and loop until it's filled. I have no idea why you loop 21 times for 10 items though...
let s = new Set();
while (s.size < 10) {
s.add((Math.floor(Math.random() * 21 /* ??? */) + 1));
}
console.log([...s]);
You're almost there, but instead of using a for loop, use a while loop that continues as long as there are less than 10 things in the array:
const array = [];
const j = 21; // Pick numbers between 1 and 21 (inclusive)
while (array.length < 10) {
const number = (Math.floor((Math.random() * j) + 1))
const genNumber = array.indexOf(number);
if (genNumber === -1) {
array.push(number);
}
}
console.log(array);

Prompting for a variable not working when trying to find random number

My assignment for Intro to Javascript is to: "Write a function that accepts two numbers and returns a random number between the two values." It seems easy enough until I attempt to prompt the variables to input, at which point the output seems incorrect.
This is code that is most recommended for finding a random number between two ints, in this case 1 and 6:
function getRandomizer(bottom, top) {
return function() {
return Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom;
}
}
var rolldie = getRandomizer(1, 6);
document.write(rolldie());
The output I get is what it should be, a random integer between 1 and 6. However my assignment is to prompt for the numbers, which can be anything. So I do this, using 10 and 1 as example numbers:
var max = prompt("input 10");
var min = prompt("input 1");
function getRandomizer(bottom, top) {
return function() {
return Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom;
}
}
var rolldie = getRandomizer(min, max);
document.write(rolldie());
The output: 961. Second try: 231. etc. If I set the variables max and min directly to 10 and 1, the code works perfectly, returning numbers between 1 and 10. But for some reason, prompting input and then entering the exact same numbers gives completely different output. Why does this happen and how can I fix it?
The reason this happens is that the prompts are being treated as strings. So you're actually getting numbers between 1101 and 1.
You can ensure the vars min and max are numbers by using parseInt:
var max = parseInt(prompt("input 10"));
Try this Code below:
var max = Number(prompt("input 10"));
var min = Number(prompt("input 1"));

Generate random number, between 2 numbers? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Generating random numbers in Javascript in a specific range?
Say I wanted to generate a random number from 50 to 100.
I know there's:
Math.random()
but I could only find ways to go from 1 to 'x'
From MDN on Math.random():
// Returns a random integer between min and max
// Using Math.round() will give you a non-uniform distribution!
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
I believe this would also work:
function randomInt(min,range) {
return Math.floor((Math.random()*(range+1))+min)
}
In your case min would be 50 and range would be 50

Categories