Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Add mode function #42

Closed
Closed
Assignees
Labels
completedIssue completed and committed to develop. To be closed on next release enhancementNew feature or request
@delphidabbler

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

Labels

completedIssue completed and committed to develop. To be closed on next release enhancementNew feature or request

Projects

Status

Completed

Milestone

No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      AltStyle によって変換されたページ (->オリジナル) /