How to use if-statement with randgen [duplicate] - javascript

This question already has answers here:
Random number, which is not equal to the previous number
(16 answers)
Closed 4 years ago.
I'm trying to make sure two randomly generated numbers don't match, is there a way to do this in an if-statement?
i'm fairly new to javascript and couldn't find anything that answered my question, rand2 and rand3 both pick from the same list and it would make the outcome seem odd if they matched. my code also stopped working when i put the if-statement in (if i messed that up i guess it wouldn't matter if i got an answer).
function sentence() {
var rand1 = Math.floor(Math.random() * 2);
var rand2 = Math.floor(Math.random() * 12);
var rand3 = Math.floor(Math.random() * 12);
var rand4 = Math.floor(Math.random() * 10);
var rand5 = Math.floor(Math.random() * 10);
var rand6 = Math.floor(Math.random() * 10);
// var randCol = [rand1,rand2,rand3,rand4,rand5];
// var i = randGen();
if (rand2 == rand3) {
// whatever changes one
} else {
//
}

You could use a do while statement that runs while the numbers are the same, therefore will terminate as soon as the random numbers generated are different.
e.g.
var rand2 = 1;
var rand3 = 1;
do {
rand2 = Math.floor(Math.random() * 12);
rand3 = Math.floor(Math.random() * 12);
} while(rand2 === rand3 );
Hope that helps :)

Related

Storing random generated number in a variable, why does the value not change?

The first time I type the random variable in the console I get a number between 1 and 10 which is expected. Then every time I retype the random variable it gives me the same number. Why is this?
var random = Math.floor(Math.random() * 10) + 1;
Instead of using a variable, you should create a function to generate a random number.
const random = () => Math.floor(Math.random() * 10) + 1;
const number1 = random();
const number2 = random();
const number3 = random();
console.log(number1, number2, number3);
Also this is useful,
const randomVariable = function () {
return Math.floor(Math.random() * 4);
};
randomVariable();

if x bigger than y then return x smaller than y javascript

I'am trying to make a simple calculation generator in prompt window. But it should not generate a negative number as answer, such as: x-y=-answer
My code so far:
CodepenLink
How it should look like
function myFunction() {
var randomNumber = Math.floor(Math.random() * 10);
var nxtRandomNumber = Math.floor(Math.random() * 10);
var question = prompt("What is:"+ randomNumber+ " minus " + nxtRandomNumber);
if(nxtRandomNumber > randomNumber){
return ;
}
var result = Number(randomNumber) - Number(nxtRandomNumber);
document.getElementById("demo").innerHTML = "Number:" + answer + " was right!";
}
<p>Push the button to start </p>
<button onclick="myFunction()">Calculate!</button>
<p id="demo"></p>
make sure when you calculate nxtRandomNumber to use the value of randomNumber as a minimum.
So if randomNumber is 5, nextRandomNumber should be calculated to compute a number at least equal to 'randomNumber'
for ex:
nextRandomNumber = Math.floor(Math.random() * 10) + randomNumber;
Theres a trick to generate random number between 2 values.
var nxtRandomNumber = Math.floor(Math.random() * (10 - randomNumber) + randomNumber);
From mdn
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
This example returns a random number between the specified values. The returned value is no lower than (and may possibly equal) min, and is less than (and not equal) max.>>>

Conflict when trying to generate two separate numbers

I have the following script, which is meant to generate 2 different numbers
<script type="text/javascript">
function GenerateRandomNumber2to6No1() {
var min = 2, max = 7;
var random = Math.floor(Math.random() * (max - min + 1)) + min;
return random;
}
var GenerateRandomNumber2to6No1 = GenerateRandomNumber2to6No1();
$('.GenerateRandomNumber2to6No1').html(GenerateRandomNumber2to6No1);
function GenerateRandomNumber2to6No2() {
var min = 2, max = 7;
var random = Math.floor(Math.random() * (max - min + 1)) + min;
return (random !== GenerateRandomNumber2to6No1) ? random: GenerateRandomNumber2to6No2();
}
var GenerateRandomNumber2to6No2 = GenerateRandomNumber2to6No2();
$('.GenerateRandomNumber2to6No2').html(GenerateRandomNumber2to6No2);
</script>
NUMBER 1: <span class = "GenerateRandomNumber2to6No1"></span>
NUMBER 2: <span class = "GenerateRandomNumber2to6No2"></span>
This usually works fine but occasionally the page will load and no numbers will appear. I'm guessing this is when GenerateRandomNumber2to6No2 happens to generate the same number as GenerateRandomNumber2to6No1. I thought that
return (random !== GenerateRandomNumber2to6No1) ? random: GenerateRandomNumber2to6No2(); accounted for this, but perhaps instead of generating another unique number when there's redundancy, it generates no number at all. Is this the case? If so, how can I fix this?
Thanks!
function getRand(){
var array=[2,3,4,5,6,7]
var newArray=[];
for(var i=0;i<2;i++){
var ran=~~(array.length*Math.random());
newArray[i]=array.splice(ran,1)[0]
}
return newArray
}
var ranArray=getRand();
var ran1=ranArray[0];
var ran2=ranArray[1];
console.log(ran1,ran2)
getRand() is a function to give you an array of distinct numbers.Since you only need two,it only loop two times,and give you an array,which you can make use of it.
Back to your code,from what I see,Gno2 should keep running until it got another number,I don't know why.It's the time you try to debug.
First I will try to change the max=2 to max=3,if the code may not work for some number,then you can quickly realize and found out the problem is in these two functions.
Then try to log,console.log(Gno1,Gno2),see what exactly the numbers are,also help you to know where is the problem.
I think this piece of code can help you
var rand1,rand2;
var min = 3;
var max = 6;
do {
rand1 = Math.floor(Math.random() * (max - min)) + min;
rand2 = Math.floor(Math.random() * (max - min)) + min;
}while(rand1 === rand2);
$('.GenerateRandomNumber2to6No1').html(rand1);
$('.GenerateRandomNumber2to6No2').html(rand2);

Using variables inside javascript for loop few times

I don't know how to name a title for my question. Here is the problem:
//Setup all the stats.
var randomStat = Math.floor(Math.random() * ((monster.level + 5) - monster.level + 1) + monster.level);
var multiplier = randomStat * itemQuality.qualityMultiplier;
//Assign the Stats.
var strength = Math.floor(multiplier * itemSubType.strengthMultiplier / 2); //divide each stat by 2 for better balance
var endurance = Math.floor(multiplier * itemSubType.enduranceMultiplier / 2);
var agility = Math.floor(multiplier * itemSubType.agilityMultiplier / 2);
var dexterity = Math.floor(multiplier * itemSubType.dexterityMultiplier / 2);
var wisdom = Math.floor(multiplier * itemSubType.wisdomMultiplier / 2);
var intelligence = Math.floor(multiplier * itemSubType.intelligenceMultiplier / 2);
var luck = Math.floor(multiplier * itemSubType.luckMultiplier / 2);
What it does, is create a randomStat variable and multiplier variable, then use them for each stat. My problem is that if each stat i.e. "strengthMultiplier" is the same as "enduranceMultiplier" which is the case sometimes, then stats will be exactly the same, because randomStat and multiplier is called just once and is used for every stat.
I am trying to create a loop for it, to call it 7 times, and each time its called use it for a single stat, up to 7 stats total.
I could of course create 2 new variables for each stat (total 14) but I hope there is better way to do that, using loops.
I am using javascript, so any help is welcome with javascript only, not jquery or anything else. Thanks :)
You might keep your stats in an array or an object (the latter shown here), and iterate over those:
var stats = {
strenght: null,
endurance: null,
agility: null,
dexterity: null,
wisdom: null,
intelligence: null,
luck: null
};
for (var stat in stats) {
// todo: consider using Object.hasOwnProperty here.
var randomStat = Math.floor(Math.random() * ((monster.level + 5) - monster.level + 1) + monster.level);
var multiplier = randomStat * itemQuality.qualityMultiplier;
stats[stat] = Math.floor(multiplier * itemSubType[stat + 'Multiplier'] / 2);
}
That would store values in a stats dict, i.e. as stats.luck instead of luck.

Generate random numbers Jquery

I'd like to show a random numbers within my list. Im grabbing the list from the backend, and im just using these numbers as examples. This is my code, I'm not quite sure why its not filling in the text.
setInterval(function() {
var number = 1 + Math.floor(Math.random() * 6);
$('.num-gen').text(number);
},
Made a fiddle here to show you what I'm working with. Thanks in advance.
You had an error in your code, you were missing the finishing , 1000/*time in ms*/);!
Also, jQuery is not required here, you may do this in Javascript like this.
setInterval(function() {
var number = 1 + Math.floor(Math.random() * 6);
document.getElementsByClass('num-gen')[0].innerHtml = number;
}, 1000);
EDIT:
setInterval(function() {
jQuery.each(jQuery('.num-gen'),function(){
var number = 1 + Math.floor(Math.random() * 6);
jQuery(this).text(number);
});
}, 1000);
you have syntax error in you code, change it to:
setInterval(function() {
var number = 1 + Math.floor(Math.random() * 6);
$('.num-gen').text(number);
}, 10);

Categories

Resources