Why does it take so many attempts to generate a random value between 1 and 10000? - javascript

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.

Related

Sorting Arrays Javascript

I am brand new to javascript(I have been exposed to DOM manipulation, however for this assignment we can display input in a simple console.log according to the prof) and I have came across this problem that was due for a school assignment, I need to take user input of 3 numbers, display them, and show the max and min number entered, as well as the average.
The code I have below preforms as I intended but what I am looking for is feedback for improvements, I am still in the process of training my brain to break down these types of problems as well as organize my thinking. I would like to be practicing the "best" methods or most effective methods, as my thinking and logic is not yet defined and I am in the stage where everything is new so I may as learn the most effective ways/strategies. Any improvements or better ways to solve this question is greatly appreciated.
Thanks!
let num = parseFloat(prompt("enter your first number"));
let num1 = parseFloat(prompt("enter your second number"));
let num2 = parseFloat(prompt("enter your third number"));
let avg = parseFloat(console.log('The Average of The Numbers',
num, ',', num1, ',', num2, 'Is:', (num + num1 + num2) / 3));
let numTot = parseFloat(console.log(`The Numbers You Have Entered
Are`, num, +num1, +num2));
let total = parseFloat(console.log('The Total Of', num, '+', num1,
'+', num2, 'Is :', num + num1 + num2));
let highest = Math.max(num, num1, num2);
let lowest = Math.min(num, num1, num2);
console.log("The Highest Number Entered Is:", highest);
console.log("The Lowest Number Entered Is:", lowest);
Here's how I would do it:
Declare your numbers in an array. Prefix them with + to coerce them
from a String to Number.
Array.reduce to loop over your array and calculate the average.
Use spread syntax to obtain min/max values in the accumulator object,
you pass to .reduce.
// prompt returns a String, prefix with +
// to coerce them to Numbers, since we'll be
// working with numbers.
const numbers = [
+prompt('Enter number 1'),
+prompt('Enter number 2'),
+prompt('Enter number 3')
]
const result = numbers.reduce((acc, number, index) => {
// For each number:
// Add the number to the accumulator sum.
acc.sum += number
// If this is the last iteration:
if (index === numbers.length - 1) {
// Calculate the average from the sum.
acc.avg = acc.sum / numbers.length
// Also discard the sum property, we no longer need it.
delete acc.sum
}
// Return the accumulator for the next iteration.
return acc
}, {
// Our accumulator object, initialised with min/max values.
min: Math.min(...numbers),
max: Math.max(...numbers),
sum: 0,
avg: 0
})
// Log the processed accumulator.
console.log(result)
Why use a loop at all?
Array.reduce loops over an array, similarly to how a for loop does. Using a loop-like construct allows you to add more numbers in the numbers array without needing to modify your calculations code.
Why divide at the end of the loop?
Summing the numbers and dividing once at the end of the loop helps avoid numerical errors.
If you do acc.avg = acc.avg + number / numbers.length on each iteration you'll start noticing that the average turns out to be a bit off. Try it just for the sake of it.
Might look a bit complex for a beginner but those 2 concepts (esp. Array.reduce) are worth looking into. FWIW, the classroom example given for teaching Array.reduce is calculating
averages from an array of numbers.
If you want to use advances features, then reference to the Nik Kyriakides answer. On this approach I will use a for loop to ask for numbers in an iterative way and calculate the minimun, maximun and total progressively. The average could be obtained dividing total by the quantity of numbers you asked for:
const numbersToAsk = 3;
let max, min, avg, total = 0;
for (var i = 1; i <= numbersToAsk; i++)
{
// Ask the user for a new number and get it.
let num = parseFloat(prompt("enter your number " + i));
// Sum the new number to the previous accumulated total.
total += num;
// Recalculate the new maximum, if there wasn't a previous one,
// just assign the current number.
max = !max ? num : Math.max(max, num);
// Recalculate the new minimum, if there wasn't a previous one,
// just assign the current number.
min = !min ? num : Math.min(min, num);
}
// Calulate the average.
avg = total / numbersToAsk;
// Show the obtained results on the console.
console.log(
"Total: " + total,
"Average: " + avg,
"Min: " + min,
"Max: " + max
);

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 ^^;

How do I optimally distribute values over an array of percentages?

