Generate number but exclude one number in javascript [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I need to generate one random number between a range but exclude one specific number.
I thought I can do this like that but it didn't work.
function randNum(num){
var randNumber=Math.floor(Math.random()*num)+1;
if(randNumber==2){
randNum(num);
}else{
alert(num);
}
}
randNum(4);
What is the problem?
Thanks.

Assuming you want to output the random number and not the num-parameter, you just have to change the alert to:
alert(randNumber)
Like in this fiddle http://jsfiddle.net/3urFC/

Are you trying to alert the randNum that you generated? Right now you will alert the function argument (in this case the number 4) everytime. I think you want to change it to alert(randNumber).

Math.random returns a number between 0 and 1. See the documentation on MDN.
Also, see this question about generating a random number in a specific range.
So, you have two problems: one, you're not generating a random number in the range you think you are, and two, you're not using the random number you generated.
I made this fiddle that does something similar to what you described.
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function generateRandomWithExclusion(exclude, min, max) {
var num = getRandomInt(min, max);
while (num === exclude) {
num = geRandomInt(min, max);
}
return num;
}
generateRandomWithExclusion(2, 0, 10) // returns an integer between 0 and 10 that is not 2
You pass the number you want to exclude and a range of min and max, and get a random integer in that range that isn't the number you want excluded.

function randNum(num) {
var randNumber;
do { randNumber = Math.floor(Math.random()*num)+1; } while(randNumber==2);
return randNumber;
}
randNum(4);

There is a typho as other has stated.
Also I would rearrange it this way:
function randNum(num){
var numberToExclude=2;
var randNumber=Math.floor(Math.random()*(num-1))+1;
if(randNumber>=numberToExclude) {
randNumber+=1;
}
alert(randNumber);
}
randNum(4);
Here is a JSFidle
http://jsfiddle.net/2F5Md/1/

Related

So I am trying to pluralize my pennies but it keeps failing my pipeline

Trying to get the following to pass my pipeline it is failing to pluralize. The rest of the change passed the pipeline just can't seem to get the pennies to pass. Help with this would be greatly appreciated. I have tried everything I could think of to get the pennies function to pass the pipeline.
function pluralizePennies(change) {
// calculate the number of pennies from the given change
let pennies = Math.floor(change/0.01);
// calculate the remaining change
let changeRemainder = change % 0.01;
// determine the correct string for the number of pennies, whether it is plural or not
let penniesString;
if (pennies == 1) {
penniesString = 'penny';
} else {
penniesString = 'pennies';
}
// output the result to a given element
document.getElementById('penny-output').textContent = `${pennies} ${penniesString}`;
// return the remaining change
return changeRemainder;
}
So, my output so far reads
$7.67
7 dollars
2 quarters
1 dime
1 nickel
1 penny (but this needs to read 2 pennies
don't use floats, use no change*100, etc. instead

JavasScript Add half a percent to a number any amount of times I choose

Hi I need a block of code for some math that I'm trying to work out. The code I'm looking for will be able to add half a percent (0.005) to a number and return the result back to me. I need the code to take two separate inputs, the first is the start number, and the second is how many times I want the loop to execute. An example would be if I started with 7000 the code should output ~7321.37 (if possible let it stop after 2 decimal points). Thank you for the help in advance!
Code example of what I'm trying to do:
function growth(initialValue, timesOfExecution)` {
let answer;
let execute;
while (execute > 0) {
answer = initialValue + initialValue(0.05)
execute--
}
return answer;
}
console.log(growth(7000, 9))
Here you go:
function growth(initialValue, timesOfExecution) {
for (let i = 0; i < timesOfExecution; i++) {
initialValue = initialValue + (initialValue * 0.005)
}
return initialValue.toFixed(2);
}
console.log(growth(7000, 9))

How to add functions on randomly generated numbers

Is it possible to add a function on randomly generated numbers. For example I used getRndInteger(min, max), Math.floor() and Math.random() to generate random numbers, and within those numbers you want to add function to see which of those generated numbers is the biggest. I was thinking maybe it was possible to put each randomized number in array and use Math.max() on them, but I'm not quite sure how you put those numbers in a function that for example on click, you see the generated numbers and result(the biggest number of them all) underneath it. I mainly want to know if it's even possible and if so, how. I'd be super thankful!
So I specifically want to use a random number from -35 to 76 including -35 and 76. I made a button that on click shows the randomized number. Another problem to me is, I'm not sure how to add a randomized number one after another instead of adding new one on click. (Haha sorry if it's a super newbie problem). Then I put an id on paragraph that displays the answer. And I was thinking to use the document.getElementById("") for the Math.max.apply() and make another paragraph with another ID that displays the answer.
<button onclick="document.getElementById('result').innerHTML = getRndInteger(-35,76)">Click Me</button>
Chosen number:
<p id="result"></p>
Biggest number:
<p id="result2"> </p>
<script>
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
</script>
<script>
Array.max = function(document.getElementById("result");) {
return Math.max.apply(document.getElementById"result");
};
</script>
When I put .getElementById() in Math.max.apply() as an array, even on click, java script no longer loads randomized number. Maybe you have to add id to the answers or something, I'm all out of ideas here. Any help would be greatly appreciated! I'd also like if I'd still use Math.max() to do this and avoid any overly complicated codes to understand the issue and use the answer in the future codes. Thank you loads!
You should store the previously generated maximum number to be able to determine that the currently generated number is higher than it. See snippet to get an idea.
(() => {
let max = null;
const range = {
min: -35,
max: 76
};
const result = document.querySelector("#result");
const maxResult = document.querySelector("#resultMax");
const allNrs = document.querySelector("p#all");
document.querySelector("button").addEventListener("click", handleButtonClick);
function handleButtonClick() {
const someRandomNumber = getRndInteger(range.min, range.max);
result.textContent = someRandomNumber;
max = max && someRandomNumber > max
? someRandomNumber
: max
? max
: someRandomNumber;
maxResult.textContent = max;
allNrs.textContent += ` ${someRandomNumber} `;
}
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
})();
#all {
max-width: 400px
}
<p>
<button>Click Me</button>
</p>
Random number:
<span id="result"></span>
<br>Biggest number until now:
<span id="resultMax"></span>
<div>
<br>All numbers until now:
<p id="all"></p>
</div>

Average calculator finding strange and incorrect numbers [duplicate]

This question already has answers here:
How to get numeric value from a prompt box? [duplicate]
(6 answers)
Closed 3 years ago.
I am trying to make an average calculator. This is my code for it:
var data = [];
var yesno = confirm("Would you like to add more data?");
while (yesno) {
var newdata = prompt("Enter a piece of data (must be a number)");
data.push(newdata);
var yesno = confirm("Would you like to add more data?");
}
var total = 0;
var i = 0;
if (!yesno) {
while (i < data.length) {
total += data[i];
i++;
}
}
var average = total / data.length;
document.write(average);
It seems to take input well, however something goes wrong when it comes to calculation. It says that the average of 6 and 6 is 33, 2 and 2 is 11, and 12 and 6 is 306. These are obviously wrong. Thank you in advance for your help.
You need to take a number, not a string value from the prompt.
The easiest was is to take an unary plus + for converting a number as string to a number
data.push(+newdata);
// ^
Your first example shows, with '6' plus '6', you get '66', instead of 12. The later divsion converts the value to a number, but you get a wrong result with it.
It is taking the input as string. Convert the input to floats before putting them in the array. I think its performing string additions like 6+6=66 and then 66/2 = 33. Similar is the case of 2 and 2.

How to generate random numbers in Javascript [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Generating random numbers in Javascript
Hi..
I want to generate random numbers (integers) in javascript within a specified range. ie. 101-999. How can I do that. Does Math.random() function supports range parameters ?
Just scale the result:
function randomInRange(from, to) {
var r = Math.random();
return Math.floor(r * (to - from) + from);
}
The function below takes a min and max value (your range).
function randomXToY(minVal,maxVal)
{
var randVal = minVal+(Math.random()*(maxVal-minVal));
return Math.round(randVal);
}
Use:
var random = randomXToY(101, 999);
Hope this helps.
Math.floor(Math.random()*898)+101

Categories

Resources