# Random Grid Generation with Random Density

I have a 2D grid of cells in Unity, and each cell can be on or off. I want to randomly generate the on cells, and when I just assign a probability to each cell, the entire grid has the same density, looking something like this:

But I would like different densities for random areas, something more like:

Is there some kind of algorithm to make this random generation possible?

• Have you looked into Mathf.PerlinNoise as a way to vary the spawn probability over space in a smoothly-varying way? Commented Dec 28, 2023 at 2:27
• In this answer I show how to use Poisson-Disk sampling to get a very similar result. That solution uses Perlin noise to guide the probability rate (much as DMGregory suggested). With some minor changes it could be adapted to use your on/off cell grid. Is that enough to address your question? Commented Dec 28, 2023 at 3:30

Use Mathf.PerlinNoise todo it , example here:

float Perlin(float x, float y)
{
for(x; x< ChunkSize; x++)
{
for(y; y < ChunkSize; y++)
{
return Mathf.PerlinNoise(x,y);
}
}
}


• This code uses two for loops to return just a single value. Only the first and seventh line actually do anything. It may be better to tailor your example to the question that was asked, showing how to use Perlin noise to vary an on/off probability. Commented Dec 28, 2023 at 12:17

You can just set the densities probability to each area so you will get result close to your second picture. Write the algorithm to separate the gird on areas. for example you have 8x8 grid and areas:

11122333
11122333
44422555
44466555
44466555
77888888
77888888
77888888


Generate probablity for each area: 1)p=80% 2)p=30% 3)p=45% etc. And you can customize it for your needs.

• This answer would be better if it detailed how to write such an algorithm. Commented Dec 31, 2023 at 0:42
• Sure I can but It will take 2 hours to write such algorithm and I don't know his project requirements so he will need to rewrite it anyway, I believe if person need such result he should be able to write such an algorithm by himself and he will learn more by doing it instead of copy paste the solution. Commented Dec 31, 2023 at 19:28