Skip to content

Instantly share code, notes, and snippets.

@i7an
Created June 26, 2017 13:07
Show Gist options
  • Save i7an/b34139b61ca249291737892fdf3af10c to your computer and use it in GitHub Desktop.
Save i7an/b34139b61ca249291737892fdf3af10c to your computer and use it in GitHub Desktop.
-module(assignment).
-export([perimeter/1, area/1, enclose/1, bits/1, bits_direct/1,
test_perimeter/0, test_area/0, test_enclose/0, test_bits/0]).
% {circle, {X,Y}, R}
% Represents a circle.
% X,Y - center
% R - radius
% {rectangle, {X,Y}, H, W}
% Represents a rectangle, sides of which are parallel to axises
% X,Y - center
% H - height
% W - width
% {triangle, {X,Y}, A, B, C}
% X,Y - left coordinate of A-side
% A - the longest side of a triangle, parallel to x-axis
% B,C - other two sides
perimeter({circle, {_X,_Y}, R}) -> 2 * math:pi() * R;
perimeter({rectangle, {_X,_Y}, H, W}) -> 2 * (H + W);
perimeter({triangle, {_X,_Y}, A, B, C}) -> A + B + C.
area({circle, {_X,_Y}, R}) -> math:pi() * R * R;
area({rectangle, {_X,_Y}, H, W}) -> H * W;
area({triangle, {_X,_Y}, A, B, C}) ->
S = perimeter({triangle, {_X,_Y}, A, B, C}) / 2,
math:sqrt(S * (S - A) * (S - B) * (S - C)).
enclose({circle, {X,Y}, R}) -> {rectangle, {X,Y}, 2*R, 2*R};
enclose({rectangle, {X,Y}, H, W}) -> {rectangle, {X,Y}, H, W};
enclose({triangle, {X,Y}, A, B, C}) ->
H = 2 * area({triangle, {X,Y}, A, B, C}) / A,
{rectangle, {X+A/2, Y+H/2}, H, A}.
bits_direct(0) -> 0;
bits_direct(N) when N >= 0 ->
(N rem 2) + bits_direct(N div 2).
bits(N) when N >= 0 ->
bits(N, 0).
bits(0, Sum) -> Sum;
bits(N, Sum) -> bits(N div 2, Sum + (N rem 2)).
test_perimeter() ->
2.0 = perimeter({circle, {0,0}, 1 / math:pi()}),
12 = perimeter({rectangle, {2,1}, 2, 4}),
12 = perimeter({triangle, {0,0}, 5, 3, 4}),
ok.
test_area() ->
3.141592653589793 = area({circle, {0,0}, 1}),
8 = area({rectangle, {2,1}, 2, 4}),
6.0 = area({triangle, {0,0}, 5, 3, 4}),
ok.
test_enclose() ->
{rectangle, {0,0}, 2, 2} = enclose({circle, {0,0}, 1}),
{rectangle, {2,1}, 2, 4} = enclose({rectangle, {2,1}, 2, 4}),
{rectangle, {2.5,1.2}, 2.4, 5} = enclose({triangle, {0,0}, 5, 3, 4}),
ok.
test_bits() ->
3 = bits(7),
1 = bits(8),
3 = bits_direct(7),
1 = bits_direct(8),
ok.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment