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>
Related
I'm writing a basic random number generator (self teachingvia freeCodeCamp, going to use it for games with my 2 little boys). I'm using a basic HTML with no CSS added as the DOM and Javascript client side for the function (client side as my eldest is 5 and we have a family blog he loves to show people).
The problem is that the code below is working to a point - the Math random function is fine, it works with Math.floor well and the multiplcation * (maximum - minimum +1) is all working as expected.
The issue is that the last segment is not working: + minimum. From the results I have looked at the formula is generating a result up to and including the multiplcation bracked, but then concatenating the minimum on the end, rather than adding it to the result.
I have converted the maximum and minimum values to integers via parseInt when I first discovered the problem, in case there was an issue there (I didn't see why as they both worked fine in the multiplcation bracket), but that of course made no difference.
function randomNumberFunction(maximum, minimum) {
var numRan;
var maximum = document.getElementById("maximum").value;
var minimum = document.getElementById("minimum").value;
parseInt(maximum);
parseInt(minimum);
numRan = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
alert(numRan);
}
<div id="dice">
<form name="randomDice">
<h1>Get a random number</h1>
<p>Maximum</p>
<input id="maximum" type="number" name="random"><br>
<p>Minimum</p>
<input id="minimum" type="number" name="random"><br>
<br>
<button onclick="randomNumberFunction()">Get a random number</button>
</form>
</div>
I'm looking to be able to capture the minimum and maximum values a user inputs, and produce a random integer from that range. Instead I get values like 01 when I input min 1, max 4, or 21. or 63 when inputting min 3, max 10.
You aren't assign value when you cast minimum and maximum variables
Try this:
function randomNumberFunction(maximum, minimum) {
var numRan;
var maximum = document.getElementById("maximum").value;
var minimum = document.getElementById("minimum").value;
maximum = parseInt(maximum);
minimum = parseInt(minimum);
numRan = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
alert(numRan);
}
I have been trying to figure out how to do this thing on my own for a while now. I need to create something that will allow the user, by pushing a button on screen or refreshing the browser window, to generate numbers/words. The thing is I have figured out how to do this so that the numbers/words are generated randomly, but what I need is to ensure they generate at a percentage chance so that one will have a 95% chance of returning to screen and another a 20% chance and so on.
I know this is more of a favor for service than a question, but I have been trying to figure this out on my own for too long. I totally understand if I get kicked from site/no one gives me the time of day.
Below is the code I use to generate random numbers but as explained above I want to change this so each number is generated at percentage chance.
<html>
<body>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<p id="demo4"></p>
<p id="demo5"></p>
<p id="demo6"></p>
<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 10);
document.getElementById("demo1").innerHTML =
Math.floor(Math.random() * 10);
document.getElementById("demo2").innerHTML =
Math.floor(Math.random() * 10);
document.getElementById("demo3").innerHTML =
Math.floor(Math.random() * 10);
document.getElementById("demo4").innerHTML =
Math.floor(Math.random() * 10);
document.getElementById("demo5").innerHTML =
Math.floor(Math.random() * 10);
document.getElementById("demo6").innerHTML =
Math.floor(Math.random() * 10);
</script>
</body>
</html>
Thank you.
PS : I have no programming experience FYI.
It was clarified in a comment that a single click of a button (or page refresh, whatever) could show any number of words simultaneously, with each word having its own percentage chance of appearing.
On that basis, you need to define a list of words with their chances, so maybe an array of objects like:
var words = [ { word: "Hello", chance: 10 }, { word: "Hi", chance: 95 }, /* etc. */ ]
Or just an object where each property name is a word with the associated value giving the chance of appearance:
var words = { "Hello": 10, "Hi" : 95, /* etc. */ }
Either way, when the button is clicked you iterate over the list, and decide for each one whether to display it. For this demo I've gone with the second option of using an object rather than an array of objects:
var words = {
"Green": 95, "Yellow": 25, "Blue": 50, "Orange": 75, "Black": 33, "Purple": 10
}
document.getElementById("generate") // when the button
.addEventListener("click", function() { // is clicked
var output = [] // create an empty array, then
Object.keys(words).forEach(function(word) { // for each word in the list
if (Math.random() * 100 < words[word]) // decide whether to display
output.push(word) // if so add to output array
})
// finally, turn output array into a string separated by <br> elements
document.getElementById("output").innerHTML = output.join("<br>")
})
<button id="generate">Show words</button>
<div id="output"></div>
You could change the last line to output.join(", ") to show the selected words as a comma-separated list. Or you could add very slightly more complicated code to output each word in its own li element in a ul, or whatever.
If you can generate random numbers, you can use the generated number with a series of if statements to choose which word to display. So if you wanted your word to be 'apple' 25% of the time and 'banana' 75%:
function randomWord(){
var num = Math.floor(Math.random() * 100);
var word;
if (num < 26){
word = 'apple';
} else {
word = 'banana';
}
return word;
}
Etc for however many options you want to consider.
Edit: after re-reading and seeing your code, this doesn't exactly answer your question, but it might help you anyway.
I want to round up a decimal value in JavaScript. I need functionality something like below :
if decimal value is grater than or equal to 25 then i want to round up a value by plus one.
eg. if value = 5.56789 then new value should be 6
I know using if condition it is possible.
I have done using if condition like below :
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the fixed number.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var num = 5.24389;
var n = num.toFixed(2)
var num_arr = n.split('.');
var newval = num_arr[0];
if(num_arr[1] >= 25)
{
newval++;
}
document.getElementById("demo").innerHTML = newval;
}
</script>
</body>
</html>
But i don't want to use any conditions.
So is there any JavaScript function which do like my example?
Any help would be appreciated!!
So the question here is how can you shift the rounding point so it is .25 instead of .50. The basic idea is you need to subtract .25 and round up to the nearest whole number.
If we are dealing with two decimal max it is simple, we subtract .24 and use ceil().
function roundUpOverQuarter(num) {
return Math.ceil(num - .24);
}
console.log("1", roundUpOverQuarter(1));
console.log("1.24", roundUpOverQuarter(1.24));
console.log("1.25", roundUpOverQuarter(1.25));
console.log("1.5", roundUpOverQuarter(1.5));
Now the code above works with "money" value, only two decimals.To deal with greater than two decimals, it requires a bit more math. You would need to first chop it to two decimals by shifting the number up two, floor it, to drop the decimals, then shift the number back so we can follow the same process we did above.
function roundUpOverQuarter(num) {
num = Math.floor((num*100))/100;
return Math.ceil(num - .24);
}
console.log("1", roundUpOverQuarter(1));
console.log("1.24", roundUpOverQuarter(1.24));
console.log("1.25", roundUpOverQuarter(1.25));
console.log("1.5", roundUpOverQuarter(1.5));
console.log("1.24999", roundUpOverQuarter(1.24999)); //would fail with the first solution
I am creating a game,now as the code,when i click attack,the enemies power lowers randomly,but i want same with player but the random value should be different from the one in enemies ..if possible,can there aso be a heal option to randomly raise players power and decrease it too because enemy is still attacking
appearence(current): http://amerish.webs.com/amerish/testgame.html
code:
<head>
<script>
var playerHealth=100;
var enemyHealth=100;
var strength=10;
function begin(){
document.getElementById'playerhealth').innerHTML= playerHealth;
document.getElementById('enemyhealth').innerHTML =enemyHealth;
}
function hitEnemy(){
var attack=Math.floor(Math.random()*20 +strength);
enemyHealth =enemyHealth - attack;
document.getElementById('damage').innerHTML= attack;
document.getElementById('enemyhealth').innerHTML =enemyHealth;
}
</script>
<body onload="begin()">
<input type="button" name="doit" id="doit" value="Attack!"
onclick="hitEnemy();">
<br /
<span>playerhealth</span>
<div style="font-ize:3em;"id="playerhealth"></div>
<span>enemyhealth</span>
<div style="font-size:3em;"id="enemyhealth"></div>
<br />
<span>You Did:</span><span style="font-size:3em;"id="damage"></span>
<span>damage</span>
</body>
This question looks like homework, did you write the code so far yourself? If you didn't, try to read through it and understand what each function is doing and where it is being invoked from.
the random value should be different from the one in enemies
Q: How can I generate random integers?
A: Here is a general-use function to generate pseudo-random integers
function rand_int(max, min) {
min = min | 0;
if (max === (max | 0))
if (max < min)
throw new RangeError("Range cannot be negative [" + min + '..' + max + ']');
else
return min + Math.floor(Math.random() * (max - min + 1));
throw new TypeError("Expected Integer for max but recieved: " + max);
}
Explanation: The random number is coming from Javascript's own Math.random which is between 0 and (but not equal to) 1. The x | 0 used to convert variables to 32-bit integers. Math.floor is used to change the floating point number into an Integer by always "rounding down". It works better than x | 0 for distributions over positive-and-negative numbers
can there aso be a heal option to randomly raise players power
Q: How can I add a random number to player's health?
A: Make a second <input> type button which causes something like the following to happen
playerHealth += rand_int(10); // add between 0 and 10
and decrease it too because enemy is still attacking
Q: Where do I put the code for the enemy turn?
A: Make a copy of the function hitEnemy, rename it to hitPlayer and change all occurances of enemy to player inside it. Then invoke it after hitEnemy is called, for example
<input
type="button" name="doit" id="doit"
value="Attack!" onclick="hitEnemy();hitPlayer();"
/>
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/