Created
February 28, 2017 16:35
-
-
Save creeonix/787535d6d1694ac490ca7c0c1ae31783 to your computer and use it in GitHub Desktop.
First week future learn assignment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(first_assignment). | |
-export([perimeter/1, area/1, enclosing/1, bits/1, tbits/1]). | |
%%%%%%%%%%%%%%%%%%%%% | |
% shapes | |
%%%%%%%%%%%%%%%%%%%%% | |
% all shapes are represented by one point and parameters | |
% {rectangle, {x, y}, {width, height}} | |
% {circle, {x, y}, radius} | |
% triangle is point and two sides + angle between them | |
% {triangle, {x, y}, {width, height, angle}} | |
perimeter({rectangle, {_,_}, {W, H}}) -> | |
(2*W)+(2*H); | |
perimeter({circle, {_,_}, R}) -> | |
2 * math:pi() * R; | |
perimeter({triangle, {_,_}, {A, B, AB}}) -> | |
triangle_third_side(A, B, AB) + A + B. | |
area({rectangle, {_,_}, {W, H}}) -> | |
W*H; | |
area({circle, {_,_}, R}) -> | |
math:pi() * R * R; | |
area({triangle, {_,_}, {A, B, AB}}) -> | |
(A * triangle_height(B, AB)) / 2. | |
enclosing({rectangle, {X, Y}, {W, H}}) -> | |
bounding_box(X, Y, (X + W), (Y + H)); | |
enclosing({circle, {X, Y}, R}) -> | |
bounding_box((X - R), (Y - R), (X + R), (Y + R)); | |
enclosing({triangle, {X, Y}, {A, B, AB}}) -> | |
bounding_box(X, Y, (X + max(A, B)), (Y + triangle_height(min(A,B), AB))). | |
% Helper functions | |
triangle_third_side(A, B, AB) -> | |
math:sqrt(A * A + B * B - 2 * A * B * math:cos(rad(AB))). | |
triangle_height(Side, Angle) -> | |
Side * math:sin(rad(Angle)). | |
rad(D) -> | |
D * math:pi() / 180. | |
bounding_box(X1, Y1, X2, Y2) -> | |
{{min(X1, X2), min(Y1, Y2)}, {max(X1, X2), max(Y1, Y2)}}. | |
%%%%%%%%%%%%%%%%%%%%% | |
% bits | |
%%%%%%%%%%%%%%%%%%%%% | |
bits(0) -> 0; | |
bits(N) -> | |
bit(N) + bits(N div 2). | |
% tail version | |
tbits(N) -> tbits(N, 0). | |
tbits(1, A) -> A + 1; | |
tbits(N, A) -> | |
tbits(N div 2, A + bit(N)). | |
% HELPERS | |
bit(N) when N rem 2 == 0 -> 0; | |
bit(_) -> 1. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment