Delphi (2006) Loop Help
So what I'm trying to do is that something happened 70% of the time, a few more things happen 10% of the time if it makes sense, but my application doesn't seem to be doing anything. I guess I don't understand the syntax for for loop or something, if anyone can take a look and maybe give me some advice.
per1 := 70;
per2 := 77;
per3 := 84;
per4 := 91;
per5 := 100;
per6 := Random(2) + 1;
randomize;
RandPer:= Random(100);
randomize;
RandPer2 := Random(100);
if RandPer2 <= 70 then begin
If RandPer <= per1 then begin
Functiontest(1);
end Else If RandPer <= per2 then begin
Functiontest(3);
end Else begin If RandPer <= per3 then begin
Functiontest(5);
end Else begin If RandPer <= per4 then begin
Functiontest(6);
end Else begin If RandPer <= per5 then begin
Functiontest(9);
end;
end;
end;
end;
You don't have loop syntax, so this is definitely a possible source of your confusion.
Do not press Randomize
multiple times. It reinitializes a random seed every time you do this and based on the system clock. If your code is faster than a clock, then your multiple calls Randomize
will not actually reset with a random seed to the same value it had before, causing repeated calls to Random
return the same value.
The help system advises you to call Randomize
only once at the beginning of your program. If you are writing a block or component and you are not in charge of the entire program, then don't call Randomize
at all. Instead, document that the consumers of your code should name it themselves.
If you are writing a DLL and do not use runtime packages, call Randomize
the initialization function that your DLL exports; users of your DLL will not have access to your DLL copy of the Delphi Runtime Library.
Also, if you want something to happen 70% of the time, then you should check if your value is strictly less than 70. Possible return values Random
include zero; 70 percent of the results will be between 0 and 69 inclusive. A resolution of 70 will actually cause the event to happen 71 percent of the time.
Finally, your calculations don't make sense to me 10% of the time. You have three events that will happen 7% of the time, and this will happen 9% of the time. You cannot have four events, each of which will run 10% of the time, with only 30% left. Do you mean that the frequency of each event is measured independently of the others? If so, then don't bundle all of your conditional tests together with else
; Use a completely separate operator if
for each one.
source to share
I just modified the CharlesF code to do what you need. Hope Charles F. won't mind.
begin
randomize;
for i := 0 to NumberOfTimesNeed do
begin
R := Random(100);
case R of
0..69 : Functiontest(1); // this will fire 70% of NumberofTimes
70..79 : Funciotntest(2); // 10 percent
80..89 : Funciotntest(3); // 10 percent
90..94 : Funciotntest(4); // 5 percent
// and so on ...
end;
end;
source to share