"lottery" in javascript - sort algorithm? - javascript

I'm trying to understand the code example that's at the end of my post and I need help. So this is supposed to be a "lottery". So here's what I see:
for( i = 1 ; i < 50 ; i++ ){ nums[ i ] = i ; }
Here it assigns the value of i (which will be between 1 and 49) to each each i-th element of the nums array. So I guess it's just making an array that contains the numbers 1 to 49. I don't see the point of this whole line, actually, given the code that follows.
for( i = 1 ; i < 50 ; i++ )
{
rand = Math.ceil( Math.random() * 49 ) ;
temp = nums[ i ] ;
nums[ i ] = nums[ rand ] ;
nums[ rand ] =temp ;
}
Here I get confused. So, once again it runs a standard loop from 1 to 49, and for each of the 49 iterations, it:
assigns a random number between 1 and 49 to "rand"
assigns the i-th value of the 'nums' list (which will still be just i, right?) to temp (why?)
assigns the random number to the i-th element of the "nums" array, so presumably if it's at i=1, nums[i] = 1, and now instead of 1 it's the random number.
Then it assigns temp (which was the original value, which was i anyway) back to the value that's in the rand-th position of the nums array.
So what am I misunderstanding here? I don't get the point of this. Where is this leading? Am I reading it correctly? Presumably at the end of this, the numbers inside the array are jumbled up, and then at the end it just picks the first six, which are 6 "random" numbers. But why not just do something like:
var nums=[];
for(i=0; i<6; i++) {
nums[i] == Math.ceil(Math.random() * 49);
}
along with a test to ensure the random numbers weren't the same?
Here's the code example in whole:
function init()
{
var panel = document.getElementById( "panel" ) ;
var i , rand , temp , str , nums = [] ;
for( i = 1 ; i < 50 ; i++ ){ nums[ i ] = i ; }
for( i = 1 ; i < 50 ; i++ )
{
rand = Math.ceil( Math.random() * 49 ) ;
temp = nums[ i ] ;
nums[ i ] = nums[ rand ] ;
nums[ rand ] =temp ;
}
str = "Your Six Lucky Numbers:<br>" ;
for( i = 1 ; i < 7 ; i++ )
{
str += nums[ i ] ;
if( i !== 6 ) { str += " - " ; }
}
panel.innerHTML = str;
}
document.addEventListener( "DOMContentLoaded" , init , false ) ;

The code is supposed to create an array of numbers and then shuffle them. It's almost using a Fisher-Yates shuffle, but not quite. There is also a bug in the random number generation.
Putting the numbers 1 through 49 in the array is not pointless, those are the numbers that are used later on. They are not replaced, they are just moved around in the array.
The next loop will shuffle the items in the array, but first let's look at the random number generation. This way of creating a random number is wrong:
rand = Math.ceil(Math.random() * 49); // Don't use this
The Math.random() method returns a value that is 0 <= x < 1. Multiplying that number by 49 and then using Math.ceil doesn't produce numbers between 1 and 49, it produces numbers between 0 and 49. The number 0 comes very rarely, but you can't ignore it. The correct way to produce the random number is:
rand = Math.floor(Math.random() * 49) + 1;
The code for shuffling the items in the array loops through the items and picks an item by random to swap each item with. This produces a biased shuffle, and it should use the Fisher-Yates algorithm instead:
for (i = 49 ; i >= 1 ; i--) {
rand = Math.floor(Math.random() * i) + 1;
temp = nums[i];
nums[i] = nums[rand];
nums[rand] = temp;
}
The last three lines in the loop swaps two items in the array. It stores away the value from one item, copies the value from the other item into the first, and then puts the stored value in the other item.
(The values of i and rand can actually be the same for some items, so that an item is swapped with itself. This is how the algorithm is supposed to work, it ensures that the item has the same chance of staying in the same place as the chance of being moved to any other place.)
But why not just do something like [code] along with a test to ensure
the random numbers weren't the same?
That is another way of creating the random numbers. It would be somewhat more efficient, at least most of the time (it could theoretically loop forever), but it's about the same amount of code.
Another solution would be to put all the numbers in one array, then pick numbers by random from it and move them to another array. That is the same principle as the shuffling algorithm, but it only needs to shuffle enough to get the first six items in the right place (or the last six items as it would be using the Fisher-Yates algorithm). However, removing items from an array is generally an expensive operation, as the items after it needs to be shifted into its place.

It is indeed a basic shuffle. The point is to ensure we only have unique numbers to begin with.
Doing this shuffle iterates once over the loop.
Checking uniqueness requires iterating once over the loop... for every element in the loop.
For small loops like this, the difference is basically nil, but in general when given two options you should take the one that's less computationally complicated... but always remember to comment the code to explain it to future developers!

Related

Trying to optimize my code to either remove nested loop or make it more efficient

A friend of mine takes a sequence of numbers from 1 to n (where n > 0)
Within that sequence, he chooses two numbers, a and b
He says that the product of a and b should be equal to the sum of all numbers in the sequence, excluding a and b
Given a number n, could you tell me the numbers he excluded from the sequence?
Have found the solution to this Kata from Code Wars but it times out (After 12 seconds) in the editor when I run it; any ideas as too how I should further optimize the nested for loop and or remove it?
function removeNb(n) {
var nArray = [];
var sum = 0;
var answersArray = [];
for (let i = 1; i <= n; i++) {
nArray.push(n - (n - i));
sum += i;
}
var length = nArray.length;
for (let i = Math.round(n / 2); i < length; i++) {
for (let y = Math.round(n / 2); y < length; y++) {
if (i != y) {
if (i * y === sum - i - y) {
answersArray.push([i, y]);
break;
}
}
}
}
return answersArray;
}
console.log(removeNb(102));
.as-console-wrapper { max-height: 100% !important; top: 0; }
I think there is no reason for calculating the sum after you fill the array, you can do that while filling it.
function removeNb(n) {
let nArray = [];
let sum = 0;
for(let i = 1; i <= n; i++) {
nArray.push(i);
sum += i;
}
}
And since there could be only two numbers a and b as the inputs for the formula a * b = sum - a - b, there could be only one possible value for each of them. So, there's no need to continue the loop when you find them.
if(i*y === sum - i - y) {
answersArray.push([i,y]);
break;
}
I recommend looking at the problem in another way.
You are trying to find two numbers a and b using this formula a * b = sum - a - b.
Why not reduce the formula like this:
a * b + a = sum - b
a ( b + 1 ) = sum - b
a = (sum - b) / ( b + 1 )
Then you only need one for loop that produces the value of b, check if (sum - b) is divisible by ( b + 1 ) and if the division produces a number that is less than n.
for(let i = 1; i <= n; i++) {
let eq1 = sum - i;
let eq2 = i + 1;
if (eq1 % eq2 === 0) {
let a = eq1 / eq2;
if (a < n && a != i) {
return [[a, b], [b, a]];
}
}
}
You can solve this in linear time with two pointers method (page 77 in the book).
In order to gain intuition towards a solution, let's start thinking about this part of your code:
for(let i = Math.round(n/2); i < length; i++) {
for(let y = Math.round(n/2); y < length; y++) {
...
You already figured out this is the part of your code that is slow. You are trying every combination of i and y, but what if you didn't have to try every single combination?
Let's take a small example to illustrate why you don't have to try every combination.
Suppose n == 10 so we have 1 2 3 4 5 6 7 8 9 10 where sum = 55.
Suppose the first combination we tried was 1*10.
Does it make sense to try 1*9 next? Of course not, since we know that 1*10 < 55-10-1 we know we have to increase our product, not decrease it.
So let's try 2*10. Well, 20 < 55-10-2 so we still have to increase.
3*10==30 < 55-3-10==42
4*10==40 < 55-4-10==41
But then 5*10==50 > 55-5-10==40. Now we know we have to decrease our product. We could either decrease 5 or we could decrease 10, but we already know that there is no solution if we decrease 5 (since we tried that in the previous step). So the only choice is to decrease 10.
5*9==45 > 55-5-9==41. Same thing again: we have to decrease 9.
5*8==40 < 55-5-8==42. And now we have to increase again...
You can think about the above example as having 2 pointers which are initialized to the beginning and end of the sequence. At every step we either
move the left pointer towards right
or move the right pointer towards left
In the beginning the difference between pointers is n-1. At every step the difference between pointers decreases by one. We can stop when the pointers cross each other (and say that no solution can be obtained if one was not found so far). So clearly we can not do more than n computations before arriving at a solution. This is what it means to say that the solution is linear with respect to n; no matter how large n grows, we never do more than n computations. Contrast this to your original solution, where we actually end up doing n^2 computations as n grows large.
Hassan is correct, here is a full solution:
function removeNb (n) {
var a = 1;
var d = 1;
// Calculate the sum of the numbers 1-n without anything removed
var S = 0.5 * n * (2*a + (d *(n-1)));
// For each possible value of b, calculate a if it exists.
var results = [];
for (let numB = a; numB <= n; numB++) {
let eq1 = S - numB;
let eq2 = numB + 1;
if (eq1 % eq2 === 0) {
let numA = eq1 / eq2;
if (numA < n && numA != numB) {
results.push([numA, numB]);
results.push([numB, numA]);
}
}
}
return results;
}
In case it's of interest, CY Aries pointed this out:
ab + a + b = n(n + 1)/2
add 1 to both sides
ab + a + b + 1 = (n^2 + n + 2) / 2
(a + 1)(b + 1) = (n^2 + n + 2) / 2
so we're looking for factors of (n^2 + n + 2) / 2 and have some indication about the least size of the factor. This doesn't necessarily imply a great improvement in complexity for the actual search but still it's kind of cool.
This is part comment, part answer.
In engineering terms, the original function posted is using "brute force" to solve the problem, iterating every (or more than needed) possible combinations. The number of iterations is n is large - if you did all possible it would be
n * (n-1) = bazillio n
Less is More
So lets look at things that can be optimized, first some minor things, I'm a little confused about the first for loop and nArray:
// OP's code
for(let i = 1; i <= n; i++) {
nArray.push(n - (n - i));
sum += i;
}
??? You don't really use nArray for anything? Length is just n .. am I so sleep deprived I'm missing something? And while you can sum a consecutive sequence of integers 1-n by using a for loop, there is a direct and easy way that avoids a loop:
sum = ( n + 1 ) * n * 0.5 ;
THE LOOPS
// OP's loops, not optimized
for(let i = Math.round(n/2); i < length; i++) {
for(let y = Math.round(n/2); y < length; y++) {
if(i != y) {
if(i*y === sum - i - y) {
Optimization Considerations:
I see you're on the right track in a way, cutting the starting i, y values in half since the factors . But you're iterating both of them in the same direction : UP. And also, the lower numbers look like they can go a little below half of n (perhaps not because the sequence start at 1, I haven't confirmed that, but it seems the case).
Plus we want to avoid division every time we start an instantiation of the loop (i.e set the variable once, and also we're going to change it). And finally, with the IF statements, i and y will never be equal to each other the way we're going to create the loops, so that's a conditional that can vanish.
But the more important thing is the direction of transversing the loops. The smaller factor low is probably going to be close to the lowest loop value (about half of n) and the larger factor hi is probably going to be near the value of n. If we has some solid math theory that said something like "hi will never be less than 0.75n" then we could make a couple mods to take advantage of that knowledge.
The way the loops are show below, they break and iterate before the hi and low loops meet.
Moreover, it doesn't matter which loop picks the lower or higher number, so we can use this to shorten the inner loop as number pairs are tested, making the loop smaller each time. We don't want to waste time checking the same pair of numbers more than once! The lower factor's loop will start a little below half of n and go up, and the higher factor's loop will start at n and go down.
// Code Fragment, more optimized:
let nHi = n;
let low = Math.trunc( n * 0.49 );
let sum = ( n + 1 ) * n * 0.5 ;
// While Loop for the outside (incrementing) loop
while( low < nHi ) {
// FOR loop for the inside decrementing loop
for(let hi = nHi; hi > low; hi--) {
// If we're higher than the sum, we exit, decrement.
if( hi * low + hi + low > sum ) {
continue;
}
// If we're equal, then we're DONE and we write to array.
else if( hi * low + hi + low === sum) {
answersArray.push([hi, low]);
low = nHi; // Note this is if we want to end once finding one pair
break; // If you want to find ALL pairs for large numbers then replace these low = nHi; with low++;
}
// And if not, we increment the low counter and restart the hi loop from the top.
else {
low++;
break;
}
} // close for
} // close while
Tutorial:
So we set the few variables. Note that low is set slightly less than half of n, as larger numbers look like they could be a few points less. Also, we don't round, we truncate, which is essentially "always rounding down", and is slightly better for performance, (though it dosenit matter in this instance with just the single assignment).
The while loop starts at the lowest value and increments, potentially all the way up to n-1. The hi FOR loop starts at n (copied to nHi), and then decrements until the factor are found OR it intercepts at low + 1.
The conditionals:
First IF: If we're higher than the sum, we exit, decrement, and continue at a lower value for the hi factor.
ELSE IF: If we are EQUAL, then we're done, and break for lunch. We set low = nHi so that when we break out of the FOR loop, we will also exit the WHILE loop.
ELSE: If we get here it's because we're less than the sum, so we need to increment the while loop and reset the hi FOR loop to start again from n (nHi).

Array of random numbers optimization

I have a function that generates an array of random numbers. It works, but I feel that it might works slow on big numbers. Is there a way how to optimize it?
function renerateRandomNumbers(maxNumber, randomNumbersCount) {
let i;
const arrResult = [];
for (i = 0; i < randomNumbersCount; i++) {
let rand = Math.random() * (maxNumber);
rand = Math.round(rand);
if (arrResult.indexOf(rand) === -1 ) {
arrResult.push(rand);
} else {
i--;
}
}
return arrResult;
}
EDIT - To any future users, #ScottSauyet's solution should be the accepted answer. It is a more consistently efficient solution than mine.
I think the most algorithmically efficient way to solve this would be to generate the list of all possible numbers from 0-maxNumber, shuffle that array (O(n)), and then take the first randomNumbersCount numbers from the shuffled array. It would look like the following:
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
function generateRandomNumbers(maxNumber, randomNumbersCount) {
var possibleNumbers = [];
// populate array with all possible values
for (var i = 0; i <= maxNumber; i++) { possibleNumbers.push(i); }
// shuffle the array to get a random order of the possible numbers O(n)
shuffleArray(possibleNumbers);
// trim the array down to only the first n numbers where n = randomNumbersCount
possibleNumbers.length = randomNumbersCount;
return possibleNumbers;
}
console.log (generateRandomNumbers(10, 5));
console.log (generateRandomNumbers(10, 5));
console.log (generateRandomNumbers(10, 5));
The problem of your code is that complexity grows geometrically because it have a chance generate number that was already picked multiple times.
What we need to achieve is to get number on every iteration to achieve iterations count to be equal to the randomNumbersCount.
How to avoid multiple same random numbers?
let's say you want to have 5 random numbers from 0-10 range
First iteration
Create an array with values var candidates = [0,1...10]
Generate random number let's say 0
Store the number candidates[0] in results
Remove 0 from candidates. To avaoid reindexing of the candidates array we will put candidates[candidates.length - 1] into candidates[0] and remove candidates[candidates.length - 1]
and then will do this operation randomNumbersCount times.
Second iteration
Our candidates array is now [10,1,2,3,4,5,6,7,8,9]
Generate random number let's say 0 again. Wow we generated similar random number, but so what?
we alreay have 0 in our results, but candidates[0] is not a 0 anymore candidates[0] is 10 right now
so we pick candidates[0] that is 10 and will store it and remove it from candidates. Put candidates[candidates.length - 1] (9) into candidates[0] and remove candidates[candidates.length - 1]
our result is [0, 10] right now
Third iteration
Our candidates is now [9,1,2,3,4,5,6,7,8]
Generate random number let's say 0
we are not worring anymore because we know that candidates[0] is 9
add candidates[0] (witch is 9) we are saving to results, and remove it from candidates
our result is [0,10,9], candidates is [8,1,2,3,4,5,6,7]
And so on
BTW implementation is much shorter than explanation:
function renerateRandomNumbers(maxNumber, randomNumbersCount) {
var candidates = [...Array(maxNumber).keys()];
return Array(randomNumbersCount).fill()
.map(() => {
const randomIndex = Math.floor(Math.random() * candidates.length)
const n = candidates[randomIndex]
candidates[randomIndex] = candidates[candidates.length - 1]
candidates.length = candidates.length - 1
return n
})
.sort((a, b) => a - b) // sort if needed
}
console.log (renerateRandomNumbers(10, 5))
The solution from mhodges is reasonably efficient, but only when the sought count is fairly close to the max number. If your count is significantly smaller, this can be a problem, as the solution is O(m + n) where m is the maximum and n is the desired count. It's also O(m) in space. If m is large, this could be a problem.
A variant would make this approximately O(n) in time and space, by doing the same thing, but stopping the shuffle when when we've reached count items and by not pre-filling the array but instead defaulting to its indices.
function venerateRandomNumbers(max, count) {
// todo: error if count > max
const arr = new Array(max + 1)
for (let i = max; i > max - count; i--) {
const j = Math.floor(Math.random() * (i + 1))
const temp = arr[j] || j
arr[j] = arr[i] || i
arr[i] = temp
}
return arr.slice(-count)
}
console.log(venerateRandomNumbers(1000000, 10))
You can see performance comparisons on repl.it

Why is my for loop stopping before everything is evaluated?

I'm trying to get the largest palindrome made from the product of two 3-digit numbers. In case you don't know, a palindrome is a number that is the same forwards as it is backward (ex: 9009, or 55855, etc..).
My method involves looping through all three digit numbers and multiplying them, if the product matches itself reversed, updating the variable 'palindrome' with that product. I'm expecting 906609, but it's returning 99999.
Been racking my brain on this one, don't see anything wrong but there's obviously something. Any thoughts?
//Hoist 'palindrome'
var palindrome = 0;
//Loop through 100 - 1000
for(var i = 100; i < 1000; i++) {
//Within that loop, loop through 100 - 1000
for(var k = 100; k < 1000; k++) {
//Convert product of K & I and reverse to strings
var product = (k * i).toString();
var reversed = product.match(/.{1}/g).reverse().toString().replace(/,/g, '');
//If the product and reverse are the same, update palindrome
if(product === reversed) {
if(reversed > palindrome) {
var palindrome = product;
}
}
}
}
//Expecting 906609, but returns 99999
console.log(palindrome)
because
"99999" > "906609" // true
as you are comparing strings, they are compared lexically. You want to compare numbers:
if(+reversed > +palindrome)

new to javascript code and having some issues already

i have this code: the idea is to print the list of the 10 random numbers and then add 6 to each item on the list and finally print new list with the new numbers after the additions: I've tried several modification but all of them are failing, any ideas??
var myArray = [];
appendItem(myArray, randomNumber(1,10));
appendItem(myArray, randomNumber(1,10));
appendItem(myArray, randomNumber(1,10));
appendItem(myArray, randomNumber(1,10));
console.log("Before: " + myArray);
for (var i = 0; i < myArray.lenght; i++) {
myArray = [i] + 5;
}
console.log("After: " + myArray);
one solution can be
let myArray = []
for (let i = 0 ; i < 5 ; i++) {
myArray.push(Math.floor(Math.random() * 10) + 5);
}
console.log(myArray)
A couple of things to help you along your way...
It looks like you're using borrowed code somewhere, because randomNumber is not a native JavaScript function.
So, first to get a random number, you can read more about Math.random() here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
Math.random() natively provides a decimal number between 0 and 1 (0.4, 0.67, 0.321 ...) To get a range, you multiply your answer by the maximum number for the range. And then commonly you want to wrap that in a Math.floor() method to trim the decimal points (this is just a Math method that all it does is trim off anything that's a decimal point and provides a whole number)
W3C is a good place to start to read up about arrays:
https://www.w3schools.com/js/js_arrays.asp
The common convention for adding elements to an array is to use .push() but you can look into .pop() and .filter() and .map() and there's just a ton of helpful methods attached to JavaScript arrays :)
/*
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
*/
let originalArray = [];
let plusSixArray = [];
let max = 10; // set the range for your random number
// max = 10 will let the range be from 0 - 9
// max = 273 will let the range be from 0 - 272
for( var i=0; i<10; i++ ){
let number = Math.floor(Math.random() * max) + 1;
// adding 1 to the end gives you a range between 1 - 10
originalArray.push( number );
// since you're already in a loop, just add the 6
plusSixArray.push( number + 6 );
}
console.log( originalArray );
console.log( plusSixArray );

wait for while loop to end before executing code

I am trying to retrieve data from an object, I generate 3 random numbers from 1-9 and then pick out data from a json object using these random numbers. However it sometimes works and then sometimes doesn't, I think it might be because it doesn't wait for the random numbers to be generated before selecting data from the object, it all occurs on page load:
the jsfiddle:
http://jsfiddle.net/dbqw79j4/1/
the code:
var jsonfile =[
{
"id" : "article1",
"image" : "http://images.domain.com/is/image/boss/BOSS_london_bridge_skyline?$c_overview_large$",
"headline" : "<h2>EIN TAG IN LONDON<span class='h2'>MIT LEWIS HAMILTON</span></h2>"
},
{
"id" : "article2",
"image" : "http://images.domain.com/is/image/boss/FAB_5819?$c_overview_large$",
"headline" : "<h2>EIN TAG IN MONACO<span class='h2'>MIT NICO ROSBERG</span></h2>"
},
...
]
var arr = []
var article1;
var article2;
var article3;
var art1hd;
var art1img;
var art2hd;
var art2img;
var art3hd;
var art3img;
while(arr.length < 3){
var randomnumber=Math.ceil(Math.random()*9)
var found=false;
for(var i=0;i<arr.length;i++){
if(arr[i]==randomnumber){found=true;break}
}
if(!found)arr[arr.length]=randomnumber;
}
console.log(arr);
console.log(arr[0]);
console.log(arr[1]);
console.log(arr[2]);
article1 = arr[0];
article2 = arr[1];
article3 = arr[2];
console.log(article1)
console.log(article2)
console.log(article3)
art1hd = jsonfile[article1]['headline'];
art1img = jsonfile[article1]['image'];
art2hd = jsonfile[article2]['headline'];
art2img = jsonfile[article2]['image'];
art3hd = jsonfile[article3]['headline'];
art3img = jsonfile[article3]['image'];
console.log(art1hd)
console.log(art1img)
console.log(art2hd)
console.log(art2img)
console.log(art3hd)
console.log(art3img)
You generate random numbers from range of 0-9 and your array contains only 9 elements and it is indexed from 0-8
You should use:
while(arr.length < 3){
var randomnumber=Math.ceil(Math.random()*8)
var found=false;
for(var i=0;i<arr.length;i++){
if(arr[i]==randomnumber){found=true;break}
}
if(!found)arr[arr.length]=randomnumber;
}
The problem is, your "jsonfile" array has nine elements. this breaks when you generate the random number 9, as arrays are zero-based, the valid values for indexing the array are 0-8
Math.ceil() is never the right function to generate an integer result based on Math.random() times something as this code does:
var randomnumber = Math.ceil( Math.random() * 9 );
You should always use Math.floor() in code like this instead. If you don't want your range to start with 0, then add the range base after doing the Math.floor().
In other words, if you want a random integer in the range 1 through 9 inclusive, this is the correct way to do it:
var randomnumber = Math.floor( Math.random() * 9 ) + 1;
Why is this? It's important to understand that Math.random() produces a value that is greater than or equal to 0, and less than (but never equal to) 1.
So Math.random() * 9 gives a value that is always less than 9 (and never equal to 9). If you take Math.floor() on that, you now have an integer in the range 0 through 8 inclusive.
Add 1 to that, and you have your desired range of 1 through 9.
Many JavaScript references fail to describe Math.random() clearly. Just keep in mind that its result is in the range 0 <= Math.random() < 1.
So, what could go wrong if you used Math.ceil()? Going back to the original example:
var randomnumber = Math.ceil( Math.random() * 9 );
What this code actually does is generates a number in the range 0 through 9, not 1 through 9. Now the chance of getting a 0 result is extremely small: it would be fairly rare for Math.random() to return 0, but it can happen. By using Math.floor() instead, you insure that the result is always in the desired range.
That said, as suvroc points out, you're (eventually) using this value as an index into an array of 9 elements, therefore the range you want is actually 0 through 8. So the code should be:
var randomnumber = Math.floor( Math.random() * 9 );
It is, because the random number generator can generate the number 9, but your jsonfile has only 9 elements, so the last index is 8.
First, as others said the random number generated as to be :
Math.floor(Math.random()*9)
Then I reviewed the code to be sure of synchronicity :
http://jsfiddle.net/dbqw79j4/6/
I did a recursive function who calls logs on arr.length >= 3 and add a random number if it doesn't exists on arr.

Categories

Resources