This question already has answers here:
How can I shuffle an array? [duplicate]
(2 answers)
Closed 8 years ago.
My exact requirement is to return all numbers from 1 to 2000 randomly and shouldn't repeat a number twice. So we can say if i have
function generateRnNumber(){
var arr = [1,2,3,4,5,6,7,8,9,10,...2000];
randomNumber = Math.floor((Math.random()*2000));
return randomNUmber;
}
So if i call generateRnNumber a number between 1 - 2000 which is not returned before, or a unique number so if i call 2000 times i should get all the numbers but in random order. I don't want to keep an array with 2000 elements. Please help me in writing this function.
Keep an array with all possible values and randomize the order. When you need a random value, pop the array (removing the value the "possible values"-array).
To do this otherwise, you would anyway need an array to hold the "taken" values so i don't think you can get around keeping an array of the size of your "value range".
You can shuffle the array like this:
function shuffle(o){
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
usage:
var myArray = [];
for(var i = 1; i <= 2000; i++) {
myArray.push(i);
}
var randomArray = shuffle(myArray).splice(0, 10); // an array with 10 random numbers varrying from 1-2000
source: How can I shuffle an array?
Related
This question already has answers here:
How to add same elements to javascript array n times
(4 answers)
Closed 4 years ago.
I've been trying to figure this problem out for a while but I'm at a blank. Here's what I have so far:
var repeatNumbers = function(data) {
var repeated = [];
for ( var x = 0; x < data.length; x++){
var unit = data[x][0]
var quant = data[x][1]
for(var i = quant; i > 0; i--){
repeated.push(unit);
repeated.join(',');
}
return repeated;
}
};
console.log(repeatNumbers([1, 10]));
Basically I'm trying to repeat the first number of the array based off of the second value. Any insight would be greatly appreciated thank you! :)
You don't need to loop over your array if you only have two numbers, where the first number (at index 0) is the number you want to repeat, and the second number is the number of times you want to repeat that number (index 1).
Once you have the number of times you wish to repeat the number, you can simply use a for loop to enter the number into your repeated array that number of times.
See working example below (read code comments for further explanation):
var repeatNumbers = function(data) {
var repeated = []
var toRepeat = data[0]; // get the first number in the array
var times = data[1]; // get the second number in the array
// loop the number of times you want to repeat the number:
for(var i = 0; i < times; i++) {
repeated.push(toRepeat); // push the number you wish to repeat into the repeated array
}
return repeated.join(); // return the joined array (as a string - separated by commas)
}
console.log(repeatNumbers([1, 10]));
If I understand your question correctly, you want the function repeatNumbers() to return an array with the first element in the passed array replicated by the second element in the passed array.
To achieve that, you could do the following:
var repeatNumbers = function(data) {
// Extract the "value" to be repeated, and the "repeated" value
// that will control the number of "value" items in result array
var value = data[0];
var repeated = data[1];
var result = []
// Loop over repeated range, and push value into the result array
for (var i = 0; i < repeated; i++) {
result.push(value);
}
// Result result array
return result;
};
console.log(repeatNumbers([1, 10]));
Or, if you don't need to support IE, a more consise approach would be:
var repeatNumbers = function(data) {
var value = data[0];
var repeated = data[1];
return (new Array(repeated).fill(value));
};
console.log(repeatNumbers([1, 10]));
I am wanting to generate a random number between 1-100, but I am only wanting to generate those numbers once each time. I have a loop that runs 3 times to run the .Math and then push that into an array. But I dont want the situation where it generates the same number more than once.
I have put 21 in the allAnswers[] array as that is something that will stay consistent. Is there a way to generate and then check that array if that number exists and then run the .math again?
function buttonGenerator(){
var allAnswers = [21],
randomizer = [];
// Generates 3 random answers
for(a = 0 ; a < 3; a++) {
wrongAnswers = Math.floor((Math.random() * 100) + 1);
allAnswers.push(wrongAnswers);
}
// Generates random buttons while inputting the correct and incorrect answers randomly
for(i = 0 ; i < 4; i++) {
var buttonArea = $("#answerOptions");
input = $('<button class="col-xs-6 btn btn-primary"></button>');
input.appendTo(buttonArea);
}
shuffle(allAnswers);
console.log(allAnswers);
}
buttonGenerator();
Use indexOf to check if the array has the value before pushing:
if (allAnswers.indexOf(wrongAnswers) === -1) {
allAnswers.push(wrongAnswers);
}
This question already has answers here:
Split array into chunks
(73 answers)
Closed 8 years ago.
I am new to javascript. I have a list of 500 or more items. I need split this array into sub arrays each containing 20 items. i.e 25 arrays if there are exactly 500 items and each array containing 20 items. I created 25 arrays like below:
var firstSet=[];
var secondSet=[];
.....
And i populate each of this array using the for loop. In javascript how can I make it programmatically since the main list can return more than 500 items in future and each sub array should be configured for more than 20 items in future. What is the best solution to fix this situation?
As comments say, you should split it with a 2 dimentional array:
var mainArray=[1,2,3,4,5,6,7,8,9,10];
function splitArray(arr,qty){
var mainArr=[], subarr=[];
for(var i=0;i<arr.length;i++){
subarr.push(arr[i]);
if( ((i+1) % qty == 0) || i+1==arr.length){
mainArr.push(subarr);
subarr=[];
}
}
return mainArr;
}
console.log(splitArray(mainArray,2));
This creates 1 array with 5 indexes. In each index, you have an array of 2 elements. So it groups it in [1,2], [3,4], [5,6], [7,8], [9,10]
Use nested loops to create a 2-dimensional array from the original data.
var sets = [];
var items_per_set = 20;
for (var i = 0, outer = 0; i < list.length; i += items_per_set, outer++) {
sets[outer] = [];
var limit = Math.min(list.length, i+items_per_set);
for (j = i; j < limit; j++) {
sets[outer].push(list[j]);
}
}
This question already has answers here:
How to randomize (shuffle) a JavaScript array?
(69 answers)
Closed 9 years ago.
I am trying to make a script which is outputting every number from 1-10.
Using a random number generator, in JavaScript.
I want every number to be unique.
Here is an example of what i would like the script to output:
5 9 7 6 1 3 4 8 2 10
This is my attempt:
var test = [];
var amountOfNumbers = 10;
var inArray = false;
var useNumbers = [];
for(var i=0; useNumbers.length<=amountOfNumbers; i++){
var rng = Math.floor((Math.random()*amountOfNumbers)+1);
for(var a=0; a<=test.length; a++){
if(rng == test[a]){
inArray == true;
}
}
if(!inArray){
document.write(rng);
test.push(rng);
useNumbers.push(rng);
}
}
Hope you can help.
for the record I am not interested in jQuery og any other library :)
1) How to fix your code
You have a few errors, among them the fact you don't reset inArray to false and that you don't iterate over the whole test array (use <, not <=). But using a loop to see if you already have the number isn't efficient, it's better to use an object as a map :
var test = [];
var amountOfNumbers = 10;
var useNumbers = {};
for(var i=0; test.length<amountOfNumbers; i++){
var rng = Math.floor((Math.random()*amountOfNumbers)+1);
if(!useNumbers[rng]){
document.write(rng);
test.push(rng);
useNumbers[rng] = true;
}
}
2) How to do it properly
Your algorithm will loop until it is lucky enough to find the remaining numbers. This isn't efficient and isn't predictable. The normal reliable practice is
to generate the array [1..10]
to shuffle it
Generating an array of the integers from 1 to N can be done with a simple loop or in a fancier way :
var arr = Array.apply(0,new Array(N)).map(function(_,i){ return i+1 });
Shuffling an array is usually done with the Fisher-Yates algorithm, for which you'll easily find JS implementations (it's easy to write anyway). A fast (theoretically not guaranteed to work with all future sort implementations) alternative is this one :
arr = arr.sort(function(a,b){ return Math.random()>0.5 });
The whole program
Your approach means to check over all the array in each step, looking if your random number is already inside the array, which means a lot lost time.
Best approach is disordering an ordered array. In each loop, we generate a random number (in the example, a number between 0 and 1) and with a 50% probability we change the item in the current position for other item in a random position (between 0 and the length of the array).
Hope it helps.
function disorder(arg) {
for (var i = 0; i < arg.length; i++) {
if (Math.random() < 0.5) {
var aux = arg[i];
var rndPos = Math.floor(Math.random()) * arg.length;
arg[i] = arg[rndPos];
arg[rndPos] = aux;
}
}
return arg;
}
var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var myNewArray = disorder(myArray);
myNewArray.forEach(function(item) {
console.log(item);
});
I have:
function getRandomInt(min, max){
return Math.floor(Math.random() * (max - min + 1)) + min;
}
But the problem is I want randomise the population of something with elements in an array (so they do not appear in the same order every time in the thing I am populating) so I need to ensure the number returned is unique compared to the other numbers so far.
So instead of:
for(var i = 0; i < myArray.length; i++) {
}
I have:
var i;
var count = 0;
while(count < myArray.length){
count++;
i = getRandomInt(0, myArray.length); // TODO ensure value is unique
// do stuff with myArray[i];
}
It looks like rather than independent uniform random numbers you rather want a random permutation of the set {1, 2, 3, ..., N}. I think there's a shuffle method for arrays that will do that for you.
As requested, here's the code example:
function shuffle(array) {
var top = array.length;
while (top--) {
var current = Math.floor(Math.random() * top);
var tmp = array[current];
array[current] = array[top - 1];
array[top - 1] = tmp;
}
return array;
}
Sometimes the best way to randomize something (say a card deck) is to not shuffle it before pulling it out, but to shuffle it as you pull it out.
Say you have:
var i,
endNum = 51,
array = new Array(52);
for(i = 0; i <= endNum; i++) {
array[i] = i;
}
Then you can write a function like this:
function drawNumber() {
// set index to draw from
var swap,
drawIndex = Math.floor(Math.random() * (endNum+ 1));
// swap the values at the drawn index and at the "end" of the deck
swap = array[drawIndex];
array[drawIndex] = array[endNum];
array[endNum] = swap;
endNum--;
}
Since I decrement the end counter the drawn items will be "discarded" at the end of the stack and the randomize function will only treat the items from 0 to end as viable.
This is a common pattern I've used, I may have adopted it into js incorrectly since the last time I used it was for writing a simple card game in c#. In fact I just looked at it and I had int ____ instead of var ____ lol
If i understand well, you want an array of integers but sorted randomly.
A way to do it is described here
First create a rand function :
function randOrd(){
return (Math.round(Math.random())-0.5); }
Then, randomize your array. The following example shows how:
anyArray = new Array('1','2','3','4','5');
anyArray.sort( randOrd );
document.write('Random : ' + anyArray + '<br />';);
Hope that will help,
Regards,
Max
You can pass in a function to the Array.Sort method. If this function returns a value that is randomly above or below zero then your array will be randomly sorted.
myarray.sort(function() {return 0.5 - Math.random()})
should do the trick for you without you having to worry about whether or not every random number is unique.
No loops and very simple.