⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 bestfit.pas

📁 《Delphi COM深入编程》原书光盘
💻 PAS
字号:
unit BestFit;

interface

uses
  Windows, ActiveX, ComObj, classes, BinIntf, BinBase;

type
  TBestFit = class(TAbstractOneDBin)
    procedure Optimize; override;
    function GetName: WideString; override;
  end;

implementation

uses
  ComServ;
  
{ TBestFit }

function TBestFit.GetName: WideString;
begin
  Result := 'Best Fit';
end;

procedure TBestFit.Optimize;
var
  Index: Integer;
  Item: TBinItem;
  BinIndex: Integer;
  BestBinIndex: Integer;
  BestValue: Integer;
begin
  FCurrentBin := nil;
  for Index := 0 to FItems.Count - 1 do begin
    Item := TBinItem(FItems[Index]);

    // Find a bin with enough room
    BestBinIndex := -1;
    BestValue := 0;
    for BinIndex := 0 to FBins.Count - 1 do begin
      FCurrentBin := TBin(FBins[BinIndex]);
      if FCurrentBin.Value + Item.Value <= FMaxValue then begin
        if (BestBinIndex = -1) or
           (FCurrentBin.Value > BestValue) then begin
          BestBinIndex := BinIndex;
          BestValue := FCurrentBin.Value;
        end;
      end;
    end;

    // if no available bin, create a new one
    if BestBinIndex = -1 then begin
      FCurrentBin := TBin.Create;
      FBins.Add(FCurrentBin);
    end;

    FCurrentBin.Items.Add(Item);
    FCurrentBin.Value := FCurrentBin.Value + Item.Value;
  end;

  FBinIndex := -1;
end;

initialization
{$IFDEF VER100}
  TComObjectFactory.Create(ComServer, TBestFit, Class_BestFit,
    'BestFit', 'Best Fit algorithm', ciMultiInstance);
{$ELSE}
  TComObjectFactory.Create(ComServer, TBestFit, Class_BestFit,
    'BestFit', 'Best Fit algorithm', ciMultiInstance, tmApartment);
{$ENDIF}
end.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -