Generate 1000 random 10 digit number using javascript in a loop - javascript
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)
Related
How to write an efficient algorithm that generates a list of unique random numbers? [duplicate]
This question already has answers here: How do I shuffle a Javascript Array ensuring each Index is in a new position in the new Array? (5 answers) Closed 1 year ago. I'm pretty new to algorithms and am trying to solve a problem that involves generating a list of 5,000 numbers in random order each time it is run. Each number in the list must be unique and be between 1 and 5,000 (inclusive). function createRandomList() { let arr = []; while(arr.length < 5000){ const num = Math.floor(Math.random() * 5000) + 1; if(arr.indexOf(num) === -1) arr.push(num); } console.log(arr); } createRandomList() Here's the solution that I came up with. I wanted to know the Time/Space complexity of this solution. Would it just be O(1) for both space and time because the values are bounded? Any feedback would be greatly appreciated as well better ways to optimize the solution.
Keep a sequential list around and shuffle it. Fisher-Yates shuffle in-place is O(n). Mike Bostock suggests an implementation here. function shuffle(array) { var m = array.length, t, i; // While there remain elements to shuffle… while (m) { // Pick a remaining element… i = Math.floor(Math.random() * m--); // And swap it with the current element. t = array[m]; array[m] = array[i]; array[i] = t; } return array; } const sequence = [1,2,3,4,5,6,7,8,9] // or gen this for any length you choose let randomNonRepeatingSequence = shuffle(sequence) console.log(randomNonRepeatingSequence)
function createRandomList() { let i=0, numbers=[] while(i++<5000) numbers.push(i); numbers.sort(() => (Math.random() > .5) ? 1 : -1); return numbers } console.log(createRandomList())
Your approach has one big problem: towards the end, it will generate many random numbers which are already contained in your sequence. Consider, you already generated 4999 random numbers. Now for the last one, you only have one possibility left, but you still generate numbers in a range from 1 to 5000. So in average you'll 2500 tries to hit the correct number. Better would be, creating a sequence of your allowed elements and then shuffle this sequence. An easy possibly could be the following. let arr = [1,2,3,4 ..., 5000] for (let i = arr.length-1; i > 0; i--){ let r = Math.floor(Math.random() * (i + 1)); let x = a[i]; a[i] = a[r]; a[r] = x; } How does is work: first you initialize the array with all your allowed values. Then you pick a random index from your array and switch that with the last element of the array. In the next iteration, the range for your random index is decreased by one, and it's switched with the but-last element. And so on and so forth. Once the loop is down to 1, you have a random sequence of your allowed values.
Codefights: Correct solution but system does not accept it
Experienced codefighters, i have just started using Codefight website to learn Javascript. I have solved their task but system does not accept it. The task is to sum all integers (inidividual digit) in a number. For example sumDigit(111) = 3. What is wrong with my code? Please help me. Code function digitSum(n) { var emptyArray = []; var total = 0; var number = n.toString(); var res = number.split(""); for (var i=0; i<res.length; i++) { var numberInd = Number(res[i]); emptyArray.push(numberInd); } var finalSum = emptyArray.reduce(add,total); function add(a,b) { return a + b; } console.log(finalSum); //console.log(emptyArray); //console.log(res); }
Here's a faster trick for summing the individual digits of a number using only arithmetic: var digitSum = function(n) { var sum = 0; while (n > 0) { sum += n % 10; n = Math.floor(n / 10); } return sum; }; n % 10 is the remainder when you divide n by 10. Effectively, this retrieves the ones-digit of a number. Math.floor(n / 10) is the integer division of n by 10. You can think of it as chopping off the ones-digit of a number. That means that this code adds the ones digit to sum, chops off the ones digit (moving the tens digit down to where the ones-digit was) and repeats this process until the number is equal to zero (i.e. there are no digits left). The reason why this is more efficient than your method is that it doesn't require converting the integer to a string, which is a potentially costly operation. Since CodeFights is mainly a test of algorithmic ability, they are most likely looking for the more algorithmic answer, which is the one I explained above.
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; }
assigning x amount of random numbers to an array
I currently have 64 values (1-64) and each value returns a different outcome. I have an array setup with a range of numbers var battleships = ['1', '2', '3', '6'] which links with if ($.inArray(String($(this).data("value")), battleships) > -1) { $(this).addClass("success").removeClass("pointer"); } how would i make the array assign (for example) 26 random numbers between 1 and 64 which could then be picked up by the if statement.
You can have a function to get random numbers between min and max like this: function getRandomBetween(min, max) { return Math.random() * (max - min) + min; } And then you can loop 64 times to fill your array. for (var i = 0; i < 64; i++) { battleships.push(getRandomBetween(1, 64)); }
function getDistinctNumbers(count) { var values = []; for (var i=1; i<=64; i++) values.push(i); values.sort(function(a,b){return Math.round(Math.random() * 2) -1;}); values.length = count +1; return values; } Basically you fill an array with the values you want, shuffle it around and then reduce its length to fit your needs. If count is larger than 64, the array will be padded with undefined values. If your needs change and for some reason, the 64 gets turned into a large number, while the 24 remains relatively low, it will be faster to simply add random numbers and make sure you don't add duplicates than to sort randomly a huge array, but for now this is the fastest solution. Here is a JsBin with the code: http://jsbin.com/UwAYACe/1/edit