Delphi-PRAXiS
Seite 3 von 3     123   

Delphi-PRAXiS (https://www.delphipraxis.net/forum.php)
-   Sonstige Fragen zu Delphi (https://www.delphipraxis.net/19-sonstige-fragen-zu-delphi/)
-   -   Delphi aus mehreren Werten größte Kombination. (https://www.delphipraxis.net/80476-aus-mehreren-werten-groesste-kombination.html)

Cöster 11. Nov 2006 16:13

Re: aus mehreren Werten größte Kombination.
 
Hier mal eine zweite (rekursive) Lösung:

Delphi-Quellcode:
TIntArray = array of Integer;

TCombi = record
  Factors: array of Boolean;
  Value: Integer;
end;

{...}

function TForm1.GetCombi(const Ints: TIntArray; Combi: TCombi; I, Limit: Integer): TCombi;
var
  Combi2: TCombi;
begin
  Combi.Factors := Copy(Combi.Factors);
  if Combi.Factors[I] then
  begin
    Combi.Factors[I] := False;
    Dec(Combi.Value, Ints[I]);
  end;
  if I < High(Ints) then
  begin
    Combi2 := GetCombi(Ints, Combi, I + 1, Limit);
    Combi.Factors[I] := True;
    Inc(Combi.Value, Ints[I]);
    Result := GetCombi(Ints, Combi, I + 1, Limit);
    if Result.Value < Combi2.Value then
      Result := Combi2;
  end
  else
  begin
    Combi.Factors[I] := True;
    Inc(Combi.Value, Ints[I]);
    if Combi.Value > Limit then
    begin
      Combi.Factors[I] := False;
      Dec(Combi.Value, Ints[I]);
      if Combi.Value > Limit then
        Combi.Value := -1;
    end;
    Result := Combi;
  end;
end;
Zur Erklärung der Parameter:
Ints sind die Zahlen, aus denen die Kombination gefunden werden soll.
Combi speichert, welche Indizes aus Ints in der Kombination vorhanden sind und den Gesamtwert.
I ist der Index im Array von Combi, die geändert wird.
Limit ist die Obergrenze.

Wenn jemand Optimierungstipps hat, würde ich sie gerne hören.


Alle Zeitangaben in WEZ +1. Es ist jetzt 01:01 Uhr.
Seite 3 von 3     123   

Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
LinkBacks Enabled by vBSEO © 2011, Crawlability, Inc.
Delphi-PRAXiS (c) 2002 - 2023 by Daniel R. Wolf, 2024-2025 by Thomas Breitkreuz