Advertisement
WarPie90

Slice

Apr 22nd, 2022 (edited)
1,172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Delphi 2.19 KB | None | 0 0
  1. program new;
  2.  
  3. function Slice(arr:TIntegerArray; start,stop:Int64; step:Int32=1): TIntegerArray;
  4. var
  5.   len:Int32;
  6.   P,R:^Int32;
  7.   L:PtrUInt;
  8. begin
  9.   len := Length(arr);
  10.   if len = 0 then Exit();
  11.  
  12.   if (step > 0) and (stop >= len)  then
  13.     stop  := len;   //not inclusive
  14.   if (step < 0) and (start >= len) then
  15.     start := len-1; //inclusive
  16.   if ((stop  < 0) and ((abs(stop) > abs(start)) or (step > 0))) then
  17.     stop  := len+stop;
  18.   if (start < 0) then
  19.     start := len+start;
  20.  
  21.   SetLength(Result, Max(0, Ceil((stop-start) / step)));
  22.   if Length(Result) = 0 then Exit();
  23.  
  24.   //WriteLn('>>> ', [start, stop, step]);
  25.  
  26.   P := @arr[start];
  27.   R := @Result[0];
  28.   L := PtrUInt(@Result[High(Result)]);
  29.   while PtrUInt(R) <= L do
  30.   begin
  31.     R^ := P^;
  32.     Inc(R);
  33.     Inc(P, step);
  34.   end;
  35. end;
  36.  
  37. function Equal(Left, Right: TIntegerArray): Boolean;
  38. begin
  39. //WriteLn([Left, Right]);
  40.   if Length(Left) <> Length(Right) then Exit(False);
  41.   If (Length(Left) = Length(Right)) and (Length(Left) = 0) then Exit(True);
  42.   Result := CompareMem(Left[0], Right[0], SizeOf(Int32)*Length(Left));
  43. end;
  44.  
  45. var
  46.   x: TIntegerArray = [0,1,2,3,4,5,6,7,8,9];
  47. begin
  48.   WriteLn Equal(Slice(x, 0,High(Int32),1),   [0, 1, 2, 3, 4, 5, 6, 7, 8,9]);
  49.   WriteLn Equal(Slice(x, High(Int32),0,-1),  [9, 8, 7, 6, 5, 4, 3, 2, 1]);
  50.   WriteLn Equal(Slice(x, 0,-1,1),   [0, 1, 2, 3, 4, 5, 6, 7, 8]);
  51.   WriteLn Equal(Slice(x, 6,0,-1),   [6, 5, 4, 3, 2, 1]);
  52.   WriteLn Equal(Slice(x, 0,6,1),    [0, 1, 2, 3, 4, 5]);
  53.   WriteLn Equal(Slice(x, 0,10,1),   [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
  54.   WriteLn Equal(Slice(x, 0,7,3),    [0, 3, 6]);
  55.   WriteLn Equal(Slice(x, 5,9,1),    [5, 6, 7, 8]);
  56.   WriteLn Equal(Slice(x, -1,0,-1),  [9, 8, 7, 6, 5, 4, 3, 2, 1]);
  57.   WriteLn Equal(Slice(x, -1,-1,-1), [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]);
  58.   WriteLn Equal(Slice(x, -3,-1, 1), [7, 8]);
  59.   WriteLn Equal(Slice(x, -1,-1, 1), []);
  60.   WriteLn Equal(Slice(x, 5,0, 1),   []);
  61.   WriteLn Equal(Slice(x, 0,5,-1),   []);
  62.   WriteLn Equal(Slice(x, 7,2,-3),   [7,4]);
  63.   WriteLn Equal(Slice(x, 7,2,-100), [7]);
  64.   WriteLn Equal(Slice(x, -4,-1, 1), [6,7,8]);
  65.   WriteLn Equal(Slice(x, -1,-4,-1), [9,8,7]);
  66.   WriteLn Equal(Slice(x, -1, 3,-1), [9, 8, 7, 6, 5, 4]);
  67. end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement