2016-03-31 9 views
0

Python 3を使用して、与えられた円形の領域を埋めるために必要な部分タイル(辺の長さ1単位)がいくつあるかを調べたい半径r。複数の部分タイルを合計して完全なタイルを形成することはできず、部分タイルの残りの部分を他の場所で再利用することはできません。円を埋めるために必要な完全および部分sqareタイルの数

円の中心は常に4つのタイルの間の境界になりますので、我々は円の1/4の必要性を計算し、例えばのであれば4

でそれを掛けることができますr=1の場合、0個の完全タイルと4個の部分タイルが存在します。
r=2の場合、結果は完全4個、部分タイル12個などとなります。

どのようなアプローチを使用できますか?コードはできるだけ短くする必要があります。

答えて

2

私は以下のトリックを行う必要がありますと思う。 print文がPython 2であることをお詫びしますが、変換するのは簡単だと思います。

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) 
関連する問題