Quantcast
Viewing all articles
Browse latest Browse all 14069

Find the optimal clipped circle

Given an n by n matrix of integers, I want to find the clipped circle which maximizes the sum. Here is a picture and then explanation/code will follow:

Image may be NSFW.
Clik here to view.
enter image description here

The circle has center at (0,0) and we are only interested in the part that intersects the grid. At each integer coordinate in the grid there is an integer. The circle can have any radius (not necessarily an integer radius but more on this below).

There is also a diagonal line which might clip the circle as in the picture. The diagonal line always starts and ends at an integer coordinate and goes down and to the right at 45 degrees to the horizontal as shown in the picture.

The score for a clipped circle is the sum of all the integers that are both within the circle and on the side of the diagonal line including (0,0). In the picture, this would include -2, 2, 3, 2, 3, 0, -2, 1, -2, 0 on (or close to) the border and everything that is closer to (0, 0).

Even though the circle can have any radius, we need only consider circles that intersect a grid point precisely so there are n^2 different relevant radiuses. Further, we need only record one position where the circle intersects with the diagonal line at a grid point to fully specify the clipped circle. If solution doesn't have the diagonal clipping the circle at all then we need only return the radius of the circle.

If we only wanted to find the optimal circle we could do that with:

import numpy as npfrom math import sqrtnp.random.seed(40)def find_max(A):    n = A.shape[0]    sum_dist = np.zeros(2 * n * n, dtype=np.int32)    for i in range(n):        for j in range(n):            dist = i**2 + j**2            sum_dist[dist] += A[i, j]    cusum = np.cumsum(sum_dist)    # returns optimal radius with its score    return sqrt(np.argmax(cusum)), np.max(cusum)A = np.random.randint(-3, 4, (10, 10))print(find_max(A))

How quickly can the optimal clipped circle be found?


Viewing all articles
Browse latest Browse all 14069

Trending Articles