Search code examples
javascriptcolorsrandomcolor-pickerprng

Create programmatic colour picker


How would one create a deterministic Javascript HTML colour picker which given arguments of how many colours are desired returns an array of HTML hex colour codes, ie:

    function createColours(numColours) {
        return [/* colours array of size numColours */]     
    }

The colours themselves can be chosen / generated randomly, but the method must guarantee that colours chosen are always the same between calls and always in the same order in series.

For example, if the series of colours decided on by the function started with the following 8:

    "#47092E", "#CC2A43", "#00C66B", "#BC1300", "#667E00", "#795800", "#FFD245", "#6EFFAD", etc, etc

The function would behave with the following consistent responses across separate method invocations on the client

    ["#47092E", "#CC2A43"] == createColours(2);
    ["#47092E", "#CC2A43", "#00C66B", "#BC1300", "#667E00"] == createColours(5);
    ["#47092E"] == createColours(1);        
    ["#47092E", "#CC2A43", "#00C66B", "#BC1300", "#667E00", "#795800", "#FFD245", "#6EFFAD", #and 49 others#] == createColours(57);     

Note: The colours are not defined as a variable in advance; the method might be asked for 345 colours, all of which it would be required to generate by whatever suitable means.

The problem to be solved is - first and foremost - how would you create a capability within the method to generate the n HEX colour values consistently the same each time also preserving the sequence


Solution

  • You need to use a pseudo random number generator (PRNG), with a fixed start seed. The Math.random method in javascript is a PRNG, but you can't set the seed like you can in other languages.

    A PRNG is reasonably simple to create - lots of code on the internet. Given a fixed start seed it will always generate the same sequence of random numbers, which is what you're asking for.

    Whether those colors look pleasing or not, is another question entirely...

    One javascript implementation with seeding capability:
    http://www.erikoest.dk/rng2.htm

    You'll also find C implementations (easy to convert to javascript) and other details of building your own PRNG of the Lehmer type here:
    http://www.google.com/search?q=Lehmer%20random%20number%20generator

    Another one with code (Mersenne twister):
    http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/VERSIONS/JAVASCRIPT/java-script.html

    This question covers several types of PRNG in javascript:
    Seedable JavaScript random number generator

    If you give the same starting seed to the PRNG at the beginning of the function, it will always return the same number sequence with each successive call.

    Convert that number into a color, and you're all set.

    -Adam