Einzelnen Beitrag anzeigen

Cöster

Registriert seit: 6. Jun 2006
589 Beiträge
 
Turbo Delphi für Win32
 
#21

Re: aus mehreren Werten größte Kombination.

  Alt 11. Nov 2006, 16:13
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.
  Mit Zitat antworten Zitat