Node.js is trolling me. Generating random names and tweets using arrays - javascript
This question involves a snippet of code which is supposed to generate random tweets. However, I don't understand line by line what is happening; especially with the
Math.floor(Math.random() * arr.length)
My guess is that it picks a random array length, which is truncated to the lowest integer and then assigned as the array length of randArrayEl[].
However, I don't understand how it selects random first and last names with the following:
return randArrayEl(fakeFirsts) + " " + randArrayEl(fakeLasts);
Here's the whole code. Can anyone explain the logic of each line?
var randArrayEl = function(arr)
{
return arr[Math.floor(Math.random() * arr.length)];
};
var getFakeName = function()
{
var fakeFirsts = ['Nimit', 'Dave', 'Will', 'Charlotte', 'Jacob','Ethan','Sophia','Emma','Madison'];
var fakeLasts = ["Alley", 'Stacky', 'Fullstackerson', 'Nerd', 'Ashby', 'Gatsby', 'Hazelnut', 'Cookie', 'Tilde', 'Dash'];
return randArrayEl(fakeFirsts) + " " + randArrayEl(fakeLasts);
};
var getFakeTweet = function()
{
var awesome_adj = ['awesome','breathtaking','amazing','sexy','sweet','cool','wonderful','mindblowing'];
return "Fullstack Academy is " + randArrayEl(awesome_adj) + "! The instructors are just so " + randArrayEl(awesome_adj) + ". #fullstacklove #codedreams";
};
for(var i=0; i<10; i++)
{
store.push(getFakeName(), getFakeTweet());
}
Also, what is the for loop at the end supposed to do?
randArrayEl returns a random element from the array. It does this by picking a random integer between 0 and arr.length-1 (because Math.random() never returns exactly 1), and returning that element from the array.
So randArrayEl(fakeFirsts) returns a random name from the fakeFirsts array, and likewise for randArrayEl(fakeLasts). Concatenate them with a space and you have a random first and last name combo!
getFakeTweet works in a similar way with randArrayEl(awesome_adj) to describe Fullstack Academy.
Finally, the for loop puts 10 random tweets and associated random names in the store array.
randArrayEl picks a single random item from the array.
Take a look at the line from inside towards outside:
Math.random() gives you a random number between 0 and 1;
Math.random() * arr.length gives you a random number from 0 to n,
where n is the number of items in that array; but it's not a whole
number/integer;
Math.floor(Math.random() * arr.length) gives you a rounded integer
number from 0 to n;
arr[Math.floor(Math.random() * arr.length)] gives you the text that
corresponds to that number.
The for loop at the end puts a fake name and a fake tweet into the "store" and repeats it 10 times.
In the line
Math.floor(Math.random() * arr.length)
Math.random() returns a floating point number x in the range 0 <= x < 1. Multiplying that by arr.length gives you a floating point number in the range 0 <= x < arr.length. Taking math.Floor of that removes the fractional part, so you are left with an integer n in the range 0 <= n <= arr.length-1.
If you now access array[n], for some random n, you will get a random string from the array of strings. So the line
return randArrayEl(fakeFirsts) + " " + randArrayEl(fakeLasts);
returns a random first name from fakeFirsts concatenated with a random second name chosen from fakeLasts (separated by a space).
Related
Why does it take so many attempts to generate a random value between 1 and 10000?
I have the following code that generates an initial random number between 1 and 10000, then repeatedly generates a second random number until it matches the first: let upper = 10000; let randomNumber = getRandomNumber(upper); let guess; let attempt = 0; function getRandomNumber(upper) { return Math.floor(Math.random() * upper) + 1; } while (guess !== randomNumber) { guess = getRandomNumber(upper); attempt += 1; } document.write('The randomNumber is ' + randomNumber); document.write(' it took' + attempt); I am confused at (attempt) variables. Why is it that the computer took this many attempts to get the randomNumber? Also, it didn't put attempt in the loop condition.
Just to give you a start. This is what your code does: // define the maximum of randomly generated number. range = 0 - 10.000 let upper = 10000; // generate a random number out of the range 0-10.000 let randomNumber = getRandomNumber(upper); // predefine variable guess let guess; // set a counter to 0 let attempt = 0; // generate and return a random number out of the range from 0 to `upper` function getRandomNumber(upper) { return Math.floor(Math.random() * upper) + 1; } // loop until guess equals randomNumber while (guess !== randomNumber) { // generate a new random number and assign it to the variable guess guess = getRandomNumber(upper); // increase the counter by 1 attempt += 1; } // output the initially generated number document.write('The randomNumber is ' + randomNumber); // output the number of repetitions document.write(' it took' + attempt); So, once again. You generate a random number at start. And then you repeat generating another random number until this second random number matches the first. As you don't set any limits e.g. "each random number can only appear once" or "no more than 10.000 tries" your program might need millions of tries until the number matches, because you have a range of 10.000 possible numbers and they might repeat a hundreds of times each before the match is finally there. Try to optimize your program by limiting the number of tries to 10.000. And you could your computer just let count upwards from 0 to 10.000 instead of guessing with a randomly generated number.
When I repeatedly run your snippet, I am seeing your code take anywhere from a few thousand to a few tens of thousands of repetitions to get a given value for a random number sampled between 1 and 10000. But this is not surprising -- it is expected. Assuming your getRandomNumber(upper) function does indeed return a number between 1 and upper with a uniform distribution, the expected probability that the number returned will not be the initial, given value randomNumber is: 1 - (1/upper) And the chance that the first N generated numbers will not include the given value is: (1 - (1/upper)) ^ N And so the chance P that the first N generated numbers will include given value is: P = 1 - (1 - (1/upper)) ^ N Thus the following formula gives the number of repetitions you will need to make to generate your initial value with a given probability P: N = ln(1.0 - P) / ln(1.0 - (1.0/upper)) Using this formula, there is only a 50% chance of getting randomValue after 6932 repetitions, and a 95% chance after 29956 repetitions. let upper = 10000; function numberOfRepetitionsToGetValueWithRequiredProbability(upper, P) { return Math.ceil(Math.log(1.0 - P) / Math.log(1.0 - (1.0/upper))) } function printNumberOfRepetitionsToGetValueWithRequiredProbability(upper, P) { document.write('The number of tries to get a given value between 1 and ' + upper + ' with a ' + P + ' probability: ' + numberOfRepetitionsToGetValueWithRequiredProbability(upper, P) + ".<br>"); } var probabilities = [0.10, 0.20, 0.30, 0.40, 0.50, 0.60, 0.70, 0.80, 0.90, 0.95, 0.99, 0.9999]; probabilities.forEach((p) => printNumberOfRepetitionsToGetValueWithRequiredProbability(upper, p)); This is entirely consistent with the observed behavior of your code. And of course, assuming Math.random() is truly random (which it isn't, it's only pseudorandom, according to the docs) there is always going to be a vanishingly small probability of never encountering your initial value no matter how many repetitions you make.
Math.random to never generate same number as other Math.random [duplicate]
This question already has answers here: How to get a number of random elements from an array? (25 answers) Closed 4 years ago. I got 4 Math.random generators. Each picking 1 of the X objects from the array. var randomItem1 = projects[Math.floor(Math.random()*projects.length)]; var randomItem2 = projects[Math.floor(Math.random()*projects.length)]; var randomItem3 = projects[Math.floor(Math.random()*projects.length)]; var randomItem4 = projects[Math.floor(Math.random()*projects.length)]; How can I write a function that prevents the Math.random to generate the same number as other Math.random generator. My guess: Creating a loop that loops through the var randomItem 1 till 4. If it finds 1 or more outputs to be the same, it will regenerate a new output for 1 or more the duplicated outputs. Any other suggestions? Edit: This is for a website.
Thanks for the interesting problem. I always used a library for this sort of thing so it was fun figuring it out. var projects var randomProjects function getRandomProjects(projects, sampleSize) { var projectsClone = projects.slice(); var randomItems = []; while (sampleSize--) { randomItems.push( projectsClone.splice(Math.floor(Math.random()*projectsClone.length), 1)[0] ); } return randomItems; } projects = ['1st project', '2nd project', '3rd project', '4th project', '5th project', '6th project']; randomProjects = getRandomProjects(projects, 4); randomProjects.forEach(function(randomProject) { console.log(randomProject); }); The projectsClone.splice(...) deletes a random project from projectsClone and returns it as a single item in an array ([<project>]). Thus in the next iteration of the loop that value (<project>) can no longer be chosen. However I would suggest using a library if you are using this in production code. For example losdash's _.sampleSize(projects, 4)
Update Removed unneeded parts like Set, for loop, and added splice(). This function will mutate the original array due to splice(). Using splice() on an array of consecutive ordered numbers (even after shuffling) guarantees a set of unique numbers. /** * genRan(quantity, length) * * Need a given amount of unique random numbers. * * Given a number for how many random numbers are to be returned (#quantity) and a * number that represents the range of consecutive numbers to extract the random * numbers from (#length), this function will: * - generate a full array of numbers with the length of #length * - use shuffle() to shuffle the array to provide an array of randomly ordered numbers * - splices the first #quantity numbers of the shuffled array * - returns new array of unique random numbers * * #param {Number} quantity length of returned array. * #param {Number} length length of an array of numbers. * * #return {Array} An array of unique random numbers. */ Demo Details commented in Demo var qty = 4 var len = 100; function genRan(quantity, length) { // Ensure that quantity is never greater than length if (quantity > length) { quantity = length; } // Create an array of consecutive numbers from 1 to N var array = Array.from({ length: length }, (value, key = 0) => key + 1); // Run shuffle get the returned shuffled array var shuffled = shuffle(array); // return an array of N (quantity) random numbers return shuffled.splice(0, quantity); } console.log(genRan(qty, len)); /* shuffle utility || Uses Fisher-Yates algorithm */ function shuffle(array) { var i = 0; var j = 0; var temp = null; for (i = array.length - 1; i > 0; i -= 1) { j = Math.floor(Math.random() * (i + 1)) temp = array[i]; array[i] = array[j]; array[j] = temp; } return array; }
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 ^^;
Writing a function in javascript that is the inverse of another
I'm trying to write a function that is the inverse of the function below. So that I can get the output from the function foo and generate it's input parameter. I'm not entirely sure if it's possible. function foo(str){ var hexMap = { "0":0, "1":1, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9, "A":10, "B":11, "C":12, "D":13, "E":14, "F":15 }; var charList = []; str = str.toUpperCase(); for (var i = 0; i < str.length; i += 2) { charList.push(hexMap[str.charAt(i)] * 16 + hexMap[str.charAt(i + 1)]); } charList.splice(0, 8); charList.splice(0, 123); var sliceEnd = charList[0] + charList[1] * 256; charList.splice(0, 4); charList = charList.slice(0, sliceEnd); return charList; }
Your function takes in a string that is hopefully a hexadecimal string using only the characters [0-9a-fA-F]. Then it makes an array where every two hex characters are converted to a decimal integer between 0 and 255. Then the function immediately throws away the first 131 elements from this array. This means that the first 262 characters on your string have no impact on the output of the function (The first 262 characters can be any characters). Then there is this line: var sliceEnd = charList[0] + charList[1] * 256; sliceEnd becomes a number between 0 and 65535 (the maximum size of the resulting array). Based on the characters at indices 262 - 265 in the input string. (Two two digit hex values converted to two integers. The value at position 264 is multiplied by 256 and added to the value at position 262). Then the resulting array contains the integers converted using the same method from the characters from position 270 to 270 + sliceEnd*2. MSN is correct that this function is not 1 to 1 and therefore not mathematically invertible, but you can write a function which given an array of less than 65536 integers between 0 and 255 can generate an input string for foo which will give back that array. Specifically the following function will do just that: function bar(arr){ var sliceEnd = arr.length; var temp = '00' + (sliceEnd & 255).toString(16); var first = temp.substring(temp.length - 2); temp = '00' + Math.floor(sliceEnd/256).toString(16); var second = temp.substring(temp.length - 2); var str = '0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' + first + second + '0000'; for(var i = 0; i < arr.length; i++){ temp = '00' + arr[i].toString(16); str += temp.substring(temp.length - 2); } return str; } This gives you the property that foo(bar(x)) === x (if x is an array of less than 65536 integers between 0 and 255 as stated previously), but not the property bar(foo(x)) === x because as MSN pointed out that property is impossible to achieve for your function. EG. bar([17,125,12,11]) gives the string: "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000117dcb" which if you give as input to your function foo you get back the original array: [17,125,12,11], but there are many other inputs (at least 268 of those 0's can be any other of the values in [0-9a-fA-F], and the 04 can be anything greater than 04 which means 22^268*(255 - 4) different strings multiplied by a bit more since that only takes into account either lower case or capitals but not both when multiplying by 255 - 4. regardless 22^268 is a ridiculous number of inputs for one output anyways, and that's ignoring the fact that their are an infinite amount of strings which begin with the string above and have any other hexadecimal string appended to them which will give the same output from foo because of the sliceEnd variable.
That function is not a 1 to 1 function, i.e., many inputs will generate the same output.
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)