Last active
May 14, 2020 21:07
-
-
Save adhalanay/3cc879e2b34842df086b5551b635e117 to your computer and use it in GitHub Desktop.
This file contains 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(hwork1). | |
-export([area/1,perimeter/1,enclose/1,bits/1,bits_tail/1]). | |
max_three(X,Y,Z)-> | |
max(max(X,Y),Z). | |
area({circle,{_X,_Y},R})-> | |
math:pi()*R*R; | |
area({rectangle,{_X,_Y},H,W}) -> | |
H*W; | |
area({triangle,{_X,_Y},A,B,C})-> | |
P = perimeter({triangle,{_X,_Y},A,B,C})/2, | |
math:sqrt(P*(P-A)*(P-B)*(P-C)).%Heron's formula | |
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. | |
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}) -> | |
W = max_three(A,B,C), | |
H = 2*area({triangle,{X,Y},A,B,C})/W, | |
{rectangle,{X,Y},H,W}. | |
%I am cheating here as the center of the triangle is defined as the center of the | |
% coresponding rectangle and I am not sure how to get the center of the rectangle from the | |
% centroid or some other center of the triangle. | |
bits(0) -> | |
0; | |
bits(N) -> | |
bits(N div 2)+N rem 2. | |
%The tail-recursive version | |
bits_tail(N)-> | |
bits_tail_acc(N,0). | |
bits_tail_acc(0,Acc)-> | |
Acc; | |
bits_tail_acc(N,Acc) -> | |
bits_tail_acc(N div 2, Acc + (N rem 2)). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment