How to choose pseudo-random values in an array javascript [duplicate] - javascript

This question already has answers here:
Generate unique number within range (0 - X), keeping a history to prevent duplicates
(4 answers)
Closed 7 years ago.
I know how to sort through an array like this
var rand = myArray[Math.floor(Math.random() * myArray.length)];
but what I am trying to do is use this in a loop to pick values from my array that I haven't picked with this function before.
In other words, let's say my array contains apples, bananas, and oranges. i want to be able to pick all three of those out randomly, but I don't want to pick able to pick out the same one more than once.(I hope this made sense)

You can remove the item from the array, so it will not be selected again
var rand = myArray.length ? myArray.splice(Math.floor(Math.random() * myArray.length), 1)[0] : undefined;
Demo: Fiddle
Note: It will modify the original array, so if you want to keep the original array as it was you need to keep a different copy

Related

Why do multiple calls of Array.fill effect unreferenced arrays? [duplicate]

This question already has answers here:
Array.prototype.fill() different from fill as I go [duplicate]
(1 answer)
Unexpected behavior using Array Map on an Array Initialized with Array Fill [duplicate]
(1 answer)
Closed 2 years ago.
Playing around with different ways of instantiating Arrays with Javascript and I noticed some interesting behavior:
matrix = Array(3).fill(Array(3).fill(0))
Creates an NxN matrix of 0 values
[
[0,0,0],
[0,0,0],
[0,0,0]
]
I then tried changing the first row of the matrix to be all 1's:
matrix[0].fill(1)
Which for some reason turned ALL values in the matrix to 1's:
[
[1,1,1],
[1,1,1],
[1,1,1]
]
This behavior doesn't make sense to me. Shouldn't only the first row be affected by the final call to Array.fill? What's going on here?
Your code is equivalent to
let row = [0,0,0]
let matrix = [row, row, row];
row.fill(1);
because .fill(Array(3).fill(0)) calls Array(3).fill(0) once to get the fill value - if the fill argument were a callback, then it would call it for each item in matrix - but the fill argument is a value
In javascript, arrays are said to be a reference
var a = [1,2,3], b=a;
b[0] = 4
will result in both a and b referencing an array with values [4,2,3]
so, since each row is the same array, your result is as you've seen
try this instead
const matrix = Array.from({length:3}, () => Array(3).fill(0))
matrix[0].fill(1);
console.log(matrix);
The above is equivalent to
const matrix = [Array(3).fill(0), Array(3).fill(0), Array(3).fill(0)];
matrix[0].fill(1);
Now each entry in matrix is a different Array, not the same one each time

functional loop given a number instead of an array [duplicate]

This question already has answers here:
Tersest way to create an array of integers from 1..20 in JavaScript
(16 answers)
Closed 6 years ago.
The community reviewed whether to reopen this question 2 months ago and left it closed:
Original close reason(s) were not resolved
Say I have a number 18, instead of an array, in hand.
What is the best way to create a functional loop in JS given a number X instead of array of X elements?
I can do this:
[1,2,3].forEach(function(){
));
but if I have the number 3
I can do
for(var i = 0; i < 3; i++){
}
but I want that loop to be functional instead
If you have a number and you want to create a loop then you can use the number in limiter condition in the for loop.
for(var i = 0; i < number; i++)
Edit 1: you can use foreach on arrays only, in that case since you have a number already you can create a array of that length and then use the foreach on it.
var foo = new Array(number).fill(0);
foo.foreach()
Also another option is
var N = 18;
Array.apply(null, {length: N}).map(Number.call, Number)
result [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]
Many more options available in this thread Create a JavaScript array containing 1...N
I don't understand why you want to do this. An equivalent to:
[1,2,3].forEach(function(){ ... ));
Is
var limit = n;
while (--limit) {( // Note: 0 is falsy
function(){ ... }
)(limit);}
Or if you really want to use an array structure, the following will do:
new Array(limit).fill(0).forEach(function(){...});
You might be interested in Myth of the Day: Functional Programmers Don't Use Loops.
Per this question, you can "functionally" iterate over a linear sequence relatively easily using:
Array.apply(null, Array(number)).map(function () {}).forEach(...)
Not sure what advantage this gives you versus a regular for-loop with an index, though it is a neat trick.

how to print unordered list in javascript?

I have one Question
Write a Javascript code to store a list of strings/sort it and print it in an unordered list
could you please tell me how to print unordered list in javascript ?
I do like this use Math.random function but it is not printing the value
var arr=['abc','pqr','mnc'];
for(var i=0;i<arr.length;i++){
console.log(arr[Math.floor((Math.random() * 3) + 1)]) ;
}
http://jsfiddle.net/3s4Lqr0o/1/
It is not printing the all values?
The first problem here is that Math.floor((Math.random() * 3) + 1) will return a number between 1 to 3. Your array only has elements at index 0, 1, and 2. So abc won't be printed at all.
The second problem is, there is no guarantee that your calculation will return every single number 0, 1 and 2 exactly once. You could be getting arr[1] three times in a row, resulting in pqr being printed 3 times.
I initially voted to mark this question as a duplicate of How to randomize (shuffle) a JavaScript array?. My thought was that you can simply shuffle the array, then print the shuffled array. However, since this question has been reopened, I will propose an alternate solution.
arr = ['abc','pqr','mnc'];
while (arr.length > 0) {
var index = Math.floor(Math.random() * arr.length);
console.log(arr[index]);
arr.splice(index, 1);
}
Randomly select one element in the array, print it and then remove it from the array. Repeat until there are no more elements.

Random Selections from Arrays

I am creating a game in Unity. I'm in the planning stage of it right now, but I'm trying to work out a problem I've come to. The game involves randomly selected objects from three different categories falling and the player has to catch the particular objects in particular bins.
So here's what needs to happen:
One or two of the arrays must be randomly chosen, one or two of the objects within that particular array must be chosen, no more than four objects can fall at once, the different objects must fall from different places and fall at different times.
Now I have a clip of code that I got from another project I did that's written in JavaScript (which is what I've been using, but I could also do it in Boo or C++) that solves part of the last point. It chooses a random location along the x access and then has the object fall until y=0, and then it resets.
function Update()
{
transform.position.y -= 50 * Time.deltaTime;
if(transform.position.y < 0)
{
transform.position.y = 50;
transform.position.x = Random.Range(0,60);
transform.position.z = -16;
}
}
I'm going to rewrite part of it to say that it will reset after it hits a particular collider, yields for a short time period, and find then a new random and drop that instead. But what I'm having problems with is the actual randomizing of the objects. I have six objects in each of the three arrays, and I've looked for codes where something is chosen from an array by numerical value, but nothing about randomly choosing one of the arrays and then choosing something within the random array. Neither have I found anything about the random selection in JavaScript, Boo, or C++.
Any information on this code would be helpful, thanks in advance!
To select one object at random from one of three arrays at random, you better work with an array of array. You then will need to generate two random numbers and store them as indexes to the array of arrays.
so instead of three different arrays, initialize a single array
var a = [];
a.push([1,2,3]);
a.push([10,20]);
a.push([100,200,300,400]);
and then
var i = Math.floor(Math.random()*a.length);
var j = Math.floor(Math.random()*a[i].length);
var o = a[i][j];

Javascript mix numbers randomly [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to randomize a javascript array?
Hello guys I know how to generate a random value with Math.random() in Javascript, but can you tell me how to mix numbers randomly?
For example I have numbers 1,2,3,4,5,6,7,8,9,10 how to mix it randmoly like this: 2,8,9,1... so each number should be used only once
You could do this by putting them all in an array and sort that array in a random fashion.
var nrs = [1,2,3,4,5,6,7,8,9,10];
nrs.sort(function(a,b){
return Math.floor(Math.random()*3 - 1);
});
var nums = [1,2,3,4,5,6,7,8,9,10], numsMixed = [];
while(nums.length){
numsMixed = numsMixed.concat(nums.splice((Math.random() * nums.length), 1));
}
console.log(numsMixed);

Categories