Skip to content

Instantly share code, notes, and snippets.

@maruks
Created February 24, 2017 21:02
Show Gist options
  • Select an option

  • Save maruks/d70a8d6b49ba80de9d94779a446b7cce to your computer and use it in GitHub Desktop.

Select an option

Save maruks/d70a8d6b49ba80de9d94779a446b7cce to your computer and use it in GitHub Desktop.
futurelearn erlang assignment #1
-module(bits).
-export([bits/1, bits2/1, bits3/1]).
bits_tail_rec(<<B:1, Rest/bitstring>>, A) ->
bits_tail_rec(Rest,B + A);
bits_tail_rec(<<>>, A) ->
A.
bits(N) ->
bits_tail_rec(binary:encode_unsigned(N), 0).
bits_rec(<<B:1, Rest/bitstring>>) ->
B + bits_rec(Rest);
bits_rec(<<>>) ->
0.
bits2(N) ->
bits_rec(binary:encode_unsigned(N)).
bits3(0) ->
0;
bits3(N) ->
1 + bits3(N band (N - 1)). % turns off rightmost bit
-module(bits_test).
-import(bits,[bits/1, bits2/1, bits3/1]).
-include_lib("eunit/include/eunit.hrl").
bits_test() ->
?assertEqual(1,bits(8)),
?assertEqual(1,bits2(8)),
?assertEqual(1,bits3(8)),
?assertEqual(9,bits(2#010110101011101)),
?assertEqual(9,bits2(2#010110101011101)),
?assertEqual(9,bits3(2#010110101011101)).
-module(shapes).
-import(math,[pi/0,sqrt/1,pow/2]).
-export([perimeter/1,area/1,enclose/1]).
-include("shapes.hrl").
distance(X1,Y1,X2,Y2) ->
sqrt(pow(X1 - X2, 2) + pow(Y1 - Y2, 2)).
area(#circle{r=R}) ->
pi() * R * R;
area(#rectangle{w=W, h=H}) ->
W * H;
area(#triangle{x1=X1, y1=Y1, x2=X2, y2=Y2, x3=X3, y3=Y3}) ->
A = distance(X1, Y1, X2, Y2),
B = distance(X2, Y2, X3, Y3),
C = distance(X1, Y1, X3, Y3),
S = (A + B + C) / 2,
sqrt(S * (S - A) * (S - B) * (S - C)).
perimeter(#circle{r=R}) ->
pi() * R * 2;
perimeter(#rectangle{w=W, h=H}) ->
2 * (W + H);
perimeter(#triangle{x1=X1, y1=Y1, x2=X2, y2=Y2, x3=X3, y3=Y3}) ->
A = distance(X1, Y1, X2, Y2),
B = distance(X2, Y2, X3, Y3),
C = distance(X1, Y1, X3, Y3),
A + B + C.
enclose(#circle{r=R, x=X, y=Y}) ->
#rectangle{x = X - R, y = Y - R, w = R*2, h = R*2};
enclose(#rectangle{} = R) ->
R;
enclose(#triangle{x1=X1, y1=Y1, x2=X2, y2=Y2, x3=X3, y3=Y3}) ->
MinX = lists:min([X1, X2, X3]),
MinY = lists:min([Y1, Y2, Y3]),
MaxX = lists:max([X1, X2, X3]),
MaxY = lists:max([Y1, Y2, Y3]),
#rectangle{x = MinX, y = MinY, w = MaxX - MinX, h = MaxY - MinY}.
-record(circle,{x :: number(),
y :: number(),
r :: number()}).
-record(rectangle,{x :: number(),
y :: number(),
w :: number(),
h :: number()}).
-record(triangle,{x1:: number(),
y1 :: number(),
x2:: number(),
y2 :: number(),
x3:: number(),
y3 :: number()}).
-module(shapes_test).
-import(shapes,[perimeter/1,area/1,enclose/1]).
-include_lib("eunit/include/eunit.hrl").
-include("shapes.hrl").
enclose_test() ->
?assertEqual(#rectangle{x=0,y=0,h=2,w=2}, enclose(#circle{x=1,y=1,r=1})).
area_test() ->
?assertEqual(15,area(#rectangle{w=3, h=5})).
perimeter_test() ->
?assertEqual(16,perimeter(#rectangle{w=3, h=5})).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment