This is how I generate 6 different numbers:
window.random_row = Math.floor(Math.random() * (len_board - 1)) + 1;
window.random_column = Math.floor(Math.random() * (len_board - 1)) + 1;
window.random_row2 = Math.floor(Math.random() * ((len_board-1) - 1)) + 1;
window.random_column2 = Math.floor(Math.random() * ((len_board-1) - 1)) + 1;
window.random_row3 = Math.floor(Math.random() * ((len_board+1) - 1)) + 1;
window.random_column3 = Math.floor(Math.random() * ((len_board+1) - 1)) + 1;
However, I don't want the rows/columns to be the same number, e.g random_row == random_column is allowed, but I don't want random_row == random_row2. I was thinking of using an if/else statement. Something along the lines of: if (random_row == random_row2) then generate a new random_row2 but it came to my mind that the number could be the same again so I guess that would not be the right way to go about it. Does anyone have an idea about how to solve this issue?
I saw a good answer in https://stackoverflow.com/a/2380113/5108174
Adapting to your question:
function generate(qt, len_board) {
var arr = [];
while(arr.length < qt) {
var randomnumber = Math.floor(Math.random() * (len_board - 1)) + 1;
if(arr.indexOf(randomnumber) > -1) continue;
arr.push(randomnumber);
}
return arr;
}
var rows=generate(3,len_board);
var columns=generate(3,len_board);
window.random_row = rows[0];
window.random_column = columns[0];
window.random_row2 = rows[1];
window.random_column2 = columns[1];
window.random_row3 = rows[2];
window.random_column3 = columns[2];
Create an array of numbers from 1 .. len-board
shuffle it (sort with Math.random() < 0.5 sort function)
take the first 6.
Think of it as like shuffling a deck of cards, that you cannot pull the same card twice.
All "unique".
What about trying with a while cycle?
while(random2 == random1 || random2 == random3)
{
random2= math.....;
}
Related
I need to create a random number generator with 9 total digit created from a random 1 digit number generated thru a for loop .
This one works but i need to use a for loop for it :
var random1 = Math.floor(Math.random() * 9) + 1 ;
var random2 = Math.floor(Math.random() * 9) + 1 ;
var random3 = Math.floor(Math.random() * 9) + 1 ;
var random4 = Math.floor(Math.random() * 9) + 1 ;
var random5 = Math.floor(Math.random() * 9) + 1 ;
var random6 = Math.floor(Math.random() * 9) + 1 ;
var random7 = Math.floor(Math.random() * 9) + 1 ;
var random8 = Math.floor(Math.random() * 9) + 1 ;
var random9 = Math.floor(Math.random() * 9) + 1 ;
// ... and then dump the random number into our random-number div.
$("#random-number").text(""+ random1 + random2 + random3 + random4 + random5 + random6 + random7 + random8 + random9);
var results = ""+ random1 + random2 + random3 + random4 + random5 + random6 + random7 + random8 + random9 ;
$("#results").prepend(results + " <br>");
the above code works in creating a random 9 digit number but i need to use a for loop to make my code concise .
You can use for loop. Create a string and in each loop concentrate the new random number with that string.
let random = '';
for(let i =0;i<9;i++){
random += Math.floor(Math.random() * 9) + 1 ;
}
$("#random-number").text(random);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="random-number"></div>
Another way can be using map() and join()
let random = [...Array(9)].map(x => Math.floor(Math.random() * 9) + 1).join('')
$("#random-number").text(random);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="random-number"></div>
You can try this way with all digits is in range [0, 9] and you should relize that first digit can be zero:
var digits = [];
for (let i=0; i<9; i++) {
let n = Math.floor(Math.random()*10);
digits.push( n );
}
var number = digits.join('')
Construct a new array where the items are random numbers and then join the array with an empty string.
const random = length => Array.from(Array(length), _ => Math.floor(Math.random() * 9) + 1).join('');
console.log(random(9));
console.log(random(9));
console.log(random(9));
console.log(random(9));
console.log(random(9));
In case you want to have all the 9 number to be unique you can use a object to keep track of added previously added numbers and if it is not included add a it to random number as well as object
let random = '';
let included = {}
for(let i =0;i<9;i++){
let temp = true
while(temp){
let num = Math.floor(Math.random() * 9) + 1 ;
if(included[num] === undefined){
temp = false
random += num
included[num] = num
}
}
}
$("#random-number").text(random);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="random-number"></div>
Error detailed towards bottom of post, but before getting to that, I'll give some background info. I have the following script, which generates:
1) TWO DIFFERENT NUMBERS BETWEEN 2 & 20
var GenerateRandomNumber1to20No1 = GenerateRandomNumber1to20No1();
$('.GenerateRandomNumber1to20No1').html(GenerateRandomNumber1to20No1);
function GenerateRandomNumber1to20No2() {
var min = 2, max = 20;
var random = Math.floor(Math.random() * (max - min + 1)) + min;
return (random !== GenerateRandomNumber1to20No1) ? random: GenerateRandomNumber1to20No2();
}
var GenerateRandomNumber1to20No2 = GenerateRandomNumber1to20No2();
$('.GenerateRandomNumber1to20No2').html(GenerateRandomNumber1to20No2);
function GenerateRandomNumber1to20No3() {
var min = 2, max = 20;
var random = Math.floor(Math.random() * (max - min + 1)) + min;
return (random !== GenerateRandomNumber1to20No1 && random!==GenerateRandomNumber1to20No2) ? random: GenerateRandomNumber1to20No3();
}
2) TWO DIFFERENT NUMBERS LESS THAN THE PREVIOUS 2 NUMBERS
function GenerateRandomNumber1to20lessthanNo1() {
var min = 2, max = GenerateRandomNumber1to20No1-1;
var random = Math.floor(Math.random() * (max - min + 1)) + 1;
return random;
}
var GenerateRandomNumber1to20lessthanNo1= GenerateRandomNumber1to20lessthanNo1();
$('.GenerateRandomNumber1to20lessthanNo1').html(GenerateRandomNumber1to20lessthanNo1);
function GenerateRandomNumber1to20lessthanNo2() {
var min = 2, max = (GenerateRandomNumber1to20No2 - 1);
var random = Math.floor(Math.random() * (max - min + 1)) + min;
return (random !== GenerateRandomNumber1to20lessthanNo1) ? random: GenerateRandomNumber1to20lessthanNo2();
}
var GenerateRandomNumber1to20lessthanNo2 = GenerateRandomNumber1to20lessthanNo2();
$('.GenerateRandomNumber1to20lessthanNo2').html(GenerateRandomNumber1to20lessthanNo2);
3) 2 DIFFERENT PRIME NUMBERS
function PrimeNumber1() {
var PrimeNumber1= ['3', '5', '7', '11'];
var PrimeNumber1random= PrimeNumber1[Math.floor(Math.random() * PrimeNumber1.length)];
return PrimeNumber1random;
}
var PrimeNumber1replacer= PrimeNumber1();
$('.PrimeNumber1replacer').html(PrimeNumber1replacer);
function PrimeNumber2() {
var PrimeNumber2= ['3', '5', '7', '11'];
var PrimeNumber2random= PrimeNumber2[Math.floor(Math.random() * PrimeNumber2.length)];
return (PrimeNumber2random !== PrimeNumber1replacer) ? PrimeNumber2random: PrimeNumber2();
}
var PrimeNumber2replacer= PrimeNumber2();
$('.PrimeNumber2replacer').html(PrimeNumber2replacer);
I USE THESE VARIABLES TO REPLACE ELEMENTS WITH CORRESPONDING CLASSES WITH THE VALUES OF THE RESPECTIVE VARIABLES
<span class = "GenerateRandomNumber1to20nNo2"></span>
<span class = "GenerateRandomNumber1to20nNo2"></span>
<span class = "GenerateRandomNumber1to20lessthanNo1"></span>
<span class = "GenerateRandomNumber1to20lessthanNo2"></span>
<span class = "PrimeNumber1replacer"></span>
<span class = "PrimeNumber2replacer"></span>
Sometimes, the code works fine: the variables generate and the elements are replaced with those variables. Other times, the variables don't populate and I get one of the two following errors:
Uncaught RangeError: Maximum call stack size exceeded
at GenerateRandomNumber1to20lessthanNo2 *[or No1]*
OR
Uncaught TypeError: PrimeNumber2 *[or 1]* is not a function
at PrimeNumber2
I tried to do some research on Stackoverflow and it seems it might be an issue with recursion, but I have no idea how to fix this issue. If anyone has any advice, I would appreciate it.
Thank you!
You get a stack overflow because almost none of the JS engines are ES6 compliant yet so even though you use tail recursion you blow the stack. The best thing right now is to rewrite it into a loop that does the same until you have succeded.
function generateRandomNumber(predicate = v => true) {
const min = 2;
const max = 20;
let random;
do {
random = Math.floor(Math.random() * (max - min + 1)) + 1;
} while (!predicate(random));
return random;
}
// two different numbers
const first1 = generateRandomNumber();
const second1 = generateRandomNumber(v => v !== first1);
// two different number less than previous
const first2 = generateRandomNumber();
const second2 = generateRandomNumber(v => v < first2); // possible infinite loop
// two different prime numbers
function isPrime(n) {
if (n % 2 === 0) return n == 2
const limit = Math.sqrt(n);
for (let i = 3; i <= limit; i += 2) {
if (n % i === 0)
return false;
}
return true;
}
const first3 = generateRandomNumber(isPrime);
const second3 = generateRandomNumber(v => isPrime(v) && v !== first3);
I've left out the code that puts the values onto the DOM since it's not very interesting. I don't name the variables after the function since they share the same namespace and thus after setting the name GenerateRandomNumber1to20No1 the function has been replaced with the value.
Note that i mention the "two different number less than previous" that you might get an infinite loop. There is a 5,5% chance that the first random number is 2. There is no number generated by that same function which is smaller than 2 and thus it will not terminate.
I am trying to set a function that creates a random number between a range
I need to make it working with negative values so I can do
randomBetweenRange( 10, 20)
randomBetweenRange(-10, 10)
randomBetweenRange(-20, -10)
This is what I am trying, it is a bit confusing and at the moment randomBetweenRange(-20, -10) is not working..
function randomBetweenRange(a, b){
var neg;
var pos;
if(a < 0){
neg = Math.abs(a) + 1;
pos = (b * 2) - 1;
}else{
neg = -Math.abs(a) + 1;
var pos = b;
}
var includeZero = true;
var result;
do result = Math.ceil(Math.random() * (pos + neg)) - neg;
while (includeZero === false && result === 0);
return result;
}
How can I make it working?
ASSUMING you will always have the little value on first, this code will do the tricks, see the comment below and don't hesitate to ask !
var a=parseInt(prompt("First value"));
var b=parseInt(prompt("Second value"));
var result = 0;
// Here, b - a will get the interval for any pos+neg value.
result = Math.floor(Math.random() * (b - a)) + a;
/* First case is we got two neg value
* We make the little one pos to get the intervale
* Due to this, we use - a to set the start
*/
if(a < 0) {
if(b < 0) {
a = Math.abs(a);
result = Math.floor(Math.random() * (a + b)) - a;
}
/* Second case is we got two neg value
* We make the little one neg to get the intervale
* Due to this, we use - a to set the start
*/
} else {
if(b > 0) {
a = a*-1;
result = Math.floor(Math.random() * (a + b)) - a;
}
}
console.log("A : "+a+" | B : "+b+" | Int : "+(a+b)+"/"+Math.abs((a-b)));
console.log(result);
You have declared the variable 'pos' in the beginning itself. Then why do you declare it in the 'else' part? ( var pos = b;)
Hence, for this statement,
do result = Math.ceil(Math.random() * (pos + neg)) - neg;
'pos' will not have any value.
do result = Math.ceil(Math.random() * (pos + neg)) - neg;
Specifically Math.random() * (pos + neg) returns the wrong range. If pos = -20 and neg = -30, the range between pos and neg should be 10, but your operation returns -50. You should also add one to the range because its technically the amount of possibilities (ex: if you want to generate your function to return {0,1}, the range between pos and neg is 1, but there are two possibilities of numbers to return) and subtract another 1 from result because you're using Math.ceil
Your else clause also redeclares var pos
If you want to generate a number between -50 and 50 - Get a random number between 0 and 100 then subtract 50
var randomNumber = Math.floor(Math.random() * 101) - 50;
console.log(randomNumber);
How can I generate numbers that range from 000 to 999? Also, a single digit can only occur maximum of two times in the same number.
Examples of numbers I'd like to generate:
094
359
188
900
004
550
Examples of numbers I don't want to generate:
000
999
444
What I've got so far:
function randomNumbers () {
var one = Math.floor(Math.random() * 9) + 0;
var two = Math.floor(Math.random() * 9) + 0;
var three = Math.floor(Math.random() * 9) + 0;
return '' + one + two + three;
};
I know the code can be improved a lot, I just don't know how. Current function isn't checking if the same number occurs three times (should only occur a maximum of two).
I can use jQuery in the project.
Here is a solution that will never have to retry. It returns the result in constant time and spreads the probability evenly among the allowed numbers:
function randomNumbers () {
var val = Math.floor(Math.random() * 990);
val += Math.floor((val+110)/110);
return ('000' + val).substr(-3);
};
// Test it:
var count = new Array(1000).fill(0);
for (i=0; i<100000; i++) {
count[+randomNumbers()]++;
}
// filter out the counters that remained zero:
count = count.map((v,i) => [i,v]).filter( ([i,v]) => !v ).map( ([i,v]) => i );
console.log('numbers that have not been generated: ', count);
You could count the digits and check before return the value.
function getRandom() {
var count = {};
return [10, 10, 10].map(function (a) {
var v;
do {
v = Math.floor(Math.random() * a);
} while (count[v] && count[v] > 1)
count[v] = (count[v] || 0) + 1;
return v;
}).join('');
}
var i = 1000;
while (i--) {
console.log(getRandom());
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
Try this :
$(document).ready(function() {
for(var i=0; i<50;i++)
console.log(randomNumbers ());
function randomNumbers () {
var one = Math.floor(Math.random() * 9);
var two = Math.floor(Math.random() * 9);
var three = Math.floor(Math.random() * 9);
if( one == two && two == three && one == three )
randomNumbers();
else
return (""+one + two + three);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
The following should give you the expected result:
function getRandom() {
var randomNo = Math.floor(Math.random() * 999);
var splitted = randomNo.toString().split("");
var res = [];
splitted.filter(v => {
res.push(v);
if (res.filter(x => x == v).length > 2) return false;
return true;
});
while (splitted.length < 3) {
var ran = Math.floor(Math.random() * 9);
if (splitted.indexOf(ran) < 0) splitted.push(ran);
}
console.log(splitted.join(""))
return splitted.join("");
}
for (x = 0; x<100;x++) {getRandom()}
Keeps track of what you started.
function randomNumbers () {
var one = Math.floor(Math.random() * 10);
var two = Math.floor(Math.random() * 10);
var three = Math.floor(Math.random() * 10);
return one==two && two==three ? randomNumbers(): '' + one + two + three;
};
Here the function call itself recursively up to the point where it result
meets the requirements. The probability of generating three equal numbres is 1/100 so be sure that it will recurse nearly to never.
If, it were me, to be more flexible, I'd write a function I could pass parameters to and have it generate the numbers like the below:
function getRandoms(min, max, places, dupes, needed) {
/**
* Gets an array of random numbers with rules applied
* #param min int min Minimum digit allowed
* #param mas int min Maximum digit allowed
* #param dupes int Maximum duplicate digits to allow
* #param int needed The number of values to return
* #return array Array of random numbers
*/
var vals = [];
while (vals.length < needed) {
var randomNum = Math.floor(Math.random() * max) + min;
var digits = randomNum.toString().split('');
while (digits.length < places) {
digits.push(0);
}
var uniqueDigits = digits.removeDupes();
if ((places - uniqueDigits.length) <= dupes) vals.push(digits.join(''));
}
return vals;
}
// for convenience
Array.prototype.removeDupes = function() {
/**
* Removes duplicate from an array and returns the modified array
* #param array this The original array
* #return array The modified array
*/
var unique = [];
$.each(this, function(i, item) {
if ($.inArray(item, unique)===-1) unique.push(item);
});
return unique;
}
var randomNumbers = getRandoms(0, 999, 3, 2, 10);
console.log(randomNumbers);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I'm generating a random number with the code below:
Math.floor((Math.random() * 9999) * 7);
Some of the results I'm getting:
45130,
2611,
34509,
36658
How would I get results like this(with 2 letters included):
TT45130,
PO2611,
KL34509,
GH36658
Side question:
What is the range of numbers that Math.random() carries? Can I set a specific range of values? Not necessary to answer but just curious.
You can use a function like below to get a random uppercase character:
function getRandomUppercaseChar() {
var r = Math.floor(Math.random() * 26);
return String.fromCharCode(65 + r);
}
So to generate a code as you specified with a two-letter prefix:
function generateCode() {
var prefix = new Array(2).fill().map(() => getRandomUppercaseChar()).join(""),
integer = Math.floor((Math.random() * 9999) * 7);
return prefix + integer;
}
NOTE: The above generateCode function uses modern ES6 and ES5 javascript, which is perfectly fine in a modern environment (such as Node.js or a current browser). However, if you wanted greater compatibility (for example, to ensure that it works in old browsers), you could rewrite it like so:
function generateCode() {
var integer = Math.floor((Math.random() * 9999) * 7);
for (var i = 0, prefix = ""; i < 2; ++i)
prefix += getRandomUppercaseChar();
return prefix + integer;
}
Try the simpler answer
var randomNumber = function () {
return Math.floor((Math.random() * 9999) * 7);
}
var randomChar = function () {
return String.fromCharCode(64 + Math.floor((Math.random() * 26)+1));
}
console.log(randomChar()+randomChar()+randomNumber());
//Sample outputs
HB10527 DR25496 IJ12394
Or you can use Number#toString for this purpose with radix = 36.
function getRChar() {
return (Math.random() * 26 + 10 | 0).toString(36).toUpperCase();
}
var s = getRChar() + getRChar() + Math.floor((Math.random() * 9999) * 7);
document.write(s);
If you need to generate a random string with JS, the most common way is to define an alphabet and pick random indices from that:
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var numbers = "0123456789";
var randomString = "";
// Pick two random chars
for (var i = 0; i < 2; i++) {
var rand = Math.floor(Math.random()*alphabet.length);
randomString = randomString + alphabet.charAt(rand);
}
// Pick four random digits
for (var i = 0; i < 4; i++) {
var rand = Math.floor(Math.random()*numbers.length);
randomString = randomString + numbers.charAt(rand);
}
// randomString now contains the string you want
Sample strings:
OJ8225
YL5053
BD7911
ES0159
You could use String.fromCharCode() with a random integer between 65 and 90 to get an uppercase letter, i.e.
String.fromCharCode(Math.random() * 26 + 65) + String.fromCharCode(Math.random() * 26 + 65) + Math.floor((Math.random() * 9999) * 7);
gives med the results: "SH21248", "BY42401", "TD35918".
If you want to guarantee that the string always has the same length, you could also use
String.fromCharCode(Math.random() * 26 + 65) + String.fromCharCode(Math.random() * 26 + 65) + Math.floor(Math.random() * 59993 + 10000);
Math.random() always returns a number between 0 and 1, but never 0 or 1 exactly.
An array of the alphabet, a random number is generated to get a random letter, repeated to get a second random letter and then joined to the random number generated as in your code:
var alphabet=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
var ranletter1 = alphabet[Math.floor(Math.random() * alphabet.length)];
var ranletter2 = alphabet[Math.floor(Math.random() * alphabet.length)];
var ranNum = Math.floor((Math.random() * 9999) * 7);
var ranCode = ranletter1 + ranletter2+ ranNum;