Einzelnen Beitrag anzeigen

Schokohase
(Gast)

n/a Beiträge
 
#32

AW: Brainstorming: Datei mit definierter Entropie erzeugen

  Alt 31. Aug 2018, 13:56
Bevor ihr euch noch die Köpfe einschlagt, nehmt das hier als Diskussionsgrundlage
Delphi-Quellcode:
unit Unit1;

interface

uses
  System.Generics.Defaults, System.Generics.Collections, System.SysUtils,
  System.Math;

type
  TShannonEntropy = class
  public
    class function Calculate<T > ( const Source: array of T ): Double; overload;
    class function Calculate<T > ( const Source: array of T; const Comparer: IEqualityComparer<T> ): Double; overload;
  end;

implementation

{ TShannonEntropy }

class function TShannonEntropy.Calculate<T>( const Source: array of T; const Comparer: IEqualityComparer<T> ): Double;
var
  d: TDictionary<T, Integer>;
  i: Integer;
  p,r: Double;
begin
  d := TDictionary<T, Integer>.Create( Comparer );
  try
    for i := Low( Source ) to High( Source ) do
    begin
      if d.ContainsKey( Source[i] ) then
        d[Source[i]] := d[Source[i]] + 1
      else
        d.Add(Source[i],1);
    end;
    Result := 0;

    for i in d.Values do
    begin
      p := i / Length( Source );
      r := p * Log2( p );
      Result := Result + r;
    end;

    Result := -Result;

  finally
    FreeAndNil( d );
  end;
end;

class function TShannonEntropy.Calculate<T>( const Source: array of T ): Double;
begin
  Result := Calculate<T > ( Source, TEqualityComparer<T>.Default );
end;

end.
Das liefert dann mit
Delphi-Quellcode:
program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  Unit1 in 'Unit1.pas';

procedure Test;
var
  str: string;
  e: Double;
begin
  str := 'Grüne'#13#10'SPD'#13#10'FDP'#13#10'CSU'#13#10'CDU';
  e := TShannonEntropy.Calculate<Char > ( str.ToCharArray( ) );
  WriteLn( e );
end;

begin
  try
    Test;
  except
    on E: Exception do
      Writeln( E.ClassName, ': ', E.Message );
  end;
  ReadLn;
end.
auch die
Code:
 3.49366068968819E+0000
Grundlage dafür ist https://medium.com/udacity/shannon-e...s-5810d35d54b4
  Mit Zitat antworten Zitat