Generating random numbers in an array without any duplicate numbers [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm trying to create an array with random number with length of 78. I don't know how to search the entire array and check if last entry was duplicate and remove it. Someone please help.
function initAll() {
var balls = LoadInBingoBalls();
for(i=0; i < balls.length;i++)
{
(balls[i]);
}
}
function setSquare (numSquare) {
var BingoSquare = "square" + numSquare.toString();
document.getElementById(BingoSquare).innerHTML = RandomNumber(MaxNo);
}
var RandomNumber = function (max) {
return Math.floor(Math.random() * max) + 1;
}
function LoadInBingoBalls(){
var first = 0;
var last = 78;
var random;
var bag = [];
//Heres the part i get confused!
for (var i = first; i <= last; i++) {
do
bag.push(i) = setSquare(i);
while(bag.indexOf(i) !== -1)
}
return bag;
}
}

This function will create the array and check to see if it contains the number before pushing:
working example: https://jsbin.com/cabofa/1/edit?js,console
function randNum (max) {
return Math.floor(Math.random() * max) + 1;
}
function makeArray(n) {
var arr = [];
while (arr.length < n) {
var random = randNum(n);
if (arr.indexOf(random) === -1) {
arr.push(random);
}
}
return arr;
}

Create an array with all the possible values:
var possibles = [];
for(i=1; i<=78; i++) {
possibles.push(i);
}
Shuffle that array of values to be random:
function shuffle(a) {
var j, x, i;
for (i = a.length; i; i -= 1) {
j = Math.floor(Math.random() * i);
x = a[i - 1];
a[i - 1] = a[j];
a[j] = x;
}
return a;
}
var shuffled = shuffle(possibles);
Now pop a value from your new array to get a random element from it:
var popped = shuffled.pop();
console.log(popped);
You can call pop() as many times as you want until the array is empty, which will return undefined. For example:
for(i=0; i<shuffled.length; i++) {
console.log(shuffled.pop());
}

Related

Generate non-duplicate random number array JS 2nd [duplicate]

I need help with writing some code that will create a random number from an array of 12 numbers and print it 9 times without dupes. This has been tough for me to accomplish. Any ideas?
var nums = [1,2,3,4,5,6,7,8,9,10,11,12];
var gen_nums = [];
function in_array(array, el) {
for(var i = 0 ; i < array.length; i++)
if(array[i] == el) return true;
return false;
}
function get_rand(array) {
var rand = array[Math.floor(Math.random()*array.length)];
if(!in_array(gen_nums, rand)) {
gen_nums.push(rand);
return rand;
}
return get_rand(array);
}
for(var i = 0; i < 9; i++) {
console.log(get_rand(nums));
}
The most effective and efficient way to do this is to shuffle your numbers then print the first nine of them. Use a good shuffle algorithm.What Thilo suggested will give you poor results. See here.
Edit
Here's a brief Knuth Shuffle algorithm example:
void shuffle(vector<int> nums)
{
for (int i = nums.size()-1; i >= 0; i--)
{
// this line is really shorthand, but gets the point across, I hope.
swap(nums[i],nums[rand()%i]);
}
}
Try this once:
//Here o is the array;
var testArr = [6, 7, 12, 15, 17, 20, 21];
shuffle = function(o){ //v1.0
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
shuffle(testArr);
This is relatively simple to do, the theory behind it is creating another array which keeps track of which elements of the array you have used.
var tempArray = new Array(12),i,r;
for (i=0;i<9;i++)
{
r = Math.floor(Math.random()*12); // Get a random index
if (tempArray[r] === undefined) // If the index hasn't been used yet
{
document.write(numberArray[r]); // Display it
tempArray[r] = true; // Flag it as have been used
}
else // Otherwise
{
i--; // Try again
}
}
Other methods include shuffling the array, removing used elements from the array, or moving used elements to the end of the array.
If I understand you correctly, you want to shuffle your array.
Loop a couple of times (length of array should do), and in every iteration, get two random array indexes and swap the two elements there. (Update: if you are really serious about this, this may not be the best algorithm).
You can then print the first nine array elements, which will be in random order and not repeat.
Here is a generic way of getting random numbers between min and max without duplicates:
function inArray(arr, el) {
for(var i = 0 ; i < arr.length; i++)
if(arr[i] == el) return true;
return false;
}
function getRandomIntNoDuplicates(min, max, DuplicateArr) {
var RandomInt = Math.floor(Math.random() * (max - min + 1)) + min;
if (DuplicateArr.length > (max-min) ) return false; // break endless recursion
if(!inArray(DuplicateArr, RandomInt)) {
DuplicateArr.push(RandomInt);
return RandomInt;
}
return getRandomIntNoDuplicates(min, max, DuplicateArr); //recurse
}
call with:
var duplicates =[];
for (var i = 1; i <= 6 ; i++) {
console.log(getRandomIntNoDuplicates(1,10,duplicates));
}
const nums = [1,2,3,4,5,6,7,8,9,10,11,12];
for(var i = 1 ; i < 10; i++){
result = nums[Math.floor(Math.random()*nums.length)];
const index = nums.indexOf(result);
nums.splice(index, 1);
console.log(i+' - '+result);
}

Is it possible to access all elements in an Array randomly using a for loop? [duplicate]

This question already has answers here:
How to randomize (shuffle) a JavaScript array?
(69 answers)
Closed 6 years ago.
I have an array
var array = ["what","is","going","on"];
I know it's possible to access and list these elements with a standard for loop like so:
for (i = 0; i <= array.length; i++) {
console.log(array[i]);
}
But I want to know if there's a way to list these elements in a random order. I suspect that I have to use some variation of Math. but I don't have enough experience to decide which to use for sure. Thanks in advance!
You should first shuffle the array and then read one by one. An array method like Array.prototype.shuffle() might come handy.
Array.prototype.shuffle = function(){
var i = this.length,
j,
tmp;
while (i > 1) {
j = Math.floor(Math.random()*i--);
tmp = this[i];
this[i] = this[j];
this[j] = tmp;
}
return this;
};
var arr = [1,2,3,4,5].shuffle();
for(var i = 0; i < arr.length; i++) console.log(arr[i]);
Statistically speaking, this will definitely work. It just may take until the heat-death of the universe to complete.
var array = ["What", "am", "I", "doing", "with", "my", "life"];
var processed = [];
function randomAccess() {
if (processed.length === array.length) {
console.log('Done!');
return;
}
var index = Math.floor(Math.random() * array.length);
if (processed.indexOf(index) === -1) {
// Make sure we haven't processed this one before
console.log('array[' + index + ']:', array[index]);
processed.push(index);
}
// Prevent locking up the browser
setTimeout(randomAccess, 0);
}
randomAccess();
Please don't use this in production code. Theoretically, it may never complete.
Yes, you can introduce a second array to log the indices you have randomly returned - in order not to return the same index more than once.
Working example:
var myArray = ['what','is','going','on'];
var returnedIndices = [];
for (i = 0; i < myArray.length; i++) {
var randomIndex = Math.floor(Math.random() * myArray.length);
if (returnedIndices.indexOf(randomIndex) !== -1) {
i--;
continue;
}
else {
returnedIndices[i] = randomIndex;
console.log(myArray[randomIndex]);
}
}
console.log(array[Math.floor(Math.random() * (array.length - 1))]);

Count number of ocurrences in an array [duplicate]

This question already has answers here:
Counting the occurrences / frequency of array elements
(39 answers)
Closed 7 years ago.
I'm interested in finding out how many times every object in an array occurs.
Here's what I want to do mixed with some pseudo-code of what I think is the way to do it.
var myArray = [1,2,3,1,1,3,4];
for (i = 0; i < myArray.length; i++) {
if (myArray[i].AlreadyExistsInAVariable) {
var[i]+ = 1;
}
else {
CreateAnewVar();
}
}
var one = 3;
var two = 1;
var three = 2;
var four = 1;
You should use object to count the occurence of numbers in the array rather than using variables.
var myArray = [1,2,3,1,1,3,4];
var counter = {};
for (i = 0; i < myArray.length; i++) {
if (myArray.indexOf(myArray[i])>=0) {
if(!counter[myArray[i]]){
counter[myArray[i]]=1;
}
else{
counter[myArray[i]]++;
}
}
}
console.log(counter);
How about this:
var myArray = [1,2,3,1,1,3,4];
var count = myArray.reduce(function(n, val) {
return n + (val === 1);
}, 0);
console.log(count);
Edit:
For counting occurrences of every element in an array i would do something like this:
var result = {};
[1,2,3,1,1,3,4].forEach(function(e, i) {
result[e] = result[e] + 1 || 1;
});
alert(JSON.stringify(result, null, "\t"));
You can't actually just create new variable bindings like that. You can, however, dynamically add new properties to an object, which is probably a better match for this problem. Here's an example that counts up the occurrences of numbers in that array:
var myArray = [1,2,3,1,1,3,4];
var counts = myArray.reduce(function(result, item) {
result[item] || (result[item] = 0);
result[item]++;
return result;
}, {});
console.log(counts);
See it in action here: http://jsbin.com/huduroyite/edit?js,console

Object javascript error [duplicate]

This question already has an answer here:
Javascript unknown error
(1 answer)
Closed 8 years ago.
I am having a problem with my code, I have not been able to figure it out for the past 2 days.
/**
*
*///function 7
/**
* returns the number of times that pattern occurs in string
*/
function score(string,pattern) {
var v = string.toUpperCase();
var s = pattern.toUpperCase();
var result = [];
for (var i = 0; i < string.length; i++) {
var index = v.indexOf(s, i);
if (index != -1) {
result[result.length]=index;
i = index;
}
}
return result.length;
}
/**
* returns an array of records of the form {trackTitle: ..., trackLyrics: ..., trackScore: ...} derived from web.
* Each record contains the track title, track lyrics and pattern score of its corresponding content.
*
*
*
*/
//FUNCTION 9
function urlScores(music, pattern) {
var scoresArray = [];
for(var i = 0; i < music.length; i++) {
for(var j = 0; j < music[i].tracks.length; j++){
var itemScore = score(music[i].tracks[j].title, pattern) + score(music[i].tracks[j].lyrics, pattern);
if (itemScore > 0) {
scoresArray[scoresArray.length] = ({indexOfTrack: j, trackTitle: music[i].tracks[j].title, trackLyrics: music[i].tracks[j].lyrics, trackScore: itemScore, album: music[i]});
}
itemScore = 0;
}
}
return scoresArray;
}
/**
* Sorts the result of urlScores() into descending order.
* Records with a score of zero are omitted.
*/
//FUNCTION 10
function rankedScores(music, pattern) {
var scoresArray = urlScores(music, pattern);
function swap(a, b) {
var temp = scoresArray[a];
scoresArray[a] = scoresArray[b];
scoresArray[b] = temp;
}
for(var i = 0; i < scoresArray.length; i++) {
for(var x = 0; x < scoresArray.length - 1; x++) {
if (scoresArray[x].score > scoresArray[x + 1].score) {
swap(x, x + 1);
}
}
}
alert(scoresArray);
}
When I run it with the following:
rankedScores(albums, "sparrow");
The albums variable is - http://pastebin.com/G25SxrwY
The error is the following -
[object Object],[object Object]
Thank you very much!
This line:
alert(scoresArray);
No good. You are telling the alert() to output a whole array, but it doesn't know how to output a whole array.
Create a loop to loop through scoresArray and output it that way.

Random number generator without dupes in Javascript?

I need help with writing some code that will create a random number from an array of 12 numbers and print it 9 times without dupes. This has been tough for me to accomplish. Any ideas?
var nums = [1,2,3,4,5,6,7,8,9,10,11,12];
var gen_nums = [];
function in_array(array, el) {
for(var i = 0 ; i < array.length; i++)
if(array[i] == el) return true;
return false;
}
function get_rand(array) {
var rand = array[Math.floor(Math.random()*array.length)];
if(!in_array(gen_nums, rand)) {
gen_nums.push(rand);
return rand;
}
return get_rand(array);
}
for(var i = 0; i < 9; i++) {
console.log(get_rand(nums));
}
The most effective and efficient way to do this is to shuffle your numbers then print the first nine of them. Use a good shuffle algorithm.What Thilo suggested will give you poor results. See here.
Edit
Here's a brief Knuth Shuffle algorithm example:
void shuffle(vector<int> nums)
{
for (int i = nums.size()-1; i >= 0; i--)
{
// this line is really shorthand, but gets the point across, I hope.
swap(nums[i],nums[rand()%i]);
}
}
Try this once:
//Here o is the array;
var testArr = [6, 7, 12, 15, 17, 20, 21];
shuffle = function(o){ //v1.0
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
shuffle(testArr);
This is relatively simple to do, the theory behind it is creating another array which keeps track of which elements of the array you have used.
var tempArray = new Array(12),i,r;
for (i=0;i<9;i++)
{
r = Math.floor(Math.random()*12); // Get a random index
if (tempArray[r] === undefined) // If the index hasn't been used yet
{
document.write(numberArray[r]); // Display it
tempArray[r] = true; // Flag it as have been used
}
else // Otherwise
{
i--; // Try again
}
}
Other methods include shuffling the array, removing used elements from the array, or moving used elements to the end of the array.
If I understand you correctly, you want to shuffle your array.
Loop a couple of times (length of array should do), and in every iteration, get two random array indexes and swap the two elements there. (Update: if you are really serious about this, this may not be the best algorithm).
You can then print the first nine array elements, which will be in random order and not repeat.
Here is a generic way of getting random numbers between min and max without duplicates:
function inArray(arr, el) {
for(var i = 0 ; i < arr.length; i++)
if(arr[i] == el) return true;
return false;
}
function getRandomIntNoDuplicates(min, max, DuplicateArr) {
var RandomInt = Math.floor(Math.random() * (max - min + 1)) + min;
if (DuplicateArr.length > (max-min) ) return false; // break endless recursion
if(!inArray(DuplicateArr, RandomInt)) {
DuplicateArr.push(RandomInt);
return RandomInt;
}
return getRandomIntNoDuplicates(min, max, DuplicateArr); //recurse
}
call with:
var duplicates =[];
for (var i = 1; i <= 6 ; i++) {
console.log(getRandomIntNoDuplicates(1,10,duplicates));
}
const nums = [1,2,3,4,5,6,7,8,9,10,11,12];
for(var i = 1 ; i < 10; i++){
result = nums[Math.floor(Math.random()*nums.length)];
const index = nums.indexOf(result);
nums.splice(index, 1);
console.log(i+' - '+result);
}

Categories

Resources