How to create multiple arrays of random numbers in js? - javascript

I am attempting to create a matrix of 3 arrays with 10 elements in each array. Each element should be a random number between 1 and 10. I wanted to use a single function to generate each of the arrays, and used this:
var array1 = [];
var array2 = [];
var array3 = [];
var tempName;
function fcnArrayGenerate(){
let i = 1;
while (i < 4){
tempName = "array" + i;
let j = 0;
while (j < 10){
tempName.push((Math.floor(Math.random() * 10) + 1));
j++;
}
i++;
}
console.log(array1);
console.log(array2);
console.log(array3);
}
However, when I run the function, I receive an error stating that "tempName.push is not a function." Any assistance on how to correct this would be appreciated. Thank you.

Instead of using three variables for three different arrays, you can use a single multidimensional array to store those three arrays.
let array = [[], [], []];
function fcnArrayGenerate() {
let i = 0;
while (i <= 2) {
let j = 0;
while (j < 10) {
array[i].push(Math.floor(Math.random() * 10) + 1);
j++;
}
i++;
}
}
// call the function
fcnArrayGenerate();
// now print the arrays as tables
console.table(array);
console.table(array[0]);
console.table(array[1]);
console.table(array[2]);
Note: console.table() allows you to print out arrays and objects to the console in tabular form.

If you want to push into tempName you have to initialise it with an empty array first. Right now it’s undefined. Hence you’re seeing the error as you can’t push something to undefined
Do this:
var tempName = []

To make variable names incremental, you can pass them as objects.
var data = {
array1: [],
array2: [],
array3: []
}
function fcnArrayGenerate(){
let i = 1;
while (i < 4){
let j = 0;
while (j < 10){
data['array' + i].push((Math.floor(Math.random() * 10) + 1));
j++;
}
i++;
}
console.log(data.array1);
console.log(data.array2);
console.log(data.array3);
}
fcnArrayGenerate();

Related

How to create javascript array when each element is a pair of objects

hello I would like to build an array that every element will be a pair of objects , Something like this
var Shelves = new arr[][]
var books = new Books[] ;
Shelves[book[i],book[j=i+1]],[book[i+1],book[j=i+1]] and so on......;
I mean that I understand how to go with a for loop and to get the elements 'but how to push them in pairs array? arr.push doesn't work :(
build1ArrPairs(1Arr) {
if (1Arr != undefined || 1Arr!=null) {
for (var i = 0; i < 1Arr.length; i = i + 1) {
for (var j = i + 1; j <= 1Arr.length; j++) {
this.1ArrPair.push(1Arr[i] 1Arr[j]);
break;
}
}
}
}
Thanks :)
Alternatively, you can use array#reduce to group your array.
var names = ['a', 'b','c','d','e'];
var result = names.reduce((r,w,i) => {
let index = Math.floor(i/2);
if(!Array.isArray(r[index]))
r[index] = [];
r[index].push(w);
return r;
},[]);
console.log(result);
First of all, variables names can't start with a number.
Second, initialize an array, then add your elements - two at a time - and return the array:
var ans = [];
if (Arr != undefined || Arr != null) {
for (var i=0; i<(Arr.length-1); i+=2) { // Note the loop stops 2 elements before the last one
ans.push([Arr[i], Arr[i+1]]);
// ^ Note the comma - it's missing in your code
}
}
return ans;

Shorcut to storing incremented values in array?

this is my code currently:
let array = [`1 (1).jgp`,`1 (2).jgp`,`1 (3).jgp`,`1 (4).jgp`,`1 (5).jgp`,`1 (6).jgp`,`1 (7).jgp`,`1 (8).jgp`,`1 (9).jgp`,`1 (10).jgp`,`1 (11).jgp`]
//rest of the code
Is there a more efficent way of storing the data?
I have tried:
for (i = 0; i < 12; i++) {
let array = [`1`+(i)+`.jgp`]
};
//rest of the code
But, then when I tried to call array it returned:
Uncaught ReferenceError: array is not defined
at :1:1
I also tried:
let array = [`1`+(i = 0; i < 12; i++)+`.jgp`]
//rest of the code
But that returned: Uncaught SyntaxError: Unexpected token ;
Please let me know what I'm doing wrong? Or how I can make this code more efficient.
Thanks,
You can generate the array using Array#from:
const arr = Array.from({ length: 10 }, (_, i) => `1 (${i + 1}).jgp`);
console.log(arr);
Although a simple for loop would work as well:
const array = []; // declare an empty array
for (let i = 1; i <= 10; i++) {
array.push(`1 (${i}).jgp`); // push each item to the array
};
console.log(array);
Is there a more efficent way of storing the data?
You mean store in such a way that less storage is required?
Store in this format
var arrayObj = {
template : "{{i}} ({{i}}).jgp",
startIndex : 1,
endIndex : 10
};
Or how I can make this code more efficient.
If how much storage is used is not the concern, then simply use a simple iterator
var array = [];
for( var counter = 1; counter <= 10; counter++ )
{
array.push( "1 ( " + counter + " ).jgp" );
}
You can do
let array = [];
for (let i = 0; i < 12; i++) {
array.push(`1 (`+i+`).jgp`);
};
console.log(array);

Shuffle content of two json files in Vue.js

I have two json files, list1.json and list2.json and I managed to concat them, but I have two roles:
Resulting list should contain only 10 random items from list1.json, all the items from list2.json, and then I should display them in random order on the page.
How can I do that?
You can use lodash for this task.
_.sampleSize(list1.json, 10) will give you ten random items,
then _.concat(_.sampleSize(list1.json, 10), list2.json) will give you the desired result.
After you have a list containing the desired items, you can randomize its order by using the _.shuffle function.
You can read a bit more here:
https://lodash.com/docs#sampleSize and https://lodash.com/docs#concat
Off course both these functions work on JavaScript Arrays and not files, you would have to read/require these files and parse them first.
Solution with plain javascript (but I suggest too going with underscore or lodash as Gilad Artzi says).
function array_random_idx(arr) {
var idx = parseInt(Math.random() * arr.length);
return idx;
}
function remove_random(arr) {
var idx = array_random_idx(arr);
return arr.splice(idx, 1)[0];
}
function array_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;
}
}
var result1 = []
for (var i = 0; i < 10; i++) {
var elem = remove_random(list1.json);
result1.push(elem);
}
var result = result1.concat(list2.json);
array_shuffle(result);
console.log(result);

printing array in rows javascript

I have an array of 100 random numbers between 1 and 49.
I would like to print out the array in rows of twelve elements, instead of printing the array in a single line.
Here is the code I have
<script type ="text/javascript">
var arr = [];
for (var i = 0, l = 100; i < l; i++) {
arr.push(Math.round(Math.random() * 49)+1)
}
document.write(arr);
document.write("\n");
</script>
I need to print the array in rows with 12 elements per row and also need to find the smallest element in the array.
You could try using splice:
while (arr.length > 0) {
document.write(arr.splice(0, 12))
}
However, after running that code the array will be []. If you don't want to modify the array, use slice instead:
for (var i = 0; i < arr.length; i += 12) {
document.write(arr.slice(i, i + 12))
}
This would be the conventional way of doing it. The array is reset however. Let us know more detail on your requirements.
var arr = [];
function getRandom( num ){
return Math.round(Math.random() * num)+1;
}
var counter = 0;
for (var i = 0; i < 100; i++) {
arr.push(getRandom( 49 ));
counter++;
if( counter >= 12 ){
document.write(arr);
document.write("<br/>");
arr = [];
counter = 0;
}
}

How to efficiently build a random list from a given list without recurrences in JS?

I have a comma separated string, out of which I need to create a new string which contains a random order of the items in the original string, while making sure there are no recurrences.
For example:
Running 1,2,3,1,3 will give 2,3,1 and another time 3,1,2, and so on.
I have a code which picks a random item in the original string, and then iterates over the new string to see if it does not exist already. If it does not exist - the item is inserted.
However, I have a feeling this can be improved (in C# I would have used a hashtable, instead of iterating every time on the new array). One improvement can be removing the item we inserted from the original array, in order to prevent cases where the random number will give us the same result, for example.
I'd be happy if you could suggest improvements to the code below.
originalArray = originalList.split(',');
for (var j = 0; j < originalArray.length; j++) {
var iPlaceInOriginalArray = Math.round(Math.random() * (originalArray.length - 1));
var bAlreadyExists = false;
for (var i = 0; i < newArray.length; i++) {
if (newArray[i].toString() == originalArray[iPlaceInOriginalArray].toString()) {
bAlreadyExists = true;
break;
}
}
if (!bAlreadyExists)
newArray.push(originalArray[iPlaceInOriginalArray]);
}
Thanks!
You can still use a 'hash' in javascript to remove duplicates. Only in JS they're called objects:
function removeDuplicates(arr) {
var hash = {};
for (var i=0,l=arr.length;i<l;i++) {
hash[arr[i]] = 1;
}
// now extract hash keys... ahem...
// I mean object members:
arr = [];
for (var n in hash) {
arr.push(n);
}
return arr;
}
Oh, and the select random from an array thing. If it's ok to destroy the original array (which in your case it is) then use splice:
function randInt (n) {return Math.floor(Math.random()*n)}
function shuffle (arr) {
var out = [];
while (arr.length) {
out.push(
arr.splice(
randInt(arr.length),1 ));
}
return out;
}
// So:
newArray = shuffle(
removeDuplicates(
string.split(',') ));
// If you sort the first array, it is quicker to skip duplicates, and you can splice each unique item into its random position as you build the new array.
var s= 'Function,String,Object,String,Array,Date,Error,String,String,'+
'Math,Number,RegExp,Group,Collection,Timelog,Color,String';
var A1= s.split(',').sort(), A2= [], tem;
while(A1.length){
tem= A1.shift();
while(A1[0]== tem) tem= A1.shift();
if(tem) A2.splice(Math.floor(Math.random()*A2.length), 0, tem);
}
alert(A2.join(', '))
With your solution, you are not guaranteed not to pick same number several times, thus leaving some others of them never being picked. If the number of elements is not big (up to 100), deleting items from the source array will give the best result.
Edit
originalArray = originalList.split(',');
for (var j = 0; j < originalArray.length; j++) {
var iPlaceInOriginalArray = Math.round(Math.random() * (originalArray.length - 1 - j));
var bAlreadyExists = false;
for (var i = 0; i < newArray.length; i++) {
if (newArray[i].toString() == originalArray[iPlaceInOriginalArray].toString()) {
bAlreadyExists = true;
break;
}
}
var tmp = originalArray[originalArray.length - 1 - j];
originalArray[originalArray.Length - 1 - j] = originalArray[iPlaceInOriginalArray];
originalArray[iPlaceInOriginalArray] = tmp;
if (!bAlreadyExists)
newArray.push(originalArray[iPlaceInOriginalArray]);
}

Categories

Resources