Navigation

How to: generate 2D matrix from an Array of random values with Javascript


mksolemn
How to: generate 2D matrix from an Array of...

In this tutorial, I will generate a 2D matrix from an Array of random values. Also, the values will be generated per matrix tile from a predefined array of objects.

Let’s start by defining a data model that will be the tile of the 2D matrix. And variable defining 2D matrix rows and columns.

const tileData = [
    {
        chance: .1,
        label: 'crab',
        img: './png/023-crab.png'
    },
    {
        chance: .3,
        label: 'croc',
        img: './png/039-crocodile.png'
    },
    {
        chance: .4,
        label: 'chic',
        img: './png/028-chicken.png'
    },
    {
        chance: .2,
        label: 'lion',
        img: './png/048-lion.png'
    },
];
const MATRIX_SIZE = [4, 4];

Next, we need a function that will select one of the Array values at random. Remember to include the likelihood (chance)of rolling that array item.

chooseWeighted = (items, chances) => {
    var sum = chances.reduce((acc, el) => acc + el, 0);
    var acc = 0;
    chances = chances.map(el => (acc = el + acc));
    var rand = Math.random() * sum;
    return items[chances.filter(el => el <= rand).length];
};

Furthermore, we need a function that generates the matrix with randomly generated values.

const allChances = tileData.map((a => a.chance));
generateMatrix = (allChances) => {
    // generate matrix
    var result = [];
    for (var i = 0; i < MATRIX_SIZE[0]; i++) {
        result[i] = [];
        for (var j = 0; j < MATRIX_SIZE[1]; j++) {
            result[i][j] = chooseWeighted(tileData, allChances);
        }
    }
};

That’s it – now we’re generating a matrix with random values. The logic bit is done. But it’s always nice to have some UI too – for that I only need another function, addGameTile:

addGameTile = (tileImg, tileLabel, tileSize) => {
    let gameTile = document.createElement('div');
    gameTile.style.backgroundImage = 'url(' + tileImg + ')';
    gameEl.appendChild(gameTile);
    gameTile.style.width = tileSize;
};

Now just plug this function inside generateMatrix:

//...
result[i][j] = chooseWeighted(tileData, allChances);
addGameTile(result[i][j].img, result[i][j].label, 1 / MATRIX_SIZE[0] * 100 + '%')
//...

And that’s how I generate random 2D matrix from weighted Array;

You can find code with style on my github: https://github.com/mksolemn/random-2d-matrix-from-weighted-array

 

Show Comments (0)

Comments

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Javascript

React code quality with SonarQube on docker

Leverage SonarQube for increased confidence in your React project quality metrics. You can run SonarQube in docker to get the ability to continuously update your analysis through...

Posted on by mksolemn