Live Test: https://ideone.com/
Pascal Code:
program meh;
type TIntegerArray = array of Integer;
procedure Delete(var arr: TIntegerArray; index: Integer);
var
i: Integer;
begin
if (index >= 0) and (index < Length(arr)) then
begin
for i := index + 1 to high(arr) do
begin
arr[i - 1] := arr[i];
end;
SetLength(arr, Length(arr) - 1);
end;
end;
function IndexOf(var arr: TIntegerArray; value: Integer): Integer;
var
i: Integer;
begin
for i := 0 to high(arr) do
if arr[i] = value then
exit(i);
exit(-1);
end;
procedure Delete(var arr: TIntegerArray; toDelete: TIntegerArray);
var
i, j: Integer;
begin
for i := 0 to high(toDelete) do
begin
j := indexOf(arr, toDelete[i]);
if j >= 0 then
Delete(arr, j);
end;
end;
var
A: TIntegerArray;
B: TIntegerArray;
i: Integer;
begin
A := TIntegerArray.Create(1, 2, 3, 4, 5);
B := TIntegerArray.Create(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Delete(B, A);
for i := 0 to high(B) do
writeln(B[i]);
end.
Explanation..
To delete from an array, you need to perform a shift or a swap.. For example:
Simba Code:
arr := [1, 2, 3, 4, 5, 6, 7];
//We want to delete index 2. -- Value of 3.
//Therefore we shift from that index + 1 down the line until there is no space in between and the last element is duplicated..
arr := [1, 2, 3, 4, 5, 6, 7];
arr := [1, 2, 4, 4, 5, 6, 7];
arr := [1, 2, 4, 5, 5, 6, 7];
arr := [1, 2, 4, 5, 6, 6, 7];
arr := [1, 2, 4, 5, 6, 7, 7];
//Note that I added steps above to sorta show the elements moving..
//In reality a single for-loop will actually do:
arr := [1, 2, 3, 4, 5, 6, 7];
arr := [1, 2, 4, 5, 6, 7, 7];
//Now that the 3 is gone, we need to delete the last element.
arr := [1, 2, 4, 5, 6, 7];
Alternatively, you can do a swap:
Simba Code:
arr := [1, 2, 3, 4, 5, 6, 7];
//We want to delete index 2. -- Value of 3.
//Therefore we swap from that index up the line until the last element is the one we want deleted..
arr := [1, 2, 3, 4, 5, 6, 7];
arr := [1, 2, 4, 3, 5, 6, 7];
arr := [1, 2, 4, 5, 3, 6, 7];
arr := [1, 2, 4, 5, 6, 3, 7];
arr := [1, 2, 4, 5, 6, 7, 3];
//Again, a single for-loop will do fine..
//Now that the 3 is gone, we need to delete the last element.
arr := [1, 2, 4, 5, 6, 7];
You do this for every element you want to remove.. The swap is actually less efficient because swapping requires a temporary variable or xor swap (more instructions).. but in any case, you won't notice a difference.. Choose whichever method you understand.