Closed
Description
The following Mode function applies to countable sets. It obeys the rule that if all items in a sequence of values are unique then there is no mode. The following function returns an empty array in that case. If sequence in mono-modal an array of one element containing the mode is returned, while if sequence is multi-modal, an array containing all the modes is returned.
This function illustrates the case for a sequence of Integer
values. Overloads for other ordinal types are obvious.
function ModeN(const A: array of Integer): TArray<Integer>;
begin
if Length(A) = 0 then
raise EArgumentException.Create('Array is empty');
var MaxCount: Cardinal := 0;
var Counts := TDictionary<Integer,Cardinal>.Create;
try
for var X in A do
begin
var C: Cardinal;
if not Counts.TryGetValue(X, C) then
C := 0;
Inc(C);
Counts.AddOrSetValue(X, C);
if MaxCount < C then
MaxCount := C;
end;
// equivalent test?: if MaxCount = 1 then
if Length(A) = Counts.Count then
begin
// All numbers are unique => no mode
SetLength(Result, 0);
Exit;
end;
var Results := TList<Integer>.Create;
try
for KV in Counts do
begin
if KV.Value = MaxCount then
Results.Add(KV.Key);
end;
Result := Results.ToArray;
finally
Results.Free;
end;
finally
Counts.Free;
end;
end;
This issue was extracted from issue #16
Metadata
Metadata
Assignees
Projects
Status
Completed