Edited: New to coding. I’m copying and adjusting code from a simple JavaScript project, and here is the for loop I need to modify:
randomize(ShipClass = Ship) {
this.removeAllShips();
for (let size = 5; size >=2; size--) {
for (let n = 0; n < 6 - size; n++) {
const direction = getRandomFrom("row", "column");
const ship = new ShipClass(size, direction);
while (!ship.placed) {
const x = getRandomBetween(0, 9);
const y = getRandomBetween(0, 9);
this.removeShip(ship);
this.addShip(ship, x, y);
}
}
It randomly places 10 ships with the following sizes: {2,2,2,2,3,3,3,4,4,5}.
I need to modify it so that it places only 5 ships with the following sizes: {2,3,3,4,5}.
Just loop over your desired sizes array with a for..of loop:
randomize(ShipClass = Ship) {
this.removeAllShips();
for (let size of [2, 3, 3, 4, 5]) {
const direction = getRandomFrom("row", "column");
const ship = new ShipClass(size, direction);
while (!ship.placed) {
const x = getRandomBetween(0, 9);
const y = getRandomBetween(0, 9);
this.removeShip(ship);
this.addShip(ship, x, y);
}
}
}