Home > other >  How to create a random grid 3x3 of 3 different arrays in Javascript?
How to create a random grid 3x3 of 3 different arrays in Javascript?

Time:10-15

I am working on a javaScript project and I am supposed to create a 3x3 grid using 3 different arrays (each one of them should have its own random order) and the print the result by using a class method.Is there a way to randomize each arrays class instance ? See code below:

const my_arr = ['^', 'O', '░', '*'];

let field = []

for (let i = 0; i < my_arr.length; i  ) {
  const randomIndex1 = Math.floor(Math.random() * 3);
  field.push(my_arr[Math.floor(Math.random() * 3)])
  //
  //field.push(my_arr[randomIndex])
}

//console.log(field)


class Field {
  constructor(field) {
    this.field = field.reverse();
  }
  print() {
    console.log(this.field.join(''))
  }
}


const myField1 = new Field([field])
const myField2 = new Field([field])
const myField3 = new Field([field])

console.log(`${myField1.print()}\n${myField2.print()}\n${myField3.print()}`)

Any help is greatly appreciated.

CodePudding user response:

You're not randomizing the array for each Field. You're initializing field once, and then passing that to the constructor, so all 3 Fields have the same array values. If you move the field generating/randomizing logic to a callable function, you can generate a new array for each Field.

print() is doing console.log, and you're calling it by doing console.log(myField1.print());, so it's essentially doing console.log(console.log(myField1.print()));.

So you can change print() to just return the joined array, and then the single console.log at the bottom of your script works as expected.

Lastly, you were passing [field] to the constructor like const myField1 = new Field([field]), but that's passing an array of arrays ([field] vs field).

const my_arr = ['^', 'O', '░', '*'];
  
function generateRandomArray() {
  let field = []

  for (let i = 0; i < my_arr.length; i  ) {
    const randomIndex1 = Math.floor(Math.random() * 3);
    field.push(my_arr[Math.floor(Math.random() * 3)])
  }
  
  return field;
}


class Field {
  constructor(field) {
    this.field = field.reverse();
  }
  print() {
    return this.field.join('');
  }
}


const myField1 = new Field(generateRandomArray())
const myField2 = new Field(generateRandomArray())
const myField3 = new Field(generateRandomArray())

console.log(`${myField1.print()}\n${myField2.print()}\n${myField3.print()}`)

CodePudding user response:

You could use the array's sort method with Math.random to shuffle the values:

function randomizeArray(arr) {
  return [...arr].sort(() => Math.random() - 0.5)
}

const arr = ['^', 'O', '░', '*'];

console.log(randomizeArray(arr).join());
console.log(randomizeArray(arr).join());
console.log(randomizeArray(arr).join());

The randomizeArray function above does the following:

  1. creates a copy of the array via spread [...arr] because we want it to be independent, unaffected by other manipulations to the source array.
  2. "sorts" the array randomly via sort(() => Math.random() - 0.5). Sort functions return a positive number, negative number, or zero to indicate whether an item should be before, after, or equal to another. Generating a random number between 0 and 1 and subtracting 0.5 gives us an (approximately) even distribution of positive and negative numbers.
  • Related