Let's say I have the following code:
arr = [0.1,0.5,0.2,0.2]; //The percentages (or decimals) we want to distribute them over.
value = 100; //The amount of things we have to distribute
arr2 = [0,0,0,0] //Where we want how many of each value to go
To find out how to equally distribute a hundred over the array is simple, it's a case of:
0.1 * 100 = 10
0.5 * 100 = 50
...
Or doing it using a for loop:
for (var i = 0; j < arr.length; i++) {
arr2[i] = arr[i] * value;
}
However, let's say each counter is an object and thus has to be whole. How can I equally (as much as I can) distribute them on a different value. Let's say the value becomes 12.
0.1 * 12 = 1.2
0.5 * 12 = 6
...
How do I deal with the decimal when I need it to be whole? Rounding means that I could potentially not have the 12 pieces needed.
A correct algorithm would -
Take an input/iterate through an array of values (for this example we'll be using the array defined above.
Turn it into a set of whole values, which added together equal the value (which will equal 100 for this)
Output an array of values which, for this example it will look something like [10,50,20,20] (these add up to 100, which is what we need to add them up to and also are all whole).
If any value is not whole, it should make it whole so the whole array still adds up to the value needed (100).
TL;DR dealing with decimals when distributing values over an array and attempting to turn them into an integer
Note - Should this be posted on a different stackoverflow website, my need is programming, but the actual question will likely be solved using a mathematics. Also, I had no idea how to word this question, which makes googling incredibly difficult. If I've missed something incredibly obvious, please tell me.
You should round all values as you assign them using a rounding that is known to uniformly distribute the rounding. Finally, the last value will be assigned differently to round the sum up to 1.
Let's start slowly or things get very confused. First, let's see how to assign the last value to have a total of the desired value.
// we will need this later on
sum = 0;
// assign all values but the last
for (i = 0; i < output.length - 1; i++)
{
output[i] = input[i] * total;
sum += output[i];
}
// last value must honor the total constraint
output[i] = total - sum;
That last line needs some explanation. The i will be one more than the last allowed int the for(..) loop, so it will be:
output.length - 1 // last index
The value we assign will be so that the sum of all elements is equal to total. We already computed the sum in a single-pass during the assignment of the values, and thus don't need to iterated over the elements a second time to determine it.
Next, we will approach the rounding problem. Let's simplify the above code so that it uses a function on which we will elaborate shortly after:
sum = 0;
for (i = 0; i < output.length - 1; i++)
{
output[i] = u(input[i], total);
sum += output[i];
}
output[i] = total - sum;
As you can see, nothing has changed but the introduction of the u() function. Let's concentrate on this now.
There are several approaches on how to implement u().
DEFINITION
u(c, total) ::= c * total
By this definition you get the same as above. It is precise and good, but as you have asked before, you want the values to be natural numbers (e.G. integers). So while for real numbers this is already perfect, for natural numbers we have to round it. Let's suppose we use the simple rounding rule for integers:
[ 0.0, 0.5 [ => round down
[ 0.5, 1.0 [ => round up
This is achieved with:
function u(c, total)
{
return Math.round(c * total);
}
When you are unlucky, you may round up (or round down) so much values that the last value correction will not be enough to honor the total constraint and generally, all value will seem to be off by too much. This is a well known problem of which exists a multi-dimensional solution to draw lines in 2D and 3D space which is called the Bresenham algorithm.
To make things easy I'll show you here how to implement it in 1 dimension (which is your case).
Let's first discuss a term: the remainder. This is what is left after you have rounded your numbers. It is computed as the difference between what you wish and what you really have:
DEFINITION
WISH ::= c * total
HAVE ::= Math.round(WISH)
REMAINDER ::= WISH - HAVE
Now think about it. The remained is like the piece of paper that you discard when you cut out a shape from a sheet. That remaining paper is still there but you throw it away. Instead of this, just add it to the next cut-out so it is not wasted:
WISH ::= c * total + REMAINDER_FROM_PREVIOUS_STEP
HAVE ::= Math.round(WISH)
REMAINDER ::= WISH - HAVE
This way you keep the error and carry it over to the next partition in your computation. This is called amortizing the error.
Here is an amortized implementation of u():
// amortized is defined outside u because we need to have a side-effect across calls of u
function u(c, total)
{
var real, natural;
real = c * total + amortized;
natural = Math.round(real);
amortized = real - natural;
return natural;
}
On your own accord you may wish to have another rounding rule as Math.floor() or Math.ceil().
What I would advise you to do is to use Math.floor(), because it is proven to be correct with the total constraint. When you use Math.round() you will have smoother amortization, but you risk to not have the last value positive. You might end up with something like this:
[ 1, 0, 0, 1, 1, 0, -1 ]
Only when ALL VALUES are far away from 0 you can be confident that the last value will also be positive. So, for the general case the Bresenham algoritm would use flooring, resulting in this last implementation:
function u(c, total)
{
var real, natural;
real = c * total + amortized;
natural = Math.floor(real); // just to be on the safe side
amortized = real - natural;
return natural;
}
sum = 0;
amortized = 0;
for (i = 0; i < output.length - 1; i++)
{
output[i] = u(input[i], total);
sum += output[i];
}
output[i] = total - sum;
Obviously, input and output array must have the same size and the values in input must be a paritition (sum up to 1).
This kind of algorithm is very common for probabilistical and statistical computations.
Alternate implementation - it remembers a pointer to the biggest rounded value and when the sum differs of 100, increment or decrement value at this position.
const items = [1, 2, 3, 5];
const total = items.reduce((total, x) => total + x, 0);
let result = [], sum = 0, biggestRound = 0, roundPointer;
items.forEach((votes, index) => {
let value = 100 * votes / total;
let rounded = Math.round(value);
let diff = value - rounded;
if (diff > biggestRound) {
biggestRound = diff;
roundPointer = index;
}
sum += rounded;
result.push(rounded);
});
if (sum === 99) {
result[roundPointer] += 1;
} else if (sum === 101) {
result[roundPointer] -= 1;
}

Node.js is trolling me. Generating random names and tweets using arrays

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).

Generate 1000 random 10 digit number using javascript in a loop

I want to generate atleast 1000 unique random numbers with 10 digit using
javascript in a loop. Is this possible? Or is Javascript a wrong thing to do this?
UPDATE: How will you be sure that duplicates are not created?
Here's how I would do it:
var arr = [],
track = [],
min = 1000000000,
max = 9999999999,
qty = 1000,
ii = 0,
rnd;
while (ii < qty) {
rnd = Math.floor(Math.random() * (max - min + 1)) + min;
if (!track[rnd]) {
arr[ii] = track[rnd] = rnd;
ii += 1;
}
}
Here's a working example: http://jsfiddle.net/mTmEs/
Now, if something went awry with Math.random and for some reason it were to generate a lot of duplicates, this code could take a long time to complete. I don't think there is any way around this kind of potential problem though when you're talking about large quantities of unique random numbers.
Yes, it's possible.
Use Math.random to generate the pseudo-random numbers. Math.random returns a pseudo-random number greater than or equal to 0 and less than 1, so to get a 10-digit number (I'm assuming a whole number), you'd multiple that by 1,000,000,000 and round it off with Math.round or Math.floor. (If you need them all to be 10 digits, adjust accordingly — adding a base amount, multiplying by a higher number, etc.)
Use an object to keep track of them, so var obj = {}; to start with.
Store the numbers as keys in an object, e.g. obj[number] = true.
Test whether the object has the generated number using if (obj[number])
Loop until you have the correct number of unique numbers.
The reason I use an object for storing the numbers is that JavaScript objects are maps by their nature, and engines are optimized to retrieve properties from objects quickly. Under the covers, an implementation can do what it likes, but will probably use a hash table or similar.
Note that using an "array" for this is unnecessary; JavaScript arrays aren't really arrays, they're just objects with a couple of special features.
You could do this in JS, but you would have to check the array to see if it contains the currently generated random number. This would obviously degrade performance.
See if these answers help.
Random number generator that fills an interval
Generate unique random numbers between 1 and 100
A generic function for generating n random numbers of length l might be:
// Generate n unique random numbers of length l
// l should be less than 15
function genNRandLen(n, l) {
// Make sure l and n are numbers
n = Number(n);
l = Number(l);
// Protect against bad input
if (isNaN(l) || isNaN(n)) return;
var o = {}, a = [], num;
var min = l == 1? 0 : Math.pow(10, l-1);
var r = Math.pow(10, l) - min;
// Protect against endless loop
if (n >= (r)) return;
while (n--) {
do {
num = Math.floor(min + (Math.random()*r));
} while (o[num])
o[num] = true;
a[n] = num;
}
return a.sort();
}
Sorting is just to make it easy to see duplicates when testing, remove if not necessary or random order is preferred.
If numbers longer than 15 digits are required, they can be created by concatenating strings of shorter random numbers and trimming to the required length. The following will generate a random number of any length:
// Generate random number of length l
function randLen(l) {
var n = '';
while (n.length < l) {
n += String(Math.random()).replace(/^0\.0*/,'');
}
return n.substring(0, l);
}
It must return a string since converting to number will mess with the results. Oh, and all numbers are integers.
Why not? Here is the code:
var a=[];
for (var i=1000; i--;)
a.push(Math.random()*10000000000)

Categories