Search code examples
javascriptprobabilityprobability-densityprobability-theory

JS inverting probabilities


I'm generating a grid of objects, each of which has one of 3 colors. Assume I'm filling a particular grid cell. I know that around this cell there are, for example, 1 object of color 0, 1 of color 1 and 2 of color 2, so:

const surroundings = { 0: 1, 1: 1, 2: 2 }

Now I want to assign a color to the current cell I'm working with. I need to count probabilities for each color to be used. To make it look pleasing, I want it more likely to be different from its surroundings. So in the case above the probabilities could be { 0: 0.4, 1: 0.4, 2: 0.2 }.

I'm sure there is an implementation of such operation in the probability theory, but I'm having trouble finding the correct term for it. In the example I gave the probabilities could be different, because I have no idea how to calculate them. But for colors 0 and 1 they should certainly be equal and for color 2 it should be the smallest.


Solution

  • You could get the reciprocal and the sum and return the part of it.

    function getPro(array) {
        var inv = array.map(v => 1 / v),
            sum = inv.reduce((a, b) => a + b);
        return inv.map(v => v / sum);
    }
    
    
    console.log(getPro([1, 1, 2]));
    console.log(getPro([1, 1, 1]));
    console.log(getPro([2, 4, 6]));