48 lines
1.1 KiB
Text
48 lines
1.1 KiB
Text
use Collection;
|
|
|
|
class Entropy {
|
|
function : native : GetShannonEntropy(result : String) ~ Float {
|
|
frequencies := IntMap->New();
|
|
|
|
each(i : result) {
|
|
c := result->Get(i);
|
|
|
|
if(frequencies->Has(c)) {
|
|
count := frequencies->Find(c)->As(IntHolder);
|
|
count->Set(count->Get() + 1);
|
|
}
|
|
else {
|
|
frequencies->Insert(c, IntHolder->New(1));
|
|
};
|
|
};
|
|
|
|
length := result->Size();
|
|
entropy := 0.0;
|
|
|
|
counts := frequencies->GetValues();
|
|
each(i : counts) {
|
|
count := counts->Get(i)->As(IntHolder)->Get();
|
|
freq := count->As(Float) / length;
|
|
entropy += freq * (freq->Log() / 2.0->Log());
|
|
};
|
|
|
|
return -1 * entropy;
|
|
}
|
|
|
|
function : Main(args : String[]) ~ Nil {
|
|
inputs := [
|
|
"1223334444",
|
|
"1223334444555555555",
|
|
"122333",
|
|
"1227774444",
|
|
"aaBBcccDDDD",
|
|
"1234567890abcdefghijklmnopqrstuvwxyz",
|
|
"Rosetta Code"];
|
|
|
|
each(i : inputs) {
|
|
input := inputs[i];
|
|
"Shannon entropy of '{$input}': "->Print();
|
|
GetShannonEntropy(inputs[i])->PrintLine();
|
|
};
|
|
}
|
|
}
|