Byte Commander
Byte Commander

Reputation: 6736

number of complete and partial sqare tiles needed to fill a circle

Using Python 3, I want to find out how many complete and how many partial square tiles (side length 1 unit) one would need to fill a circular area with a given radius r. Multiple partial tiles can not be summed up to form a complete tile, also the remainder of a partial tile may not be reused anywhere else.

The center of the circle will always be on a boundary between four tiles, so we can calculate the need for 1/4 of the circle and multiply it with 4.

So if e.g. r=1, there would be 0 complete and 4 partial tiles.
For r=2 the result would be 4 complete and 12 partial tiles, and so on...

What approaches could I use? The code should be as short as possible.

Upvotes: 0

Views: 1045

Answers (1)

Xirtaminu
Xirtaminu

Reputation: 404

I think the following should do the trick. Apologies that the print statement is python 2, but I think it should be easy to convert.

import math

# Input argument is the radius
circle_radius = 2.

# This is specified as 1, but doesn't have to be
tile_size = 1.

# Make a square box covering a quarter of the circle
tile_length_1d = int(math.ceil(circle_radius / tile_size ))

# How many tiles do you need?
num_complete_tiles = 0
num_partial_tiles = 0

# Now loop over all tile_length_1d x tile_length_1d tiles and check if they
# are needed
for i in range(tile_length_1d):
    for j in range(tile_length_1d):
        # Does corner of tile intersect circle?
        intersect_len = ((i * tile_size)**2 + (j * tile_size)**2)**0.5
        # Does *far* corner intersect (ie. is the whole tile in the circle)
        far_intersect_len = (((i+1) * tile_size)**2 + ((j+1) * tile_size)**2)**0.5
        if intersect_len > circle_radius:
            # Don't need tile, continue
            continue
        elif far_intersect_len > circle_radius:
            # Partial tile
            num_partial_tiles += 1
        else:
            # Keep tile. Maybe you want to store this or something
            # instead of just adding 1 to count?
            num_complete_tiles += 1

# Multiple by 4 for symmetry
num_complete_tiles = num_complete_tiles * 4
num_partial_tiles = num_partial_tiles * 4

print "You need %d complete tiles" %(num_complete_tiles)
print "You need %d partial tiles" %(num_partial_tiles)

Upvotes: 2

Related Questions