is there solution in Delphi 7 for deynamically creating for-loop cycles?
for example, i want to have a function that generates 1..n for-cycles
for example:
function generate_binary(var number_of_loops:integer):string
var x:word
begin
for x:=1 to number_of_loops do begin
for ... cycle 1
...
...
...
for ... cycle[x]
//code
end; //cycle n
end; //cycle[x]
end;
end;
is there some code for doing that? Or i must manually set every for.. cycles?
This is not direct answer to the topic question, but an example of particular problem solving. There are more effective methods of generation (especially for numbers, not for strings).
Look at this recursive code to generate all strings with predefined length and number of 1's. Note that output size will very large for big Len (number of combination C(N,K) is exponential function)
procedure Generate01Combination(Len, OnesLeft: Integer; s: string);
begin
if Len = 0 then
Memo1.Lines.Add(s)
else begin
if Len > OnesLeft then
Generate01Combination(Len - 1, OnesLeft, s + '0');
if OnesLeft > 0 then
Generate01Combination(Len - 1, OnesLeft - 1, s + '1');
end;
end;
begin
Generate01Combination(5, 2, '');
end;
outputs
00011
00101
00110
01001
01010
01100
10001
10010
10100
11000
Yes, you can kind of "generate loops" - if you enclose them into procedures and pass those procedures as procedure pointers.
But you said for ... cycle[1] - WHAT is that "..." ? Is it for I := 1 to 4 do cycle[1]() ? Or is it for I := cycle[1] to 10 do ; ? It all fits in!
So, well, - and yes, you indeed came with XYZ problem,- I will make an answer that formally fits, I think, but is hardly to help you with your own problem.
type TLoopProc = procedure(const LoopCount: integer);
procedure Loop1(const LoopCount: integer); var i: integer;
begin
for I := 1 to LoopCount do ShowMessage('Loop1 loop is burning!');
end;
procedure Loop2(const LoopCount: integer); var i: integer;
begin
for I := 1 to LoopCount do ShowMessage('Loop2 loop is burning!');
end;
procedure Loop3(const LoopCount: integer); var i: integer;
begin
for I := 1 to LoopCount do ShowMessage('Loop3 loop is burning!');
end;
procedure Loop4(const LoopCount: integer); var i: integer;
begin
for I := 1 to LoopCount do ShowMessage('Loop4 loop is burning!');
end;
var Loops: array[1..4] of TLoopProc;
function generate_binary(const number_of_loops:integer):string
var x,y:word;
begin
Result := '1234';
for x := 1 to number_of_loops do begin
for y := 1 to x do begin
Loops[y](x+y);
end;
end;
end;
BEGIN
Loops[1] := Loop1;
Loops[2] := Loop1;
Loops[3] := Loop1;
Loops[4] := Loop1;
generate_binary(4);
END.
See, formally that does call that ever increasing number of loops.
Those loops which bodies are contained inside their own procedures.
Not that I think you really can apply that to your real task.
But coming back to your real task, it is very very different.
You are given two numbers: N <= L with N being number of "1" to position in the string of Length L.
To me it looks a slightly hidden example of mathematical induction.
Can you position one single "1" in the string? I think you can.
But if you have all the strings with a single "1" - can you position the second "1" to the right of it? And then the 3rd "1" ?
So we would not search for the strings, we would search for ones' positions, sequences like 4-6-8-9-15-16-29-....
var results: iJclStringList;
// here it is just like TStringList, but interface-based, thus needs no `.Free`
type OnePositions = array of integer;
procedure Error;
begin
raise Exception.Create ('We badly screwed'); // or whatever you would make it do
end;
procedure StoreResult( const L: integer; const P1: OnePositions );
var R: string; i,Prev1,Next1: integer;
begin
R := StringOfChar( '0', L );
Prev1 := 0;
// if those Low/High functions are not yet implemented in Delphi7,
// you may run the loop from 0 to Prev(Length(P1))
// to go through all the P1 array elements
for i := Low(P1) to High(P1) do begin
Next1 := P1[i]; // position for next "1"
if Next1 > Length(R) then Error; // outside of string
if Prev1 >= Next1 then Error; // Next "1" is left of previous "1"
R[Next1] := '1';
Prev1 := Next1; // tracing what was the right-most "1" inserted
end;
Results.Add(R);
end;
// L - string length, thus maximum position of "1"
// StartAt - the leftmost (minimal) position of the 1st left "1" to place
// positions < StartAt already were taken
// Rest1s - how many "1" left to be placed (we still have to place)
procedure PositionRest(var Pos: OnePositions; const L, StartAt, Rest1s: integer);
var Max, idx, NextRest1s, i: integer;
begin
idx := Length(Pos) - Rest1s; // number of "1" we are setting now
NextRest1s := Rest1s - 1; // how many "1"s to be set by next calls
Max := L - NextRest1s; // rightmost part of string we have to leave free for next "1" to be placed
for i := StartAt to Max do begin
Pos[idx] := i; // placing our dear "1" here or there
if NextRest1s = 0 // did we maybe just positioned the last "1" ?
then StoreResult( L, Pos )
else PositionRest( Pos, L, i+1, NextRest1s);
end;
end;
procedure GenerateAll( const L,N: integer );
var Ones: OnePositions;
begin
results := JclStringList();
SetLength(Ones,N);
PositionRest(Ones, L, 1, N);
Memo1.Lines.Text := results.Text;
results := nil;
end;
var L: integer = 20; N: integer = 7;
GenerateAll( L,N );
Here are results at Phenom X3 710 2.6GHz CPU from CodeTyphon 5.60 and Delphi XE2: http://imgur.com/a/22B9b - 4 variants.
Example:
Only single core was used, would have to think how to make it parallelized;
Sources and Win32 EXE: http://rghost.ru/7lYwX2B4Y and http://rghost.ru/8RHmCKF4D
Project1 built by CT 5.60 and Project2 built by Delphi XE2
PS. Some general advices.
Whenever you can - use const parameters to functions. Only use var parameters when you know what it is and why you do need that. It is very rarely needed !
Do not use word for looping. Today CPU runs in 32 bits or 64 bits ( for Delphi 7 - only 32 bits ) - so use CPU-native type integer or cardinal, it would make it slightly easier for the hardware and 65535 maximum value for word might be too small sometimes.
Delphi 7 is good but old. Did you purchased it? Why to stick with it today? I think you better either purchase modern Delphi version or take free Lazarus/FPC suite (i'd stick with CodeTyphon distro, without controversial Orca);
PPS. I implemented OTL-based multithreading approach.
On a somewhat good note, I had to implement exactly dynamic number of loops approach.
As was expected MT-decoupling required extensive memory copying and multiple FastMM calls, which is uni-threaded by design, so multithreading was nothing but illusion and results were even worse than I expected -
still even that crippled MT-ing would provide to "show first 100 results while others are not being calculated yet.
I could enhance it here and there, getting rid of intermediate dynamics arrays (using lists and pointers instead) and switching to MT-oriented Heap Memory Manager, but that would clearly overflow the topic-started experience. It would be challenging to make most fast implementation, but since no one cares, then be it. Still this task was interesting synthetic example for pushing some OTL features and bounds.
Related
My math may not be serving me well. I've written a simple recursive function in Verilog to calculate value of log base 2. Log2(1000) should return 9.965 rounded to 10. But, my simulation shows that the function returns 9 as the final value of the recursive function. Any idea what I'm doing wrong?
module test;
real numBits;
function real log2 (input int X);
if (X == 1)
log2 = 0.0;
else begin
log2 = log2(X / 2) + 1.0;
$display($stime,,,"log2 = %0d",log2);
end
endfunction
initial begin
numBits = log2(1000);
$display($stime,,,"numBits = %f",numBits);
end
endmodule
Here's the EDA playground link that shows the code:
https://www.edaplayground.com/x/icx7
A couple of problems with your code. The first is the input to your function needs to be real. Then, it's never good to compare real numbers with equality do to rounding errors. Use X<=1 instead. And finally you should declare recursive functions with an automatic lifetime so that the arguments and the return values do not get overwritten.
function automatic real log2 (input real X);
if (X <= 1)
log2 = 0.0;
else begin
log2 = log2(X / 2) + 1.0;
$display($stime,,,"log2 = %0g",log2);
end
endfunction
The following example in Pascal was given in a book dedicated to the basics of programming. The function ReadLongint is supposed to check whether the input is 0-9 encoded in a char type. The function then returns true or false depending on the check results, as well as a variable for calculations, rendered into an integer via the operator ord().
Being a newbie I've had hard times figuring out how exactly this code works. But even the bigger mystery for me was the necessity of line 9.
'repeat
read(c);
position := position + 1;
until (c <> #32) and (c <> #10);'
I can see that it's a cycle which repeats itself if you input Space or Enter. However, I've checked the program without these lines, substituting it with a simple read(c); , and the program seems to work just fine. Can somebody please explain the role of this line in the example?
Here is the full program:
function ReadLongint(var check: longint): boolean;
var
c: char;
number: longint;
position: integer;
begin
number := 0;
position := 0;
repeat
read(c);
position := position + 1;
until (c <> #32) and (c <> #10);
while (c <> #32) and (c <> #10) do
begin
if (c < '0') or (c > '9') then
begin
writeln('Unexpected ''', c, ''' in position: ', position);
readln;
ReadLongint := false;
exit
end;
number := number * 10 + ord(c) - ord('0');
read(c);
position := position + 1
end;
check := number;
ReadLongint := true
end;
var
x, y: longint;
ok: boolean;
begin
repeat
write('Please type the first number: ');
ok := ReadLongint(x)
until ok = true;
repeat
write('Please type the second number: ');
ok := ReadLongint(y)
until ok = true;
writeln(x, ' times ', y, ' is ', x * y)
end.
Your readLongInt function wants to (partially) mimic the behavior of read/readLn. The behavior of read/readLn differs slightly if the destination variable is an integer (or real) or char value. The ISO Standard 7185 puts it like that:
c) If v is a variable-access possessing the integer-type (or subrange thereof), read(f, v) shall satisfy the following requirements. No component of s shall equal end‑of‑line. The components of r, if any, shall each, and (s ~t ~u).first shall not, equal either the char-type value space or end‑of‑line. […]
Translated to plain English: Leading spaces and newlines are ignored when interpreting a number (i. e. an integer [or real] variable as the destination). This is quite different to read/readLn in conjunction with a char‑variable where ' ' is a legal value, thus it is not “skipped”, you know.
The until (c <> #32) and (c <> #10) loop is trying to imitate the behavior of read(check) although the actually used read(c) merely reads a single char value, one after another.
PS: It always makes me cringe seeing ok = true. I hope you, unlike the author(s) of the textbook, knows that the = true is redundant, merely an identity.
Need your help (I'm stuck on searching for). I'm on Delphi Seattle, trying to make smooth resizing bottom of my form. In my case "resizing" is just a little collapse/expand like this:
How can I realize that?
I've tried use a TTimer:
procedure TForm1.Timer1Timer(Sender: TObject);
var
h, t: integer;
begin
t := Button10.Top + Button10.Height + 10; //slide TForm from/to this point
if t > h then
begin
h := h + 1;
Form1.Height := h;
end
else
begin
Timer1.Enabled := false;
end;
end;
... but it's looks very simple (no acceleration/deceleration) and works slow even with small interval.
There's no need to get complicated with TTimers. This will take care of both collapsing and expanding forms including the smoothness that you require.
The trick is to calculate each step by taking the Target Size - Current Height and div 3 at each iteration, which will both accelerate the initial collapse or expand, then decelerate as the form gets closer to its target size.
procedure TForm1.SmoothResizeFormTo(const ToSize: integer);
var
CurrentHeight: integer;
Step: integer;
begin
while Height <> ToSize do
begin
CurrentHeight := Form1.Height;
// this is the trick which both accelerates initially then
// decelerates as the form reaches its target size
Step := (ToSize - CurrentHeight) div 3;
// this allows for both collapse and expand by using Absolute
// calculated value
if (Step = 0) and (Abs(ToSize - CurrentHeight) > 0) then
begin
Step := ToSize - CurrentHeight;
Sleep(50); // adjust for smoothness
end;
if Step <> 0 then
begin
Height := Height + Step;
sleep(50); // adjust for smoothness
end;
end;
end;
procedure TForm1.btnCollapseClick(Sender: TObject);
begin
SmoothResizeFormTo(100);
end;
procedure TForm1.btnExpandClick(Sender: TObject);
begin
SmoothResizeFormTo(800);
end;
My teacher said that initializing a function is important. I know why you would initialize a variable, but don't understand why you'd do that with a function.
function f(n: integer):integer;
begin
f := 0; //what my teacher wants me to do
Result := n + 1;
end;
In Delphi function Result is undefined unless you set specific value to it. So you always have to initialize/set function Result at some point in your function.
In your specific example initializing is not important because there is only single execution path that sets value with f := n + 1;
Also Delphi compiler can recognize that value assigned in first line is never used and show you warning message (depending on version and warning settings): H2077: Value assigned to ‘Result’ never used
function f(n: integer):integer;
begin
Result := 0; // not important because it will be set with next line
Result := n + 1;
end;
In more complex functions you can have more execution paths and you have to make sure that each single one sets the function result. Sometimes it is simpler and safer to initialize function result up front to some default value.
function f(n: integer):integer;
begin
Result := 0; // this is important because if n <= 0 Result will be undefined
if n > 0 then Result := n + 1;
end;
Of course, you can write above as
function f(n: integer):integer;
begin
if n > 0 then Result := n + 1
else Result := 0;
end;
Upfront initialization is not necessary. However, it is necessary that function result is set for each possible execution path in your function.
Also, using function name to set function value is obsolete technique. Using Result is preferable.
One important note. Different languages have different rules about returning/seting function results. There is no “one rules them all”. Keep in mind that this is very language specific question.
trying to mimic the verilog behavior regarding the bitwise operations (meaning - an operation that works on all bits of a vector and output 1 bit answer.
example:
use ieee.std_logic_1164.all;
use ieee.std_logic_unsigned.all;
...
signal vect : std_logic_vector (length -1 downto 0);
signal ans : std_logic;
signal addin : std_logic;
when vect = all '0' i will want ans to be '1' (nor)
when vect = all '1' i will want ans to be '1' (and)
when vect = even num of '1' i will want ans to be '1' (xor)
, etc.
i made the following functions (only one is shown here):
function vand (vect :std_logic_vector) return std_logic is
variable temp : std_logic;
begin
temp := '1';
for I in (vect'length -1) downto 0 loop
temp := temp and vect(I);
end loop;
return temp;
end;
this function should give the "AND" on all bits.
so, here comes my questions:
a. is there an easier way to make such operations?
b. i'm using Vand like this if Vand(vect & addin) = '1' do something... but when vect is '0H' and addin is 'H' the condition is filled and I have no idea why. can someone think why this kind of operation is problematic? the function behaves itself on other cases, but here i tested it for rapid change immunity and got this unwanted behavir.
edit
i do not know the length of the vector 'vect' or the vector 'vect & addin'.
edit 2
solved the second problem by creating a sub function Vand(vect : std_logic_vector; b: std_logic) that uses the original Vand (and found a bug in my Vnor along the way). still hoping for a better solution than these two functions.
There are functions called or_reduce and and_reduce which do what you want. They also call to_X01 on the inputs, which means that H and Ls will be converted to 1 and 0.
They can be found in std_logic_misc for std_logic_vectors and are proposed for the next rev of VHDL for ieee.numeric_std for signed and unsigned vectors.
VHDL-2008 also allows this syntax on std_logic_vectors:
anded <= and v;
ored <= or v;