Move previous cryptopals work into an Erlang subfolder, start cryptopals in Python 3
[sandbox] / cryptopals-erlang / 01.03 / stat.erl
1 -module(stat).
2 -export([sum/1,mean/1,r_value/1,frequency/1,frequencies_to_scatterplot/2]).
3
4 sum([]) -> 0;
5 sum([Head|Tail]) -> Head + sum(Tail).
6
7 mean(List) -> sum(List) / length(List).
8
9 covariance(Points, MeanX, MeanY) ->
10     sum(lists:map(fun({X,Y}) -> (X - MeanX) * (Y - MeanY) end, Points)).
11
12 standard_deviation(Samples, Mean) ->
13     math:sqrt(sum(lists:map(
14         fun(Item) -> math:pow(Item - Mean, 2) end,
15         Samples))).
16
17 r_value(Points) ->
18     Xs = lists:map(fun({X,_}) -> X end, Points),
19     Ys = lists:map(fun({_,Y}) -> Y end, Points),
20     MeanX = mean(Xs),
21     MeanY = mean(Ys),
22     Covariance = covariance(Points, MeanX, MeanY),
23     StandardDeviationX = standard_deviation(Xs, MeanX),
24     StandardDeviationY = standard_deviation(Ys, MeanY),
25     Covariance / StandardDeviationX / StandardDeviationY.
26
27 frequency([],Result) -> Result;
28 frequency([Head|Tail],Result) ->
29     frequency(Tail,dict:update_counter(Head,1,Result)).
30
31 frequency(Sample) -> frequency(Sample, dict:new()).
32
33 fetch_values(Dict) -> lists:map(
34     fun({_,Value}) -> Value end,
35     dict:to_list(Dict)).
36
37 frequencies_to_scatterplot(Fx,Fy) ->
38     FxPoints = dict:map(fun(_,Value) -> {Value,0} end, Fx),
39     FyPoints = dict:map(fun(_,Value) -> {0,Value} end, Fy),
40     KeysToPoints = dict:merge(
41         fun(_,{X,_},{_,Y}) -> {X,Y} end,
42         FxPoints,
43         FyPoints),
44     fetch_values(KeysToPoints).