Created
March 5, 2017 23:04
-
-
Save smarj/0ddbbb28b2bf1eff6b5ab54e629b9d85 to your computer and use it in GitHub Desktop.
Functional Programming in Erlang, assignment 1.24 2017-03-05
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(one_24). | |
-export([bits/1, enclose/1, perimeter/1, tail_bits/1]). | |
%% perimeter/1 - calculate the perimeter of common shapes | |
%% circle - πD, unrelated to coordinates | |
perimeter({circle, {_X,_Y}, Radius}) -> | |
Radius * 2 * math:pi(); | |
%% rectangle - assumes coordinate 1 is lower left, coordinate 2 is upper | |
%% right, clauses with guards could be used to ensure it | |
perimeter({rectangle, {X1,Y1}, {X2,Y2}}) -> | |
Height = Y2 - Y1, | |
Width = X2 - X1, | |
Height * 2 + Width * 2; | |
perimeter({triangle, {X1,Y1}, {X2,Y2}, {X3,Y3}}) -> | |
%% Use Pythagorean theorem to find side lengths | |
L1 = math:sqrt((X2-X1) * (X2-X1) + (Y2-Y1) * (Y2-Y1)), | |
L2 = math:sqrt((X3-X2) * (X3-X2) + (Y3-Y2) * (Y3-Y2)), | |
L3= math:sqrt((X1-X3) * (X1-X3) + (Y1-Y3) * (Y1-Y3)), | |
L1 + L2 + L3. | |
%% enclose/1 - find the enclosing rectangle of a given common shape | |
%% circle = a square centered around the center of the cirle, sides | |
%% are 1 radius away from the center in all four directions | |
enclose({circle, {X,Y}, Radius}) -> | |
{rectangle, {X-Radius, Y-Radius}, {X+Radius, Y+Radius}}; | |
%% rectangle = the enslosing rectangle of a rectangle is the rectangle | |
enclose({rectangle, {X1,Y1}, {X2,Y2}}) -> | |
{rectangle, {X1,Y1}, {X2,Y2}}; | |
%% triangle = min and max of values of all three coordinates | |
enclose({triangle, {X1,Y1}, {X2,Y2}, {X3,Y3}}) -> | |
{rectangle, {lists:min([X1,X2,X3]),lists:min([Y1,Y2,Y3])}, | |
{lists:max([X1,X2,X3]),lists:max([Y1,Y2,Y3])}}. | |
%% Use bit shift in math to calculate number of bits set to 1 in an int | |
%% with an accumulator | |
tail_bits(N) -> tail_bits(N, 0). | |
tail_bits(N,Acc) when N < 1 -> | |
Acc; | |
tail_bits(N, Acc) when N rem 2 =:= 1 -> | |
tail_bits(trunc(N/2), Acc + 1); %% use trunc/1 to convert float to int | |
tail_bits(N, Acc) when N rem 2 =:= 0 -> | |
tail_bits(trunc(N/2), Acc). %% use trunc/1 to convert float to int | |
%% Use bit shift in math to calculate number of bits set to 1 in an int | |
bits(0) -> 0; | |
bits(N) -> | |
N rem 2 + bits(trunc(N/2)). %% use trunc/1 to convert float to int |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment