Skip to content

Instantly share code, notes, and snippets.

@stormwatch
Created May 24, 2020 22:12
Show Gist options
  • Save stormwatch/a6bce447c9e7071526c05f6a4c80110e to your computer and use it in GitHub Desktop.
Save stormwatch/a6bce447c9e7071526c05f6a4c80110e to your computer and use it in GitHub Desktop.
-module(two18).
-export([double/1, double2/1, evens/1, evens2/1, median/1, count_elements/1, modes/1]).
%% Define an Erlang function double/1 to double the elements of a list of
%% numbers.
double([]) ->
[];
double([X | Xs]) ->
[2 * X | double(Xs)].
double2(L) ->
[2 * X || X <- L].
%% Define a function evens/1 that extracts the even numbers from a list of
%% integers.
evens([]) ->
[];
evens([N | Ns]) when N rem 2 =:= 0 ->
[N | evens(Ns)];
evens([_ | Ns]) ->
evens(Ns).
evens2(L) ->
[X || X <- L, X rem 2 =:= 0].
%% the median of a list of numbers: this is the middle element when the list is
%% ordered (if the list is of even length you should average the middle two)
median([_|_] = Unsorted) ->
Sorted = lists:sort(Unsorted),
Length = length(Sorted),
Middle = Length div 2,
Reminder = Length rem 2,
(lists:nth(Middle + Reminder, Sorted) + lists:nth(Middle + 1, Sorted)) / 2.
%% the modes of a list of numbers: this is a list consisting of the numbers that
%% occur most frequently in the list; if there is is just one, this will be a
%% list with one element only
count_elements(List) ->
lists:foldl(
fun(X, Map) ->
maps:update_with(
X,
fun(Count) ->
Count + 1
end,
1,
Map)
end,
#{},
List).
modes(List) ->
maps:fold(
fun(Key, Value, []) ->
[{Key, Value}];
(Key, Value, [{_, Prev}|_]) when Value > Prev ->
[{Key, Value}];
(Key, Value, [{_, Prev}|_] = Acc) when Value == Prev ->
[{Key, Value} | Acc];
(_Key, _Value, Acc) ->
Acc
end,
[],
count_elements(List)).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment