Fill part of a matrix with a circle shape

2

My question is how I could create a circle within a matrix. Let me explain:

Imagine a 1000x1000 matrix, filled with 0. I already have the necessary code to create rectangles and diamonds (fill in 1 the necessary boxes with that shape). But my doubt is how I could fill the matirz with ones with a shape similar to a circle.

The programming language does not matter, I just want the idea.

Thank you very much in advance.

Edit: the 1000x1000 matrix is an example, but they are always going to be sizes where a good approximation can be conceived (100x100 ....). It is simply the way to fill with a matrix of zeros in the shape of a circle.

    
asked by PABLO FERNANDEZ 09.04.2018 в 19:57
source

2 answers

1

This would form a filled circle of 1, the question is a little ambiguous so I'm not sure if it's the result you're looking for.

public static void main(String[] args)
{
    int[][] matriz = new int[9][];
    double medio = (matriz.length-1)/2.0;
    for (int columna = 0; columna < matriz.length; columna++)
    {
        int[] fila = new int[matriz.length];
        double yy = columna-medio;
        for (int x=0; x<fila.length; x++)
        {
           double xx = x-medio;
           if (Math.sqrt(xx*xx+yy*yy)<=medio)
             fila[x] = 1;
           System.out.print(fila[x]);
        }
        matriz[columna] = fila;
        System.out.println();
    }

}
    
answered by 10.04.2018 / 12:39
source
0

The formula of the circumference is f (x, y) = x 2 + and 2 - r 2 , centered on 0, 0;

Suppose the diameter of the circle is the width of the matrix: a matrix of 101 x 101 will have a circle of 50 cells of radius, and the center will be in position 50.50.

The solution would be, for each column, to calculate which rows are within the circumference:

  • For column 0: r = 50, x = -50 - > y = 0;
  • For column 1: r = 50, x = -49 - > and 2 = 2500-2401 - > y = (9, -9) approximately, so it would be necessary to paint between positions 41 and 59
  • For column 2: x = -48 - > and 2 = 2500 - 2304 = 196 - > y = 14, -14
  • ...

I give you an example in Javascript that, for simplicity, does the calculation by rows instead of columns (conceptually rotated 90º with respect to the previous explanation) and with a smaller size:

let matrix = [];

const RADIO = 25;
const DIAMETRO = RADIO * 2;

function calculaX(radio, y) {
  return Math.round(((radio ** 2) - ((y-radio) ** 2)) ** .5);
}

for (let y = 0; y < DIAMETRO; y++){
   const limite= calculaX(RADIO, y);
   matrix[y] = [];
   for (let x = 0; x < DIAMETRO; x++) {
     matrix[y].push(((x < RADIO - limite) || (x > RADIO + limite)) ? ' ' : '0');
   }
}

for (let i = 0; i < matrix.length; i++) {
  console.log(matrix[i].toString());
}
    
answered by 10.04.2018 в 13:21