I'm making a small Delphi program using Delphi XE5. In my code there is a dynamic boolean array and I'm no able to change the value of some of the arrays elements. I tried to initialize the array after setting it's length but it didn't help. Here is part of the code:
procedure DoSomething(names: array of string);
var startWithA: array of Boolean;
i: integer;
begin
SetLength(startWithA, Length(names)); // each element is false by default
for i := 0 to Length(names) - 1 do begin
if (names[i].indexOf('A') = 0) then begin
startWithA[i] := true; // the value is not changed after executing this line
end;
end;
end;
Your code works absolutely fine. Here is the proof:
{$APPTYPE CONSOLE}
uses
System.SysUtils;
function StartsWithAIndices(const Names: array of string): TArray<Boolean>;
var
i: Integer;
begin
SetLength(Result, Length(Names));
for i := 0 to high(Result) do begin
if (Names[i].IndexOf('A') = 0) then begin
Result[i] := true;
end;
end;
end;
var
Indices: TArray<Boolean>;
b: Boolean;
begin
Indices := StartsWithAIndices(['Bob', 'Aaron', 'Aardvark', 'Jim']);
for b in Indices do begin
Writeln(BoolToStr(b, True));
end;
Readln;
end.
Output
False
True
True
False
Perhaps your confusion stems from the fact that you assign to an array that is a local variable and whose values are never read. How can you say that the array values are not modified if you never read from them? Or perhaps you have optimizations enabled and the compiler decided to optimize away the local variable whose values are written to but never read.
As an aside, your function could be written more simply like this:
function StartsWithAIndices(const Names: array of string): TArray<Boolean>;
var
i: Integer;
begin
SetLength(Result, Length(Names));
for i := 0 to high(Result) do begin
Result[i] := Names[i].StartsWith('A');
end;
end;
Related
I want to print array of n prime number, like if the input is 5 so it'll print [2,3,5,7,11].
This is my code
program prime;
type
prime_number = array [1..10] of Integer;
var
dataset:prime_number;
n,i,j,count,angka:Integer;
function isPrime(a:Integer): Boolean;
var
i: Integer;
begin
for i := 2 to round(sqrt(a)) do
begin
if(a mod i = 0) then isPrime:=false
else isPrime:=true;
end;
end;
procedure printPrime(a:Integer;var df:prime_number);
var
number,primeCount,i: Integer;
begin
number:=2;
primeCount:=0;
while (primeCount < a) do
begin
if(isPrime(number)) then
begin
for i := 1 to a do
begin
df[i]:=number;
primeCount:=primeCount+1;
end;
end;
number:=number+1;
end;
end;
begin
write('Enter n: ');read(n);
printPrime(n,dataset);
end.
When I run the program it's totally fine, but it prints nothing instead of the array :( What's wrong with my code, anyone?
I see at least a couple of issues.
First, isPrime: You'll want to break out of the loop as soon as you see something that divides the test value, a, so it should be more like
function isPrime(a:Integer): Boolean;
var
i: Integer;
begin
for i := 2 to round(sqrt(a)) do
begin
if(a mod i = 0) then begin
isPrime:=false;
exit;
end;
end;
isPrime:=true;
end;
Then, in printPrime you have some, frankly, odd logic.
First of all, you're not printing anything anywhere within that procedure.
Then, when you do find a prime, you initialize all values in df up to the size with that value, why not just set the value at primeCount? You know, as in
procedure printPrime(a:Integer;var df:prime_number);
var
number,primeCount,i: Integer;
begin
number:=2;
primeCount:=0;
while (primeCount < a) do
begin
if(isPrime(number)) then
begin
primeCount:=primeCount+1;
df[primeCount]:=number;
end;
number:=number+1;
end;
end;
I work with arrays and have tested the functionality within the context of a class, like:
Ttest = class
values : array of integer;
procedure doStuff;
end;
The methods, like doStuff all operate on the values array without the need to pass the array as a parameter. This suits me and it is fast.
Now I want to use this class to work with an external array, like Ttest.create(myValues) In the constructor I could copy myValues to the internal values but that would be quite a waste and moreover, at the end the copy would have to be reversed to pass the updated values back.
My question is how can I extend this class so that it can efficiently work with an external array. In pseudo code like this:
constructor create(var myValues : array of integer);
begin
address of values := address of myValues;
doSTuff;
end;
Lesson 1
In Delphi, dynamic arrays are reference types. A variable of dynamic array type contains only a pointer to the actual dynamic array heap object, and in an assignment,
A := B
where A and B are dynamic arrays of the same type, the dynamic array heap object isn't copied. The only thing that happens is that A and B will point to the same dynamic array heap object (that is, the 32- or 64-bit B pointer is copied to A) and that the reference count of the heap object is increased by 1.
Lesson 2
When you write
constructor Create(var AValues: array of Integer);
you need to realise that this, despite the appearance, isn't a dynamic array parameter, but an open array parameter.
If you explicitly want a dynamic array parameter, you need to use such a type explicitly:
constructor Create(AValues: TArray<Integer>);
By definition, TArray<Integer> = array of Integer is a dynamic array of Integers.
Please note that the language only has two types of arrays – static and dynamic; the open array concept is only about function parameters.
If you want to work with dynamic arrays, taking advantage of their nature as reference types, I would suggest you use dynamic array parameters. Then the only thing that is passed to the function (the constructor in this case) is the pointer to the heap object. And the heap object's reference count is increased, of course.
Lesson 3 – An example
var
Arr: TArray<Integer>;
procedure Test(A: TArray<Integer>);
var
i: Integer;
begin
for i := Low(A) to High(A) do
A[i] := 2*A[i];
end;
procedure TForm1.FormCreate(Sender: TObject);
var
i: Integer;
begin
SetLength(Arr, 10);
for i := 0 to High(Arr) do
Arr[i] := i;
Test(Arr);
for i := 0 to High(Arr) do
ShowMessage(Arr[i].ToString);
end;
After SetLength, Arr points to a dynamic array heap object of reference count 1. You can see it in your RAM (press Ctrl+Alt+E, then Ctrl+G and goto Arr[0]). When you enter Test, the reference count is increased to 2 because both Arr and A refer to it. When you leave Test, the reference count is reduced back to 1 because A goes out of scope: now again only Arr refers to it.
Lesson 4
Now, a “gotcha”: if you change the number of elements of a dynamic array, it needs to be reallocated (*). Hence, a new dynamic array heap object is created with a reference count of 1, and the old object has its reference count decreased by 1 (and removed if it becomes zero).
Thus, while the previous example works as expected, the following will not:
var
Arr: TArray<Integer>;
procedure Test(A: TArray<Integer>);
var
i: Integer;
begin
SetLength(A, 5);
for i := Low(A) to High(A) do
A[i] := 2*A[i];
end;
procedure TForm1.FormCreate(Sender: TObject);
var
i: Integer;
begin
SetLength(Arr, 10);
for i := 0 to High(Arr) do
Arr[i] := i;
Test(Arr);
for i := 0 to High(Arr) do
ShowMessage(Arr[i].ToString);
end;
The SetLength will create a new dynamic array heap object with refcount 1 and copy half of the old array into this, put the new address in the local A parameter, and Test will transform this new array, not touching the old one which the global Arr variable points to. The reference count of the original heap object is decreased by one.
However, if you use a var parameter,
procedure Test(var A: TArray<Integer>);
var
i: Integer;
begin
SetLength(A, 5);
for i := Low(A) to High(A) do
A[i] := 2*A[i];
end;
it will work as before. This effectively works with Arr. If we had increased the number of elements, the array would probably have been reallocated and the global Arr variable would have been updated with the new address.
Conclusion
As long as you don't need to reallocate the memory (change the number of elements), Delphi already gives you what you want, because dynamic arrays are reference types. If you do need to reallocate, at least now you know enough of the technical details in order to reason about it.
Update: Hence, the suggestion is to do
type
TTest = class
FData: TArray<Integer>;
constructor Create(AData: TArray<Integer>);
procedure Enlarge;
procedure Shrink;
procedure ShowSum;
end;
{ TTest }
constructor TTest.Create(AData: TArray<Integer>);
begin
FData := AData; // will NOT copy the array, since dynamic arrays are reference types
end;
procedure TTest.Enlarge;
var
i: Integer;
begin
for i := 0 to High(FData) do
FData[i] := 2*FData[i];
end;
procedure TTest.ShowSum;
var
s: Integer;
i: Integer;
begin
s := 0;
for i := 0 to High(FData) do
Inc(s, FData[i]);
ShowMessage(s.ToString);
end;
procedure TTest.Shrink;
var
i: Integer;
begin
for i := 0 to High(FData) do
FData[i] := FData[i] div 2;
end;
To test it:
procedure TForm1.FormCreate(Sender: TObject);
var
MyArray: TArray<Integer>;
t: TTest;
begin
MyArray := [1, 2, 3, 4, 5];
t := TTest.Create(MyArray);
try
t.ShowSum;
t.Enlarge;
t.ShowSum;
t.Shrink;
t.ShowSum;
finally
t.Free;
end;
end;
Footnotes
If you (1) decrease the number of elements and (2) the reference count is 1, typically the data isn't moved in memory. If the reference count is > 1, the data is always moved, because SetLength guarantees that the reference count of its argument is 1 when it returns.
Please what would be the fastest (and most 'elegant') way to search for FaDirection array in the multi dim. FdVSubs array?
TaDirection = array[0..7] of TSubRect; //TSubRect = class(TObject)
Multi dim array:
FdVSubs: array[0..15] of TaDirection;
Array:
FaDirection : TaDirection;
I need to resolve if FaDirection is already stored in FdVSubs or not.
Thank You.
First and most important, you need to decide what defines two arrays as being equal. Then you'll have to adjust my code to match that definition. For the answer I'll assume arrays are equal if and only if they have identical object references at each corresponding position in the arrays.
function DirectionsAreEqual(const ADirection1, ADirection2: TaDirection): Boolean;
var
LoopI: Integer;
begin
Result := True;
for LoopI := Low(TaDirection) to High(TaDirection) do
begin
if (ADirection1[LoopI] <> ADirection2[LoopI]) then
begin
Result := False;
Exit;
end;
end;
end;
function DirectionExistsIn(const ADirection: TaDirection;
const ADirectionList: array of TaDirection): Boolean;
var
LoopI: Integer;
begin
Result := False; //Caters for empty DirectionList
for LoopI := Low(ADirectionList) to High(ADirectionList) do
begin
Result := DirectionsAreEqual(ADirection, ADirectionList[LoopI]);
if (Result) then
begin
Exit;
end;
end;
end;
//Then you can simply do the test as follows:
if DirectionExistsIn(FaDirection, FdVSubs) then ...
NOTES
DirectionExistsIn uses an Open Array, so it doesn't matter how many elements are defined for the FdVSubs array.
A small change to DirectionExistsIn can allow you to return the position of the duplicate.
This question already has answers here:
How do I declare an array when I don't know the length until run time?
(2 answers)
Closed 9 years ago.
This post was edited and submitted for review 4 months ago and failed to reopen the post:
Original close reason(s) were not resolved
I have a procedure in Delphi which currently looks like this:
Procedure Time.TimeDB(algorithm: string; Encode, Decode: InputFunction; N, R: Int);
VAR
i : LongInt;
Errors : Array[N] of LongInt;
BEGIN
for i := 0 to N-1 do
Errors[i] := 0;
END;
I'm given the error that N, as passed to the definition of Errors, is an undeclared identifier, despite declaring it in the procedure definition. N is recognized in the BEGIN-END section, though. Any ideas what's causing this and how I can otherwise declare a variable-length array in the VAR section?
You write array of Int to declare a dynamic array of Ints:
procedure Time.TimeDB(algorithm: string; Encode, Decode: InputFunction; N, R: Int);
var
i: int;
errors: array of Int;
begin
SetLength(errors, N);
for i := 0 to N - 1 do
Errors[i] := 0;
end;
Also notice that if an array has N elements, then they are indexed 0, 1, ..., N - 1. There is no element indexed N.
(Also, are you sure you don't mean integer when you write Int?)
The construct array[M..N] of Int is called a static array. In this case, M and N must be constants, like array[0..15] of TColor. You also got the static array declaration array[TMyType] of TMySecondType where the index will be of type TMyType, as in array[byte] of TColor or array[TFontStyle] of cardinal.
In your code your initializing your Errors Array to zero...Note with SetLength you don't need to do this...just set the Array to 0 and then set it to the length you want, and then just assign the values you need.
procedure WorkArrays(var aWorking: array of integer);
begin
if High(aWorking) >= 0 then
aWorking[0] := 1;
if High(aWorking) >= 3 then
aWorking[3] := 5;
end;
procedure WorkArrays2(var aWorking: array of integer);
begin
if High(aWorking) >= 1 then
aWorking[1] := 4;
if High(aWorking) >= 9 then
aWorking[9] := 7;
end;
procedure WorkArrays3(var aWorking: TIntArray);
begin
SetLength(aWorking, 4);
aWorking[0] := 1;
aWorking[3] := 5;
end;
procedure WorkArrays4(var aWorking: TIntArray);
begin
SetLength(aWorking, 10);
aWorking[1] := 4;
aWorking[9] := 7;
end;
procedure TForm58.ShowArrays(aWorking: array of integer);
var
a_Index: integer;
begin
for a_Index := Low(aWorking) to High(aWorking) do
Memo1.Lines.Add(IntToStr(aWorking[a_Index]));
end;
procedure TForm58.ShowArrays2(aWorking: TIntArray);
var
a_Index: integer;
begin
for a_Index := Low(aWorking) to High(aWorking) do
Memo1.Lines.Add(IntToStr(aWorking[a_Index]));
end;
procedure TForm58.Button1Click(Sender: TObject);
var
a_MyArray: array of integer;
a_MyArray1: TIntArray;
begin
SetLength(a_MyArray, 3);//note this is a Zero based Array...0 to 2
WorkArrays(a_MyArray);//note aWorking[3] will not show...because High is 2...
ShowArrays(a_MyArray);
SetLength(a_MyArray, 0);
SetLength(a_MyArray, 10);//note this is a Zero based Array...0 to 9
WorkArrays2(a_MyArray);
ShowArrays(a_MyArray);
WorkArrays3(a_MyArray1);
ShowArrays2(a_MyArray1);
WorkArrays4(a_MyArray1);
ShowArrays2(a_MyArray1);
end;
end.
Summarization:
Please check the comments below from David, Uwe, and other experts.
================================================================================
The following code swaps two rows in a two-dimensional, dynamic array of double values. I am wondering: (1) whether the following code is a best practice of swapping two rows of a two-dimensional array? If not, then what is the best practice to do this kind of job? (2) why would the following code work? I mean, isn't two-dimensional array a continuous contiguous section of memory? Does the following code work only by luck? Any suggestion is appreciated!
unit Unit5;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs;
type
TAADouble = array of array of Double;
TForm5 = class(TForm)
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form5: TForm5;
procedure SwapRows(arr: TAADouble; row0, row1: Integer);
implementation
{$R *.dfm}
procedure SwapRows(arr: TAADouble; row0, row1: Integer);
var
Tmp: Integer;
begin
{$IFDEF FPC}
Tmp := PtrUInt(arr[row0]);
PtrUInt(arr[row0]) := PtrUInt(arr[row1]);
PtrUInt(arr[row1]) := Tmp;
{$ELSE}
Tmp := Integer(arr[row0]);
Integer(arr[row0]) := Integer(arr[row1]);
Integer(arr[row1]) := Tmp;
{$ENDIF}
end;
procedure TForm5.FormShow(Sender: TObject);
var
tmpArray: TAADouble;
I, J: Integer;
rowStr: string;
begin
SetLength(tmpArray, 10, 10);
rowStr := '';
for I := 0 to 9 do
for J := 0 to 9 do
tmpArray[I][J] := I * J;
for I := 0 to 9 do
begin
rowStr := '';
for J := 0 to 9 do
rowStr := rowStr + FloatToStr(tmpArray[I][J]) + ' ';
OutputDebugString(PWideChar(rowStr));
end;
SwapRows(tmpArray, 3, 4);
for I := 0 to 9 do
begin
rowStr := '';
for J := 0 to 9 do
rowStr := rowStr + FloatToStr(tmpArray[I][J]) + ' ';
OutputDebugString(PWideChar(rowStr));
end;
end;
end.
You ask:
Does the following code work only by
luck?
Well, yes, you are relying on implementation specific details.
In fact the correct way to write it is perfectly natural and simple:
type
TDoubleArray = array of Double;
TDoubleMatrix = array of TDoubleArray;
procedure SwapRows(M: TDoubleMatrix; Row1, Row2: Integer);
var
Temp: TDoubleArray;
begin
Temp := M[Row1];
M[Row1] := M[Row2];
M[Row2] := Temp;
end;
You need to declare an intermediate type for the row, TDoubleArray, so that you can perform the assignment to Temp in the swap routine.
A 2D constant size array
array [1..M] of array [1..N] of TMyType
is a contiguous block of memory.
A 2D dynamically size array as you have is not. Indeed it can even be ragged in the sense that the rows have different numbers of columns. So you can have, say, a triangular matrix.
A dynamic array is implemented as a pointer to a memory block representing that array. So a two-dimensional dynamic array is actually a pointer to an array of pointers. Thats why swapping the row(-pointer)s actually works.
See David's answer for a cleaner approach.
Update:
If you are allowed to use generics you might as well do this:
procedure <SomeClassOrRecord>.SwapRows<T>(var arr: TArray<T>; row0, row1: Integer);
var
Tmp: T;
begin
Tmp := arr[row0];
arr[row0] := arr[row1];
arr[row1] := Tmp;
end;