SAIL - Reindex - Funkcja przesuwająca elementy w tablicy z miejsca x na miejsce y

Gotowe kody SAIL'a, informacje na temat moddingu, itd.

Moderator: zoNE

Post Reply
User avatar
zoNE
The Great Uniter & Site Administrator
The Great Uniter & Site Administrator
Posts: 2059
Joined: Fri Feb 17, 2006 3:44 pm
Location: Poland
Contact:

SAIL - Reindex - Funkcja przesuwająca elementy w tablicy z miejsca x na miejsce y

Post by zoNE »

Serpent wrote: Sun Jun 23, 2019 1:05 am Funkcja przesuwająca elementy w tablicy z miejsca x na miejsce y.

Code: Select all

Export Function Reindex(array, i_from, i_to, direction);
var i, j, k, d, tmp, length;
begin
result := array;

if not array or not i_from or not i_to or i_from > array or i_to > array then
   exit;
   
if direction then // ASC
   begin
   d := 1;

   if i_from > i_to then
      length := (array - i_from) + i_to
     else
      length := i_to - i_from;

   end
  else // DESC
   begin
   d := -1;

   if i_from > i_to then
      length := i_from - i_to
    else
      length := (array - i_to) + i_from;

   end;

if not length then
   exit;

// SORT
tmp := array;

for i = 1 to length do
    begin

    for j = 1 to array do
        begin
        k := j+d;

        if k > array then
           k := 1;

        if not k then
           k := array;

        tmp := Replace(tmp, k, array[j]);
        end;

    array := tmp;
    end;

result := array;
End;
Parametry:
array - tablica
i_from - miejsce z którego chcemy przesunąć wartość
i_to - miejsce na które chcemy wstawić wartość
direction - kierunek (true lub false)

Przykład #1:
Tablicę [1, 2, 3, 4, 5] chcemy przesunąć o 3 miejsca w prawo, tak aby wartość 1 znalazła się na miejscu 4.

Zatem:

Code: Select all

tab := Reindex(tab, 1, 4, true);
Otrzymamy:
[3, 4, 5, 1, 2]

Cały proces wygląda następująco:
[1*, 2, 3, 4*, 5] -> [5, 1, 2, 3, 4] -> [4, 5, 1, 2, 3] -> [3, 4, 5, 1, 2]

Przykład #2:
Pierwszy element z tablicy chcemy przesunąć na jej koniec.

Code: Select all

tab := [11, 10, 30, 40, 119, 120, 50];
tab := Reindex(tab, 1, tab, false);
Otrzymamy:
[10, 30, 40, 119, 120, 50, 11]
Author: Serpent
Topic: viewtopic.php?f=42&t=6013
Post Reply