I have 45 values stored in an array, sample
. It needs to be split into three individual arrays of size 15, sample1
, sample2
and sample3
: the first 15 items into sample1
, the next 15 into sample2
and the remaining 15 into sample3
. I tried to do that with this code:
var
sample: array of integer; // Source Array which contains data
sample1, sample2, sample3: array of integer; //Target arrays which needs to be worked upon
i: integer;
begin
SetLength(sample1, 15);
SetLength(sample2, 15);
SetLength(sample3, 15);
for i := 0 to 14 do
sample[i] := sample1[i];
for i:= 15 to 29 do
sample[i] := sample2[i];
for i:= 30 to 44 do
sample[i] := sample3[i];
i := i + 1;
I am able to get the results in the first array, but not in the other arrays. What am I doing wrong?
If I understand you well, the following is what you want. I assume your sample
array has exactly 45 items, so you probably want to do this:
var
sample: array of Integer;
sample1, sample2, sample3: array of Integer;
i: Integer;
begin
SetLength(sample, 45);
{ fill sample with values }
...
{ now split: }
SetLength(sample1, 15);
SetLength(sample2, 15);
SetLength(sample3, 15);
for i := 0 to 14 do
begin
sample1[i] := sample[i];
sample2[i] := sample[i + 15]; { i = 0..14, so i+15 = 15..29 }
sample3[i] := sample[i + 30]; { i = 0..14, so i+30 = 30..44 }
end;
That should do the trick. If this is not what you wanted, then you should specify your problem a bit better. If you sample
array is longer, this won't split all of it. If your sample
array is shorter, you'll get an overflow, causing an error or undefined behaviour.