Skip to content

Instantly share code, notes, and snippets.

@Joakineee
Created May 14, 2020 07:48
Show Gist options
  • Save Joakineee/a60264a6d0de280056e828fbb237a748 to your computer and use it in GitHub Desktop.
Save Joakineee/a60264a6d0de280056e828fbb237a748 to your computer and use it in GitHub Desktop.
Put all in toguether1
-module(pat).
-export([perimeter/1,area/1,enclosure/1,bits/1,bits_rec/1,tests/0]).
%Shapes exercises
%I considered not necessary to validate the shapes as john don't use it during his examples,
% forexp in circle R > 0 and in triangle A + B > C,etc..
perimeter({circle,_,Radius}) ->
2 * math:pi() * Radius;
perimeter({rectangle,_,H,W}) ->
(2 * H) + (2 * W);
perimeter({triangle,_,A,B,C}) ->
A + B + C.
area({circle,_,Radius}) ->
math:pi() * Radius * Radius;
area({rectangle,_,H,W}) ->
H * W;
%triangle area from Herón formula, explained in week one.
area({triangle,_,A,B,C}) ->
S = (A+B+C)/2,
math:sqrt(S*(S-A)*(S-B)*(S-C)).
enclosure({circle,{X,Y},Radius}) ->
Diameter=2*Radius,
{rectangle,{X,Y},Diameter, Diameter};
%Triangle heigh from Herón formula also.
enclosure({triangle,{X,Y},A,B,C}) ->
Ha = (2/A)*area({triangle,{X,Y},A,B,C}),
{rectangle,{X,Y},A,Ha}.
%%%%%
bits(X) ->
bits_tail(X,0).
%bits tail recursive func:
bits_tail(0,Acc) ->
Acc;
bits_tail(X,Acc) ->
bits_tail(X div 2,Acc + (X rem 2)).
%bits recursive func:
bits_rec(0) ->
0;
bits_rec(X) ->
X rem 2 + bits_rec(X div 2).
tests() ->
18.84955592153876 = perimeter({circle,{0,0},3}),
18 = perimeter({rectangle,{0,0},3,6}),
15 = perimeter({triangle,{0,0},4,5,6}),
28.274333882308138 = area({circle,{0,0},3}),
18 = area({rectangle,{0,0},3,6}),
1 = bits(8),
3 = bits(7),
1 = bits_rec(8),
3 = bits_rec(7),
success.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment