Pascal - Incompatible type: Got "Array Of Extended", expected "QWord" / error - sorting

I am trying to sort an array of 100000 extended numbers using a quicksort algorithm, but I keep getting the following errors when calling the procedure:
source.pas(69,26) Error: Incompatible type for arg no. 1: Got "Array[1..100000] Of Extended", expected "QWord"
source.pas(69,36) Error: Incompatible type for arg no. 1: Got "Array[1..100000] Of Extended", expected "QWord"
program test;
type
TVector = array of double;
var
N,M,i,x:longint;
a,b,c,apod,af: Array[1..100000] of extended;
procedure QuickSort(var apod: TVector; iLo, iHi: Integer) ;
var Lo, Hi: Integer;
pivot,t: double;
begin
if (iHi-iLo) <= 0 then exit;
Lo := iLo;
Hi := iHi;
Pivot := apod[(Lo + Hi) div 2];
repeat
while A[Lo] < Pivot do Inc(Lo);
while A[Hi] > Pivot do Dec(Hi);
if Lo <= Hi then
begin
T := apod[Lo];
apod[Lo] := apod[Hi];
apod[Hi] := T;
Inc(Lo) ;
Dec(Hi) ;
end;
until Lo > Hi;
if Hi > iLo then QuickSort(apod, iLo, Hi) ;
if Lo < iHi then QuickSort(apod, Lo, iHi) ;
end;
begin
{a[i],b[i],c[i],af[i],N,M are initialiazed here}
apod[i]:=(a[i]-((a[i]*b[i])/3000)-((c[i]*a[i])/40));
end;
begin
QuickSort(apod, Lo(apod), Hi(apod)) ;
end;
end.
How can I fix this?

You have several syntactical errors in your code. I did not check if your quicksort is actually correct. You can debug that.
Array types
You are confusing several different things:
dynamic arrays (e.g. type array of double),
static arrays (e.g. type array[a..b] of double) and probably
open array parameters (parameter array of double).
Your parameter is a dynamic array type (TVector), but you pass a static array. These are not compatible.
To be able to pass a dynamic as well as a static array, you can use the mentioned open array parameters (note that they look like, but are not the same as dynamic arrays).
procedure QuickSort(var apod: array of Double; iLo, iHi: Integer);
More about open array parameters in an article of mine: Open array parameters and array of const.
Var (reference) parameters
But there is another problem: var parameters must have the exact type (or base type). No conversion will take place. So your a, b, c, apod and af parameters must contain Doubles too:
var
a, b, c, apod, af: array[1..100000] of Double;
Unbound blocks
Then the loose begin endblocks after the QuickSort function don't make sense. That is not Pascal. Rather do something like this in the main block (the last begin ... end. — note the final .):
begin
for i := Low(apod) to High(apod) do
apod[i] := (a[i] - ((a[i] * b[i]) / 3000) - ((c[i] * a[i]) / 40));
QuickSort(apod, Low(apod), High(apod));
end.
But note that the code above doesn't make a lot of sense. Probably all values in apod will be 0, since a, b, c, etc. are not initialized yet (so a[i] etc. are probably all 0).
I have no idea where you got that code, but you may want to try to understand it, before you start translating it to Pascal.
Lo and Hi
Note that you should use Low and High. Lo and Hi are something totally different: they get the low and high byte of a 16 bit word, respectively. Low and High get the bounds of arrays, sets and types.

Related

Dynamic array in Turbo Pascal

I am working on my school project and I would like to use Dynamic (not static) array. I worked with ObjectPascal, so I am used to some syntax. But now I am programming in the old TurboPascal (I am using Turbo Pascal 7 for Windows).
It doesn't seem to know the ObjectPascal, so I thought, that you Turbo Pascal doesn't know dynamic arrays.
Could anyone tell me, if my theory is right or not? I tried to google, but I was not succesfull.
Basicly I am asking "how is it with dynamic arrays in Turbo Pascal 7" ?
Thank you for all reactions.
As MartynA says, there is no dynamic array type in Turbo Pascal. You need to manually allocate memory using pointers, and be careful if you use rangechecks.
Typically you define an array type
TYPE
TArrayT = array[0.. ((65535-spillbytes) div sizeof(T))-1] of T;
where spillbytes is a constant for a small deduction because you can't use the whole 64k, see what the compiler accepts. (Probably this deduction is for heapmanager structures inside the 64k block)
Then you define a pointer
PArrayT= ^TArrayT;
and a variable to it
var
P : PArrayT;
and you allocate nrelement elements using getmem;
getmem(P,SizeOf(T) * nrelements);
and optionally fill them with zero to initialize them:
fillchar(p^,SizeOf(T) * nrelements,#0);
You can access elements using
p^[index]
to free them, use freemem using the exact opposite of the getmem line.
freemem(P,Sizeof(T)*nrelements);
Which means you have to save the allocated number of elements somewhere. This was fixed/solved in Delphi and FPC.
Also keep in mind that you can't find bugs with rangechecking anymore.
If you want arrays larger than 64k, that is possible, but only with constraints, and it matters more which exact TP target (dos, dos-protected or Windows you use) I advise you to search for the online SWAG archive that has many examples. And of course I would recommend to go to FreePascal/Lazarus too where you can simply do:
var x : array of t;
begin
setlength(x,1000000);
and be done with it without additional lines and forget about all of this nonsense.
I'm using Turbo Pascal 5.5 and to create a dynamic array, perhaps the trick is to declare an array with zero dimension as follows:
dArray = array [0..0] of integer;
And then declare a pointer to that array:
pArray = ^dArray ;
And finally, create a pointer variable:
ArrayPtr : pArray;
You can now reference the pointer variable ArrayPtr as follows:
ArrayPtr^[i]; { The index 'i' is of type integer}
See the complete example below:
{
Title: dynarr.pas
A simple Pascal program demonstrating dynamic array.
Compiled and tested with Turbo Pascal 5.5.
}
program dynamic_array;
{Main Program starts here}
type
dArray = array [0..0] of integer;
pArray = ^dArray ;
var
i : integer;
ArrayPtr : pArray;
begin
for i := 0 to 9 do { In this case, array index starts at 0 instead of 1. }
ArrayPtr^[i] := i + 1;
writeln('The Dynamic Array now contains the following:');
writeln;
for i := 0 to 9 do
writeln(ArrayPtr^[i]);
end.
In this example, we have declared the array as:
array[0..0] of integer;
Therefore, the index starts at 0 and if we have n elements, the last element is at index n-1 which is similar to array indexing in C/C++.
Regular Pascal arrays start at 1 but for this case, it starts at 0.
unit Vector;
interface
const MaxVector = 8000;
// 64 k div SizeOf(float); number of float-values that fit in 64 K of stack
VectorError: boolean = False;
// toggle if error occurs. Calling routine can handle or abort
type
VectorStruc = record
Length: word;
Data: array [1..MaxVector] of float;
end;
VectorTyp = ^VectorStruc;
procedure CreateVector(var Vec: VectorTyp; Length: word; Value: float);
{ Generates a vector of length Length and sets all elements to Value }
procedure DestroyVector(var Vec: VectorTyp);
{ release memory occupied by vector }
procedure SetVectorElement(var Vec: VectorTyp; n: word; c: float);
function GetVectorElement(const Vec: VectorTyp; n: word): float;
implementation
var ch: char;
function WriteErrorMessage(Text: string): char;
begin
Write(Text);
Read(WriteErrorMessage);
VectorError := True; // toggle the error marker
end;
procedure CreateVector(var Vec: VectorTyp; Length: word; Value: float);
var
i: word;
begin
try
GetMem(Vec, Length * SizeOf(float) + SizeOf(word) + 6);
except
ch := WriteErrorMessage(' Not enough memory to create vector');
exit;
end;
Vec^.Length := Length;
for i := 1 to Length do
Vec^.Data[i] := Value;
end;
procedure DestroyVector(var Vec: VectorTyp);
var
x: word;
begin
x := Vec^.Length * SizeOf(float) + SizeOf(word) + 6;
FreeMem(Vec, x);
end;
function VectorLength(const Vec: VectorTyp): word;
begin
VectorLength := Vec^.Length;
end;
function GetVectorElement(const Vec: VectorTyp; n: word): float;
var
s1, s2: string;
begin
if (n <= VectorLength(Vec)) then
GetVectorElement := Vec^.Data[n]
else
begin
Str(n: 4, s1);
Str(VectorLength(Vec): 4, s2);
ch := WriteErrorMessage(' Attempt to read non-existent vector element No ' +
s1 + ' of ' + s2);
end;
end;
procedure SetVectorElement(var Vec: VectorTyp; n: word; C: float);
begin
if (n <= VectorLength(Vec)) then
Vec^.Data[n] := C
else
ch := WriteErrorMessage(' Attempt to write to non-existent vector element');
end;
end.
As long as your data fit on the stack, i.e., are smaller than 64 kB, the task is relatively simple. The only thing I don't know is where the 6 bit of extra size go, they are required, however.

How to use a variable in an array?

I'm using PASCAL for a course i'm doing and i'm having trouble with an assignment, in my program i'm using 2 arrays that uses a variable from a user's input but when i go to run the program it comes up with, Error: Can't evaluate constant expression. The code for the array is:
Var
x : integer;
s : array[1..x] of real;
n : array[1..x] of string[30];
Here x is the user's input, is there a way for an array to go from 1 to x?
If x is a variable, that won't work indeed. The range of a so called static array must be a constant expression, i.e. it must be known at compile time.
So what you want won't work, as is.
In FreePascal, you can use dynamic arrays, though. Their lengths can be set and changed at runtime.
var
x: Integer;
s: array of Real;
n: array of string[30]; // why not just string?
and later:
x := someUserInput(); // pseudo code!
SetLength(s, x);
SetLength(n, x);
You should be aware of the fact that dynamic arrays are 0-based, so your indexes run from 0 up to x - 1. But for the limits of the array, you should rather use Low() and High() instead:
for q := Low(s) to High(s) do
// access s[q];
(Low() and High() are not the topic, but just know they can also be used for static arrays, and that they return the actual array bounds -- I always use High and Low for this)
Here is not so simple as using managed types like dynamic arrays suggested by #RudyVelthuis but more funny solution providing some comprehension
about how it works internally :)
program dynarr;
{$mode objfpc}{$H+}
type
TArrayReal = array[1..High(Integer)] of Real;
TArrayString30 = array[1..High(Integer)] of string[30];
PArrayReal = ^TArrayReal;
PArrayString30 = ^TArrayString30;
var
i: Integer;
x: Integer;
s: PArrayReal;
n: PArrayString30;
begin
Write('Count: '); Readln(x);
// Allocate memory for the actual count of the elements
s := GetMem(SizeOf(Real) * x);
n := GetMem(SizeOf(string[30]) * x);
try
for i := 1 to x do
begin
Write('Row ', i:3, ': '); Readln(s^[i], n^[i]);
end;
Writeln('Your input was:');
for i := 1 to x do
Writeln('Row ', i:3, ': ', s^[i]:10:3, n^[i]: 20);
finally
// Do not forget to release allocated memory
FreeMem(s);
FreeMem(n);
end;
end.

How do i compare 3 numbers in Pascal?

i'm a newbie
and I need how to compare 3 numbers in Pascal.
Here is what I tried so far
BEGIN
max:=A;
IF B>A THEN max:= B;
IF C>B THEN max:= C;
END;
but when I choose, for example, A = 5 , B=2 , C=4, the output is 4, but it should be 5. Where is the problem?
I want at the end writeln('The Large Number is ',max);
You could do this (you should be comparing with max)
BEGIN
max:=A;
IF B>max THEN max:= B;
IF C>max THEN max:= C;
END;
You must compare with max instead of A or B.
Changing your code in a easy way:
BEGIN
max := A;
IF B > max
THEN
max := B;
IF C > max
THEN
max := C;
END;
Or, in a somewhat recent Pascal, like Delphi or Free Pascal, using the max function from the MATH unit.
result:=max(a,max(b,c));
Using the Max Function of Pascal
PROGRAM MaxProgram;
USES math;
VAR
num1,num2,num3,maxNum : INTEGER;
BEGIN
(* Receive the Values *)
WRITELN('Enter First Number');
READLN(num1);
WRITELN('Enter Second Number');
READLN(num2);
WRITELN('Enter Third Number');
READLN(num3);
(* Using the Max Function *)
maxNum := max(num1,max(num2,num3));
(* Display Result *)
writeln('The Highest number is ', MAXNUM);
END.

Change array type: 8bit type to 6bit type

I have two types and two arrays of that types in file.ads
type Ebit is mod 2**8;
type Sbit is mod 2**6;
type Data_Type is array (Positive range <>) of Ebit;
type Changed_Data_Type is array (Positive range <>) of Sbit;
and function:
function ChangeDataType (D : in Data_Type) return Changed_Data_Type
with
Pre => D'Length rem 3 = 0 and D'Last < Positive'Last / 4,
Post => ChangeDataType'Result'Length = 4 * (D'Length / 3)
Ok i can understand all of this.
For example we have arrays of:
65, 66, 65, 65, 66, 65 in 8bit values function should give to us 16, 20, 9, 1, 16, 20, 9, 1 in 6bit values.
I dont know how i can build a 6bit table from 8 bit table.
My idea of sollutions is for example taking bit by bit from type:
fill all bites in 6bit type to 0 (propably default)
if first bit (2**1) is 1 set bit (2**1) in 6bit type to 1;
and do some iterations
But i dont know how to do this, always is a problem with types. Is this good idea or i can do this with easier way? I spend last nigt to try write this but without success.
Edit:
I wrote some code, its working but i have problem with array initialization.
function ChangeDataType (D: in Data_Type) return Changed_Data_Type
is
length: Natural := (4*(D'Length / 3));
ER: Changed_Data_type(length);
Temp: Ebit;
Temp1: Ebit;
Temp2: Ebit;
Actual: Ebit;
n: Natural;
k: Natural;
begin
n := 0;
k := 0;
Temp := 2#00000000#;
Temp1 := 2#00000000#;
Temp2 := 2#00000000#;
Array_loop:
for k in D'Range loop
case n is
when 0 =>
Actual := D(k);
Temp1 := Actual / 2**2;
ER(k) := Sbit(Temp1);
Temp := Actual * ( 2**4);
n := 2;
when 2 =>
Actual := D(k);
Temp1 := Actual / 2**4;
Temp2 := Temp1 or Temp;
ER(k) := Sbit(Temp2);
Temp := Actual * ( 2**2);
n := 4;
when 4 =>
Actual := D(k);
Temp1 := Actual / 2**6;
Temp2 := Temp1 or Temp;
ER(k) := Sbit(Temp2);
n := 6;
when 6 =>
Temp1 := Actual * ( 2**2);
Temp2 := Actual / 2**2;
ER(k) := Sbit(Temp2);
n := 0;
when others =>
n := 0;
end case;
end loop Array_Loop;
return ER;
end;
IF I understand what you're asking... it's that you want to re-pack the same 8-bit data into 6-bit values such that the "leftover" bits of the first EBit become the first bits (highest or lowest?) of the second Sbit.
One way you can do this - at least for fixed size arrays, e.g. your 6 words * 8 bits, 8 words * 6 bits example, is by specifying the exact layout in memory for each array type, using packing, and representation aspects (or pragmas, before Ada-2012) which are nicely described here.
I haven't tested the following, but it may serve as a starting point.
type Ebit is mod 2**8;
type Sbit is mod 2**6;
for Ebit'Size use 8;
for Sbit'Size use 6;
type Data_Type is array (1 .. 6) of Ebit
with Alignment => 0; -- this should pack tightly
type Changed_Data_Type is array (1 .. 8) of Sbit
with Alignment => 0;
Then you can instantiate the generic Unchecked_Conversion function with the two array types, and use that function to convert from one array to the other.
with Ada.Unchecked_Conversion;
function Change_Type is new Ada.Unchecked_Conversion(Data_Type, Changed_Data_Type);
declare
Packed_Bytes : Changed_Data_Type := Change_Type(Original_Bytes);
begin ...
In terms of code generated, it's not slow, because Unchecked_Conversion doesn't do anything, except tell the compile-time type checking to look the other way.
I view Unchecked_Conversion like the "I meant to do that" look my cat gives me after falling off the windowledge. Again...
Alternatively, if you wish to avoid copying, you can declare Original_Bytes as aliased, and use a similar trick with access types and Unchecked_Access to overlay both arrays on the same memory (like a Union in C). I think this is what DarkestKhan calls "array overlays" in a comment below. See also section 3 of this rather dated page which describes the technique further. It notes the overlaid variable must not only be declared aliased but also volatile so that accesses to one view aren't optimised into registers, but reflect any changes made via the other view. Another approach to overlays is in the Ada Wikibook here.
Now this may be vulnerable to endian-ness considerations, i.e. it may work on some platforms but not others. The second reference above gives an example of a record with exact bit-alignment of its members : we can at least take the Bit_Order aspect, as in with Alignment => 0, Bit_Order => Low_Order_First; for the arrays above...
-- code stolen from "Rationale" ... see link above p.11
type RR is record
Code: Opcode;
R1: Register;
R2: Register;
end record
with Alignment => 2, Bit_Order => High_Order_First;
for RR use record
Code at 0 range 0 .. 7;
R1 at 1 range 0 .. 3;
R2 at 1 range 4 .. 7;
end record;
One thing that's not clear to me is if there's a formulaic way to specify the exact layout of each element in an array, as is done in a record here - or even if there's a potential need to. If necessary, one workaround would be to replace the arrays above with records. But I'd love to see a better answer if there is one.

TPascal, Stack Overflow, Recursion

My program should inverse a string (ex. for Hello world returns dlrow olleH) and it works only for strings smaller than 20 characters. For 20 or more i get "Error 202 Stack overflow". Thank you :)
Program Inv;
var S, A: String;
n: integer;
Function I(X: String; z: integer):String;
begin
if z=1 then I:=X[z] else
I:=X[z]+I(X, z-1);
end;
begin
write ('Enter your text: ');
readln (S);
n:=length(S);
A:=I(S, n);
writeln (A);
readln;
end.
Unless you are required to show a recursive solution, you're usually better to sticking with iteration(a). Recursion uses an often-limited resource (the stack) to weave its magic and is often the cause of crashes when you exceed that limit.
Iterative solutions tend to be far less restrictive, such as the code below:
program PaxCode;
Function reverse(inp_str: string) : string;
var out_str : string = '';
var idx : integer = 1;
begin
while (idx <= length(inp_str)) do
begin
out_str := inp_str[idx] + out_str;
idx := idx + 1
end;
reverse := out_str
end;
var test_str: string = 'My hovercraft is full of eels and they will not let me drive it';
begin
writeln(test_str);
writeln(reverse(test_str))
end.
As you can see, the output is correct, and not limited to twenty (or twenty-nine) characters:
My hovercraft is full of eels and they will not let me drive it
ti evird em tel ton lliw yeht dna slee fo lluf si tfarcrevoh yM
(a) The best areas for recursion are those where each level removes a sizable proportion of the solution space. For example, binary searches remove fully 50% of the remaining solution space on every level so you could search through a structure holding four billion entries with just thirty-two levels, since 232 is a touch above 4.2 billion.
Something like reversing a 400-character string will take, ..., let me think, oh yes, 400 levels. That won't necessarily end well :-)

Resources