Skip to content

Instantly share code, notes, and snippets.

@DmytroVasin
Last active August 7, 2018 05:05
Show Gist options
  • Save DmytroVasin/dde6bdb0d318b096201fe92e3f33e1f9 to your computer and use it in GitHub Desktop.
Save DmytroVasin/dde6bdb0d318b096201fe92e3f33e1f9 to your computer and use it in GitHub Desktop.
Задача 114: Тетрадь в клеточку
# Идея решения:
# Финальное число точек должно составляется из
# 1. Точки в центре ( начало круга ) ( На рисунке => "0" )
# 2. Точек лежащих на осях координат, умноженное на четыре
# - так как 4тыре направляющие ( На рисунке => "_" )
# 3. Точек лежащих на диагональных линиях, умноженное на четыре
# - так как 4тыре направляющие ( На рисунке => "*" )
# 4. Точки лежащие над и под диагональными линиями, умножаем на 8мь
# - так как в одном квадранте плоскости точки находятся и над и под диагональю.
# - () На рисунке => "Z" и "K" )
# X X X X X X X X X X X X X
# X X X X X X X X X X X X X
# X X X X X X _ K K K * X X
# X X X X X X _ K K * Z X X
# X X X X X X _ K * Z Z X X
# X X X X X X _ * Z Z Z X X
# X X _ _ _ _ 0 _ _ _ _ X X
# X X X X X X _ X X X X X X
# X X X X X X _ X X X X X X
# X X X X X X _ X X X X X X
# X X X X X X _ X X X X X X
# X X X X X X X X X X X X X
# X X X X X X X X X X X X X
class CartesianCircle
attr_accessor :radius
def initialize(radius:)
raise ArgumentError, 'Wrong radius' if radius <= 0
@radius = radius
end
def points_count
# Counting center
_count = 1
# Coordinate axes
_count += radius * 4
# Points that laydown on diagonal
_count += diagonal_points * 4
# Points that laydown under diagonal
_count += under_diagonal_points * 8
_count
end
private
def diagonal_points
sum_of_points = 0
1.upto(radius) do |coordinate|
if is_point_in_circle?(x: coordinate, y: coordinate)
sum_of_points += 1
end
end
sum_of_points
end
def under_diagonal_points
max_row, max_col = radius, radius
sum_of_points = 0
1.upto(max_row) do |row|
row.upto(max_col) do |col|
next if row == col # Skip diagonal
if is_point_in_circle?(x: row, y: col)
sum_of_points += 1
end
end
end
sum_of_points
end
def is_point_in_circle?(x:, y:)
radius >= Math.sqrt(x**2 + y**2)
end
end
p CartesianCircle.new(radius: 1).points_count
# Tests:
require 'test/unit'
class CartesianCircleTest < Test::Unit::TestCase
def test_1
res = CartesianCircle.new(radius: 1).points_count
assert(res.eql?(5), "Rdaius of 1 should have 5 points" )
end
def test_2
res = CartesianCircle.new(radius: 2).points_count
assert(res.eql?(13), "Rdaius of 2 should have 5 points" )
end
def test_3
res = CartesianCircle.new(radius: 3).points_count
assert(res.eql?(29), "Rdaius of 3 should have 5 points" )
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment