Home > Blockchain >  Need help for an algo [closed]
Need help for an algo [closed]

Time:09-21

I make a site where the color of the div is randomly generating compared to this array:

let pastelColor = [
    'ffaacc','ffbbcc','ffcccc','ffddcc','ffeecc','ffffcc','ffaadd','ffbbdd','ffccdd','ffdddd','ffeedd','ffffdd',
    'ffaaee','ffbbee','ffccee','ffddee','ffeeee','ffffee','ffaaff','ffbbff','ffccff','ffddff','ffeeff','ffffff',
    'ccaaff','ccbbff','ccccff','ccddff','cceeff','ccffff','ccaaee','ccbbee','ccccee','ccddee','cceeee','ccffee',
    'ccaadd','ccbbdd','ccccdd','ccdddd','cceedd','ccffdd','ccaacc','ccbbcc','cccccc','ccddcc','cceecc','ccffcc'
]

I tried several Algo with Case Switch but the function took too much room, I was wondering in curiosity if an algo would be able to generate this array ?

Thank you in advance for those who answer

CodePudding user response:

if an algo would be able to generate this array ?

Sure. If you need that array in that exact order:

let pastelColor = Array.from("abcdef".repeat(8), (ch, i) => 
    (([a,...r]) => a a ch ch r[~~(i/6)%4].repeat(2))(i<24 ? "fcdef" : "cfedc")
);

console.log(pastelColor);

If you are not really interested in the array with color codes, but only in the generation of a random color from it, then:

let pick = str => str[Math.floor(Math.random() * str.length)].repeat(2);
let pastelColor = pick("cf")   pick("abcdef")   pick("cdef");

console.log(pastelColor);

CodePudding user response:

You need to fill the array with the converted hexadecimal color with randomly generated integers ranging from 0 to 255 like this:

const getRandomInt = (min, max) => {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)   min);
}

const getRandomColorUnit = () => {
    const color = getRandomInt(0, 256).toString(16);
    if (color.length < 2) return '0'   color;
    return color;
};

const getRandomColor = () => `#${getRandomColorUnit()}${getRandomColorUnit()}${getRandomColorUnit()}`;

const colors = new Array(100).fill(0).map(getRandomColor);

console.log(colors);

  • Related