【问题标题】:How to calculate the ranges of Array?如何计算数组的范围?
【发布时间】:2014-07-16 11:11:42
【问题描述】:

如何计算数组的范围,以便将其发送到多个线程进行处理。这有效,但仅适用于较低的范围。它与数组的高值不匹配。

program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

type
  TRange = record
    High: Integer;
    Low: Integer;
  end;
  TRanges = Array of TRange;

procedure Split(const Size: Integer; const Slices: Integer; var Ranges: TRanges);
var
    SliceSize: Integer;
    SliceStart: Integer;
    I: Integer;
begin
    SliceSize := (Size + Slices) div Slices;
    SetLength(Ranges, Slices);
    SliceStart := 0;
    for I := 0 to Slices - 1 do
    begin
        Ranges[I].Low := SliceStart;
        SliceStart := SliceStart + SliceSize;
        if SliceStart > Size then
        SliceStart := Size;
        Ranges[I].High := SliceStart - 1;
    end;
end;

var
  A: TArray<Integer>;
  Ranges: TRanges;
begin
  SetLength(A, 71);
  Split(High(A), 7, Ranges); // split array in to seven ranges
  // 70 is missing from Ranges..
  ReadLn;
end.

【问题讨论】:

    标签: delphi delphi-xe6


    【解决方案1】:

    您将 High(A) 传递给 count 参数,但您应该传递 Length(A)。 High 返回最高索引,它比从零开始的数组中的元素计数小一。

    SliceSize 的计算也是错误的。 它需要是这样的:

    procedure Split(const Size: Integer; const Slices: Integer;
      var Ranges: TRanges);
    var
      SliceSize: Integer;
      SliceStart: Integer;
      LeftOver: Integer;
      I: Integer;
    begin
      SliceSize := Size div Slices;
      LeftOver := Size mod Slices;
      SetLength(Ranges, Slices);
      SliceStart := 0;
      for I := 0 to Slices - 1 do
      begin
        Ranges[I].Low := SliceStart;
        SliceStart := SliceStart + SliceSize;
        if I < LeftOver then
          Inc(SliceStart);
        Ranges[I].High := SliceStart - 1;
      end;
    end;
    

    【讨论】:

    • 传递 High(A) 是正确的,因为声明 SliceSize := (Size + Slices) div Slices; 实际上是 ("real size" + slices - 1) div Slices 并且使用 High(A) 有效地给出了“真实大小”-1。
    猜你喜欢
    • 2014-09-20
    • 2016-03-22
    • 2011-08-17
    • 1970-01-01
    • 2012-03-22
    • 1970-01-01
    • 2023-04-03
    • 2020-11-26
    相关资源
    最近更新 更多