Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

158
Vistas
Get random number of colors from a list instead of 8

I am experimenting on particles and I have set a list of 8 colors that create random shape. Now I have always the 8 colors showing up in the particles but I would like to have a random number of colors (1 to 8) everytime I run the script.

this is the relevant part of the code:

let colors = [
   "dodgerBlue",
  "red",
  "#fff200",
  "limeGreen",
  "slateGrey",
  "orange",
  "hotPink", 
  " #080808"
];
const dpi = 100;

let Particle = function(x, y) {
  this.x =  getRandomInt(cw);
  this.y =  getRandomInt(ch);
  this.coord = {x:x, y:y};
  this.r =  Math.min(getRandomInt(cw / dpi), 10 );
  this.vx = (Math.random() - 0.5) * 100;
  this.vy = (Math.random() - 0.5) * 100;
  this.accX = 0;
  this.accY = 0;
  this.friction = Math.random() * 0.07 + 0.90;
  this.color = colors[Math.floor(Math.random() * 8)];
}

how can I get a random number output instead of the "8" of the last line?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

I'd do three things:

Shuffle the array

I'll just use the shuffle code from this answer:

/**
 * Shuffles array in place.
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    var j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return a;
}

Remove items from the array

Easiest way to do this is with the slice function. You just do array.slice(0, 3) and that would keep the first few items. In your example you would want to randomise the second number, ensuring it's always 1 or more.

No hard-coding the array length

In your code there's an 8 for the length of the array. That could be improved by using the array.length because that will handle any length and it's easier to understand.

Example

Putting that together would give:

/**
 * Shuffles array in place. ES6 version
 * @param {Array} a items An array containing the items.
 * https://stackoverflow.com/a/6274381/16584778
 */
function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}

var colours = [
  "red",
  "green",
  "blue",
  "yellow",
  "black",
  "pink",
  "orange",
  "purple"
];

// randomise the order of the colours
shuffle(colours);

// keep some/all of the colours
colours = colours.slice(0, 1 + Math.floor(Math.random() * colours.length));

// show the colours that we have kept
document.write(colours.join(' ') + '<br/>');

// output dots using our chosen colours
for (var n = 0; n < 200; n++) {
  document.write('<span style="color:' + colours[Math.floor(Math.random() * colours.length)] + '">&#9632;</span> ');
}

about 4 years ago · Juan Pablo Isaza Denunciar

0

Math.floor() returns max less or equal number,that why u allways have the same 8. Specify youre requirments and use this insted youre last line:

function getRandomArbitrary(min, max) {
    return Math.random() * (max - min) + min;
 }

That function will return allways random value in specifyed diapason.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Array.prototype.random = function(){
  return this[Math.floor(Math.random() * this.length)];
}

let colors = [
   "dodgerBlue",
  "red",
  "#fff200",
  "limeGreen",
  "slateGrey",
  "orange",
  "hotPink", 
  " #080808"
];

// syntax use 

console.log(colors.random())

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda