control random number with javascript - javascript
This is my intent,
Generate random number
Store in variable
Clear variable
Generate new number greater than previous
Store in variable
I understand
(Math.floor(Math.random()*100)+1)
For 1-100 but not sure how to accomplish what I want exactly.
The following will generate a random number and then find the next random number it finds that is greater than it (or equal to it if it is greater than or equal to 99):
var num = Math.floor(Math.random()*100)+1;
alert(num); //current number
var newNum;
while((newNum = Math.floor(Math.random()*100)+1) < num && newNum < 100);
alert(newNum); //new number > num (or == num if num >= 99)
use
var ran_val = 1;
// ... some code goes here
ran_val = (Math.floor(Math.random()*100) + ran_val)
if you have no upper limit on the random numbers,
ran_val = (Math.floor(Math.random()*(100-ran_val)) + ran_val)
otherwise.
fwiw, the random numbers you emulate this way are no longer uniformly distributed.
var numb1 = Math.floor(Math.random()*100)+1, //Generate random number
numb2 = 0;
while (numb2<numb1) {
numb2 = Math.floor(Math.random()*100)+2; // Generate new number greater than previous
}
FIDDLE
You need to have a global variable and a function that handles the random number generation.
You can do something like this:
var num = 1;
function generaterandom(){
num = Math.floor(Math.random()*100)+num;
}
Related
prevent rendering to page of duplicate random number generated when min and max are user defined [duplicate]
I ran into the challenge where I need a function that returns a random number within a given range from 0 - X. Not only that, but I require the number returned to be unique; not duplicating numbers that have already been returned on previous calls to the function. Optionally, when this is done (e.g. the range has been 'exhausted'), just return a random number within the range. How would one go about doing this?
This should do it: function makeRandomRange(x) { var used = new Array(x), exhausted = false; return function getRandom() { var random = Math.floor(Math.random() * x); if (exhausted) { return random; } else { for (var i=0; i<x; i++) { random = (random + 1) % x; if (random in used) continue; used[random] = true; return random; } // no free place found exhausted = true; used = null; // free memory return random; } }; } Usage: var generate = makeRandomRange(20); var x1 = generate(), x2 = generate(), ... Although it works, it has no good performance when the x-th random is generated - it searches the whole list for a free place. This algorithm, a step-by-step Fisher–Yates shuffle, from the question Unique (non-repeating) random numbers in O(1)?, will perform better: function makeRandomRange(x) { var range = new Array(x), pointer = x; return function getRandom() { pointer = (pointer-1+x) % x; var random = Math.floor(Math.random() * pointer); var num = (random in range) ? range[random] : random; range[random] = (pointer in range) ? range[pointer] : pointer; return range[pointer] = num; }; } (Demo at jsfiddle.net) Extended version which does only generate one "group" of unique numbers: function makeRandomRange(x) { var range = new Array(x), pointer = x; return function getRandom() { if (range) { pointer--; var random = Math.floor(Math.random() * pointer); var num = (random in range) ? range[random] : random; range[random] = (pointer in range) ? range[pointer] : pointer; range[pointer] = num; if (pointer <= 0) { // first x numbers had been unique range = null; // free memory; } return num; } else { return Math.floor(Math.random() * x); } }; } (Demo)
You got some great programming answer. Here's one with a more theoretical flavor to complete your panorama :-) Your problem is called "sampling" or "subset sampling" and there are several ways you could do this. Let N be the range you are sampling frame (i.e., N=X+1) and M be the size of your sample (the number of elements you want to pick). if N is much larger than M, you'll want to use an algorithm such as the one suggested by Bentley and Floyd in his column "Programming Pearls: a sample of brilliance" (temporarily available without ACM's lock screen here), I really recommend this as they explicitly give code and discuss in terms of hash tables, etc.; there a few neat tricks in there if N is within the same range as M, then you might want to use the Fisher-Yates shuffle but stop after only M steps (instead of N) if you don't really know then the algorithm on page 647 of Devroye's book on random generation is pretty fast.
I wrote this function. It keeps its own array with a history of generated numbers, preventing initial duplicates, continuing to output a random number if all numbers in the range have been outputted once: // Generates a unique number from a range // keeps track of generated numbers in a history array // if all numbers in the range have been returned once, keep outputting random numbers within the range var UniqueRandom = { NumHistory: new Array(), generate: function(maxNum) { var current = Math.round(Math.random()*(maxNum-1)); if (maxNum > 1 && this.NumHistory.length > 0) { if (this.NumHistory.length != maxNum) { while($.inArray(current, this.NumHistory) != -1) { current = Math.round(Math.random()*(maxNum-1)); } this.NumHistory.push(current); return current; } else { //unique numbers done, continue outputting random numbers, or we could reset the history array (NumHistory = [];) return current; } } else { //first time only this.NumHistory.push(current); return current; } } }; Here's a working Fiddle I hope this is of use to someone! Edit: as pointed out by Pointy below, it might get slow with a large range (here is a fiddle, going over a range from 0-1000, which seems to run fine). However; I didn't require a very large range, so perhaps this function is indeed not suited if you look to generate and keep track of an enormous range.
You may try generating the number using the current date and time value which would make it unique. To make it within the range, you may have to use some mathematical function.
Randomize multiple integers to equal variable
Using JavaScript, how would I go about generating 30 random integers and have the sum of those 30 integers be 60000? I need the script to produce a different set of numbers each time it is run, making sure that the total is always 60000 var n = 30; var total = 60000; var min = 10; var max = 5000; for (i = 0; i < n; i++) { // Math.floor(Math.random()*(max-min+1)+min); ?? } In order to avoid excessively large and small numbers, the min and max values will likely be needed
You can try something like this: Logic Accept Max total and total number of resulting Numbers. Now loop based on this number - 1 for n-1 random numbers and last value should be max - currentSum. Since rest of numbers are random, this difference will also be random and this will also ensure total being equal. Now all you need to do is return a random number based on a given range. I have also added a flag to check for unique values. Currently I have just added 1 to it but this will not ensure its uniqueness, but as its out of scope, not rectifying it. Code function getRandomInRange(max) { var raiseVal = Math.pow(10, (max.toString().length - 1) || 1); return Math.floor(Math.random() * raiseVal) % max; } function getRandomNumbers(max, n, uniqueNum) { var nums = []; var sum = 0; for (var i = 0; i < n - 1; i++) { let r = getRandomInRange(max - sum); if(uniqueNum && nums.indexOf(r) > -1){ r += 1; } nums.push(r) sum += r; } nums.push(max - sum); console.log(nums) return nums } getRandomNumbers(3, 3, true) getRandomNumbers(3, 3) getRandomNumbers(1000, 10) getRandomNumbers(600000, 30)
Pick random combination from 194481 possibilities
I have a file of 194481 permutations for 0,1,2,3,4,5,6,...,21 which looks like this; [0,0,0,0],[0,0,0,1],[0,0,0,2],[0,0,0,3],[0,0,0,4],[0,0,0,5],[0,0,0,6],[0,0,0,7],[0,0,0,8],[0,0,0,9],[0,0,0,10],[0,0,0,11],[0,0,0,12],[0,0,0,13],[0,0,0,14],[0,0,0,15],[0,0,0,16],[0,0,0,17],[0,0,0,18],[0,0,0,19],[0,0,0,20],[0,0,1,0],[0,0,1,1],[0,0,1,2],[0,0,1,3],[0,0,1,4],[0,0,1,5],[0,0,1,6],[0,0,1,7],[0,0,1,8],[0,0,1,9],[0,0,1,10],[0,0,1,11],[0,0,1,12],[0,0,1,13],[0,0,1,14],[0,0,1,15],[0,0,1,16],[0,0,1,17],[0,0,1,18],[0,0,1,19],[0,0,1,20],[0,0,2,0],[0,0,2,1],[0,0,2,2],[0,0,2,3],[0,0,2,4],[0,0,2,5],[0,0,2,6],[0,0,2,7],[0,0,2,8],[0,0,2,9],[0,0,2,10],[0,0,2,11],[0,0,2,12],[0,0,2,13],[0,0,2,14],[0,0,2,15],[0,0,2,16],[0,0,2,17],[0,0,2,18],[0,0,2,19],[0,0,2,20],[0,0,3,0],[0,0,3,1],[0,0,3,2],[0,0,3,3],[0,0,3,4],[0,0,3,5],[0,0,3,6],[0,0,3,7],[0,0,3,8],[0,0,3,9],[0,0,3,10],[0,0,3,11],[0,0,3,12],[0,0,3,13],[0,0,3,14],[0,0,3,15],[0,0,3,16],[0,0,3,17],[0,0,3,18],[0,0,3,19],[0,0,3,20],[0,0,4,0],[0,0,4,1],[0,0,4,2],[0,0,4,3],[0,0,4,4],[0,0,4,5],[0,0,4,6],[0,0,4,7],[0,0,4,8],[0,0,4,9],[0,0,4,10],[0,0,4,11],[0,0,4,12],[0,0,4,13],[0,0,4,14],[0,0,4,15],[0,0,4,16],[0,0,4,17],[0,0,4,18],[0,0,4,19],[0,0,4,20],[0,0,5,0],[0,0,5,1],[0,0,5,2],[0,0,5,3],[0,0,5,4],[0,0,5,5],[0,0,5,6],[0,0,5,7],[0,0,5,8],[0,0,5,9],[0,0,5,10],[0,0,5,11],[0,0,5,12],[0,0,5,13],[0,0,5,14],[0,0,5,15],[0,0,5,16],[0,0,5,17],[0,0,5,18],[0,0,5,19],[0,0,5,20],[0,0,6,0],[0,0,6,1],[0,0,6,2],[0,0,6,3],[0,0,6,4],[0,0,6,5],[0,0,6,6],[0,0,6,7],[0,0,6,8],[0,0,6,9],[0,0,6,10],[0,0,6,11],[0,0,6,12],[0,0,6,13],[0,0,6,14],[0,0,6,15],[0,0,6,16],[0,0,6,17],[0,0,6,18],[0,0,6,19],[0,0,6,20],[0,0,7,0],[0,0,7,1],[0,0,7,2],[0,0,7,3],[0,0,7,4],[0,0,7,5],[0,0,7,6],[0,0,7,7],[0,0,7,8],[0,0,7,9],[0,0,7,10],[0,0,7,11],[0,0,7,12],[0,0,7,13],[0,0,7,14],[0,0,7,15],[0,0,7,16],[0,0,7,17],[0,0,7,18],[0,0,7,19],[0,0,7,20],[0,0,8,0],[0,0,8,1],[0,0,8,2],[0,0,8,3],[0,0,8,4],[0,0,8,5],[0,0,8,6],[0,0,8,7],[0,0,8,8],[0,0,8,9],[0,0,8,10],[0,0,8,11],[0,0,8,12],[0,0,8,13],[0,0,8,14],[0,0,8,15],[0,0,8,16],[0,0,8,17],[0,0,8,18],[0,0,8,19],[0,0,8,20],[0,0,9,0],[0,0,9,1],[0,0,9,2],[0,0,9,3],[0,0,9,4],[0,0,9,5],[0,0,9,6],[0,0,9,7],[0,0,9,8],[0,0,9,9],[0,0,9,10],[0,0,9,11],[0,0,9,12],[0,0,9,13],[0,0,9,14],[0,0,9,15],[0,0,9,16],[0,0,9,17],[0,0,9,18],[0,0,9,19],[0,0,9,20],[0,0,10,0],[0,0,10,1],[0,0,10,2],[0,0,10,3],[0,0,10,4],[0,0,10,5],[0,0,10,6],[0,0,10,7],[0,0,10,8],[0,0,10,9],[0,0,10,10],[0,0,10,11],[0,0,10,12],[0,0,10,13],[0,0,10,14],[0,0,10,15],[0,0,10,16],[0,0,10,17],[0,0,10,18],[0,0,10,19],[0,0,10,20],[0,0,11,0],[0,0,11,1],[0,0,11,2],[0,0,11,3],[0,0,11,4],[0,0,11,5],[0,0,11,6],[0,0,11,7],[0,0,11,8],[0,0,11,9],[0,0,11,10],[0,0,11,11],[0,0,11,12],[0,0,11,13],[0,0,11,14],[0,0,11,15],[0,0,11,16],[0,0,11,17],[0,0,11,18],[0,0,11,19],[0,0,11,20],[0,0,12,0],[0,0,12,1],[0,0,12,2],[0,0,12,3],[0,0,12,4],[0,0,12,5],[0,0,12,6],[0,0,12,7],[0,0,12,8],[0,0,12,9],[0,0,12,10],[0,0,12,11],[0,0,12,12],[0,0,12,13],[0,0,12,14],[0,0,12,15],[0,0,12,16],[0,0,12,17],[0,0,12,18],[0,0,12,19],[0,0,12,20],[0,0,13,0],[0,0,13,1],[0,0,13,2],[0,0,13,3],[0,0,13,4],[0,0,13,5],[0,0,13,6],[0,0,13,7],[0,0,13,8],[0,0,13,9],[0,0,13,10],[0,0,13,11],[0,0,13,12],[0,0,13,13],[0,0,13,14],[0,0,13,15],[0,0,13,16],[0,0,13,17],[0,0,13,18],[0,0,13,19],[0,0,13,20],[0,0,14,0],[0,0,14,1],[0,0,14,2],[0,0,14,3],[0,0,14,4],[0,0,14,5],[0,0,14,6],[0,0,14,7],[0,0,14,8],[0,0,14,9],[0,0,14,10],[0,0,14,11],[0,0,14,12],[0,0,14,13],[0,0,14,14],[0,0,14,15],[0,0,14,16],[0,0,14,17],[0,0,14,18],[0,0,14,19],[0,0,14,20],[0,0,15,0],[0,0,15,1],[0,0,15,2],[0,0,15,3],[0,0,15,4],[0,0,15,5],[0,0,15,6],[0,0,15,7],[0,0,15,8],[0,0,15,9],[0,0,15,10],[0,0,15,11],[0,0,15,12],[0,0,15,13],[0,0,15,14],[0,0,15,15],[0,0,15,16],[0,0,15,17],[0,0,15,18],[0,0,15,19],[0,0,15,20],[0,0,16,0],[0,0,16,1],[0,0,16,2],[0,0,16,3],[0,0,16,4],[0,0,16,5],[0,0,16,6],[0,0,16,7],[0,0,16,8],[0,0,16,9],[0,0,16,10],[0,0,16,11],[0,0,16,12],[0,0,16,13],[0,0,16,14],[0,0,16,15],[0,0,16,16],[0,0,16,17],[0,0,16,18],[0,0,16,19],[0,0,16,20],[0,0,17,0],[0,0,17,1],[0,0,17,2],[0,0,17,3],[0,0,17,4],[0,0,17,5],[0,0,17,6],[0,0,17,7],[0,0,17,8],[0,0,17,9],[0,0,17,10],[0,0,17,11],[0,0,17,12],[0,0,17,13],[0,0,17,14],[0,0,17,15],[0,0,17,16],[0,0,17,17]... etc. It ends at [20,20,20,20]. I need to pick 50 combinations from the file and assign it to a variable so it would be like var combinationsArr = [ [0,0,17,9],[0,0,17,10],[0,0,17,11],[0,0,17,12] ]; //BUT 50 of them it's okay if it is just in order like [0,0,0,0],[0,0,0,1],[0,0,0,2],[0,0,0,3],[0,0,0,4],[0,0,0,5],[0,0,0,6],[0,0,0,7],[0,0,0,8],[0,0,0,9],[0,0,0,10],[0,0,0,11],[0,0,0,12] and doesn't have to be super random like [1,2,3,4],[9,12,13,15],[20,12,6,7] as long as it is able to pick 50 of them. I am doing this because 194481 combinations are a lot and makes my program carsh. so I just decided i'll put it in a text file and pick random points from the text file like from [0,0,0,1] to [0,0,0,50] OR from [0,1,0,0] to [0,1,0,49] if that's possible. because i have to generate a random combination. I have another array of combinations which are not supposed to be generated. Let's call it notAllowedArr. var notAllowedArr = [ [0,0,17,9],[0,0,17,12] ]; I am thinking, i'll just generate 50 combinations and remove the ones listed in notAllowedArr then pick one from combinationsArr as the final result. I will still have to find code to remove those from combinationsArr but the result should be like. var combinationsArr = [[0,0,17,10],[0,0,17,11]]; then i'll have a code to pick a random value from combinationsArr. example. combinationsArr[0]. so the final result would be; [0,0,17,10] Does anyone have a better solution?
If I understand correctly, you need to pick one random combination, which is not present in a list of forbidden combinations. You can consider a combination of four numbers from 0 to 20 as a number from 0 to 194480 in base-21 notation. So instead of having to store all combinations in a file, we just pick a random number and convert it to base-21. To choose a random number in a range where some values are forbidden, choose a number in the range from 0 to the maximum minus the number of forbidden values; then iterate over the forbidden values from small to large, and increment the random number every time you find a smaller or equal forbidden value. This will make sure that every combination has the same probability of being chosen, and avoids the possibility of repeatedly choosing a forbidden combination. function randomBase21(skip) { var dec = [], result = [], num; // CONVERT FORBIDDEN COMBINATIONS FROM BASE-21 TO DECIMAL AND SORT for (var i = 0; i < skip.length; i++) { dec[i] = skip[i][0] * 9261 + skip[i][1] * 441 + skip[i][2] * 21 + skip[i][3]; } dec.sort(function(a, b){return a - b}); // GENERATE RANDOM NUMBER FROM 0 TO MAX - NUMBER OF FORBIDDEN COMBINATIONS num = Math.floor(Math.random() * (194481 - skip.length)); // INCREMENT RANDOM NUMBER FOR EVERY SMALLER FORBIDDEN COMBINATION for (var i = 0; i < skip.length && num >= dec[i]; i++) { ++num; } // CONVERT RANDOM NUMBER TO FOUR BASE-21 DIGITS for (var i = 3; i >= 0; i--, num /= 21) { result[i] = Math.floor(num % 21); } return result; } var notAllowed = [[0,0,17,9],[0,0,17,12],[20,19,17,12],[15,16,17,12]]; document.write(randomBase21(notAllowed));
Something like this should work (off the top of my head and not tested/debugged): var samples = new Array(); for(var index = 0; index < 50; index++) { samples.push(generatePermutation()); } function generatePermutation() { var result = [Math.floor(Math.random() * 20) + 1, Math.floor(Math.random() * 20) + 1, Math.floor(Math.random() * 20) + 1, Math.floor(Math.random() * 20) + 1]; }
I just thought of a better way. I think I will make a function that generates a random combination. Then check if it exists in notAllowedArr. If it exists, it will generate another one. If not then that will return that combination :D I think this will work faster ^^;
Spliting the binary string in half
I am trying to split binary number in half and then just add 4 zeroes. For example for 10111101 I want to end up with only the first half of the number and make the rest of the number zeroes. What I want to end up would be 10110000. Can you help me with this?
Use substring to split and then looping to pad var str = '10111101'; var output = str.substring( 0, str.length/2 ); for ( var counter = 0; counter < str.length/2; counter++ ) { output += "0"; } alert(output)
try this (one-liner) var binary_str = '10111101'; var padded_binary = binary_str.slice(0, binary_str.length/2) + new Array(binary_str.length/2+1).join('0'); console.log([binary_str,padded_binary]); sample output ['10111101','10110000']
I guess you are using JavaScript... "10111101".substr(0, 4) + "0000";
It's a bit unclear if you are trying to operate on numbers or strings. The answers already given do a good job of showing how to operate on a strings. If you want to operate with numbers only, you can do something like: // count the number of leading 0s in a 32-bit word function nlz32 (word) { var count; for (count = 0; count < 32; count ++) { if (word & (1 << (31 - count))) { break; } } return count; } function zeroBottomHalf (num) { var digits = 32 - nlz32(num); // count # of digits in num var half = Math.floor(digits / 2);// how many to set to 0 var lowerMask = (1 << half) - 1; //mask for lower bits: 0b00001111 var upperMask = ~lowerMask //mask for upper bits: 0b11110000 return num & upperMask; } var before = 0b10111101; var after = zeroBottomHalf(before); console.log('before = ', before.toString(2)); // outputs: 10111101 console.log('after = ', after.toString(2)); // outputs: 10110000 In practice, it is probably simplest to covert your number to a string with num.toString(2), then operate on it like a string as in one of the other answers. At the end you can convert back to a number with parseInt(str, 2)
If you have a real number, not string, then just use binary arithmetic. Assuming your number is always 8 binary digits long - your question is kinda vague on that - it'd be simply: console.log((0b10111101 & 0b11110000).toString(2)) // 10110000
Random number with fixed length
I want to generate a random integer number with 0-9 numbers and with length = 5. I try this: function genRand(min,max) { for (var i = 1; i <= 5; i++) { var range = max - min + 1; return Math.floor(Math.random()*range) + min; } } and call: genRand(0,9); But it always returns 1 number, not 5 ( Help please!
function genRand() { return Math.floor(Math.random()*89999+10000); }
return exits the function on the first loop.
The smallest 5 digit number is 10000, the largest is 99999, or 10000+89999. Return a random number between 0 and 89999, and add it to the minimum. var ran5=10000+Math.round(Math.floor()*90000) Math.floor rounds down, and Math.random is greater than or equal to 0 and less than 1.
Here's a more generalized version of Nate B's answer: function rand(digits) { return Math.floor(Math.random()*parseInt('8' + '9'.repeat(digits-1))+parseInt('1' + '0'.repeat(digits-1))); }
To get a 5 digit random number generate random numbers between the range (10000, 99999). Or generate randomly 5 single digits and paste them. EDIT The process you have shown simply will generate one number and return to the caller. The think which might work is (pseudo code) : int sum = 0; int m = 1; for (i=0;i<5;i++) { sum = sum + m * random (0, 9); /* or */ sum = sum * m + random (0, 9); m = m * 10; } Or better generate 5 digit random numbers with rand (10000, 99999)