Random number generation not working like it should in Pascal - random

I am trying to make a battle system where the player has to guess a random number each time and hope he will win. The problem is that the random number is generated only ONCE. Why?
unit game;
interface
uses a,b,reason,crt;
implementation
var health,ehealth: integer;
var a2:String;
var rand3,guess:Integer;
begin
ClrScr;
ehealth:=5;
health:=10;
Repeat
Randomize;
rand3:=Random (1);
writeln('YOUR HP:',health);
writeln('ENEMY HP:',ehealth);
write('Guess the number (1 or 2):');
Readln(guess);
if (rand3+1) = guess then
ehealth:=ehealth-1
else
health:=health-1;
ClrScr;
until (ehealth = 0) or (health = 0);
writeln('GAME OVER!');
readln;
end;

If i remember, the random function in pascal return a number between 0 and (N-1). So if you want a random number 0 or 1 you need to call Random(2). Also move Randomize just after the begin.

Related

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 :-)

How to generate a random combination of digits that are already defined in Pascal?

I would like to ask if anybody can give a hand in solving the following issue: How should I use the random function in Pascal in order to generate a random combination of digits that are already initialized (I mean that I have given values to four variables and I want via the random function to create a random combination of these four digits).
Thanks in advance!
Rossi
var digits : array[0..3] of integer = (10,20,30,40);
i : integer;
begin
Randomize; // initialize the random generator. Only once per program
for i:=0 to 50 do
Writeln(digits[random(4)]);
end.
The Writeln line draws a number 0<=x<4 so 0..3, and looks it up in the digits array, then writes it to console output. It is draws 50 random numbers and then quits.
var
randomnumber,i:integer;
number:array[0..3] of integer;
begin
randomize;
for i:= 0 to 3 do
begin
readln(number[i]);
end;
randomnumber:= (number[random(4)] * 1000) + (number[random(4)] * 100) + (number[random(4)] * 10) + (number[random(4)] * 1);
writeln(randomnumber);
end.
I hope this could help.
But the given initial value should be between 0 to 9.
If you want that the output contains each digit only once, then you would need to stored the digits which have already been chosen in a set to prevent them from being chosen again.
const
digits: array [0..3] of integer = (1, 3, 5, 7);
var
i, n, total: integer;
stored: set of integer;
begin
Randomize;
stored:= [];
total:= 0;
for i:= 1 to 4 do
begin
repeat
n:= random (4);
until not (n in stored);
stored:= stored + [n];
total:= total * 10 + digits[n];
end;
writeln (total)
end.

Array Tally Chart

I'm trying to create a Tally Chart based on values stored in array.
I know it is possible to do this in Python, but is there a way to do this in Pascal by keeping the amount of coding to a minimum?
var numbers:array [0..9] of integer;
Sum,aNumber, count,count2:integer;
Average:real=0;
begin
randomize;
// Put 10 Random numbers into an array
for count:= 0 to 9 do
begin
aNumber:=Random(10)+1;
numbers[count]:=aNumber
end;
// Show a Tally
begin
for count:= 0 to 9 do
writeln(numbers[count] * '£');
writeln;
end;
readln;
end.
I simply want to present the outcome of the array by showing all possible values. E.g. If my array had the following random values between 1 and 10: 3,3,8,8,9 it should show:
1-
2-
3- II
4-
..
8- II
9- I
10-
Thanks.
The obvious way would be another for loop:
for count := 0 to 9 do
begin
for i := 1 to numbers[count] do
write('£');
writeln;
end
If you can settle for just one character at the right position, you could use something like:
for count := 0 to 9 do
writeln('£' : numbers[count]);
Think it works now... i created a Function to return the number of instances in each element. That result helps me to know the no. of iterations for each number.
Function TallyCount(x:integer):integer;
var i,TotalCount:integer;
begin
i:=0;
TotalCount:=0;
for i := 0 to 9 do
begin
if numbers[i] = x then
TotalCount:=TotalCount +1;
end;
result:=Totalcount;
end;

How many times does one number divide into another, and how much is left over?

I need an algorithm in Delphi to generate partitions for a specified integer value.
Example: for 13 if 5 is specified as the max value for partition it will give 5,5,3; if 4 is specified as max partition value the result should be 4,4,4,1, and so on.
It's simple enough to solve the problem using div and mod. Here's an example program that I don't think needs any further explanation:
program IntegerPartitions;
{$APPTYPE CONSOLE}
function Partitions(const Total, Part: Integer): TArray<Integer>;
var
Count: Integer;
Rem: Integer;
i: Integer;
begin
Assert(Total>0);
Assert(Part>0);
Count := Total div Part;
Rem := Total mod Part;
if Rem=0 then
SetLength(Result, Count)
else
SetLength(Result, Count+1);
for i := 0 to Count-1 do
Result[i] := Part;
if Rem<>0 then
Result[Count] := Rem;
end;
var
Value: Integer;
begin
for Value in Partitions(13, 5) do
Writeln(Value);
Readln;
end.

How can I measure the difference of speed of code between loop and recursive method?

Let's say we have to create a calculator, and the first function it has is Fatorial.
We can write it as a recursive function or use a loop to get the result.
We all know that recursion is more slow because of it's exponential nature.
But how to prove it by code and not by counting lines?
I have tried to calculate the amount of milliseconds spent, but with my i7 it is always zero between the initial time and when the code stops.
How can I measure the difference of speed of code between loop and recursive method?
type
TJanela = class(TForm)
Instrucao: TLabel;
Entrada: TEdit;
Botao: TButton;
procedure Calcular(Sender: TObject);
end;
var
Janela: TJanela;
Val, Fat, Start, TimeRecursive, TimeLoop: Int64;
function FR(N: Int64): Int64; // Fatorial Recursivo
function FL(N: Int64): Int64; // Fatorial em Loop
implementation
{$R *.dfm}
procedure TJanela.Calcular(Sender: TObject);
begin
Val := StrToInt(Entrada.Text);
Start := StrToInt(FormatDateTime('nnsszzz',Now));
Fat := FR(Valor);
TimeRecursive := StrToInt(FormatDateTime('nnsszzz',Now)) - Start;
Start := StrToInt(FormatDateTime('nnsszzz',Now));
Fat := FL(Valor);
TimeLoop := StrToInt(FormatDateTime('nnsszzz',Now)) - Start;
if Val > 25 then
ShowMessage('Delphi can't calculate above [ 25! ]')
else
ShowMessage(' [ ' +
IntToStr(Val) + '! ] is equal to [ ' +
FormatFloat('###,###,###,###,###,###',Fat) + ' ]'#13#13+
'Recursive: [ ' + IntToStr(TimeRecursive) + ' ] ms;'#13+
'Loop: [ ' + IntToStr(TimeLoop) + ' ] ms;');
end;
function FR(N: Int64): Int64;
begin
if N <= 1 then
Result := 1
else
Result := N * FR(N - 1);
end;
function FL(N: Int64): Int64;
var
I: Integer;
begin
for I := 2 to N - 1 do
N := N * I;
if N = 0 then
Result := 1
else
Result := N;
end;
Now that David came with the answer, I asked a question on Mathematics so they can help me to come out with two equations to determine the proximate time a given factorial will spend on the computer in both methods.
You are using quite a low resolution timer and a single evaluation of the factorial function is too fast to even register.
You could use a higher resolution timer, but by far the easiest approach is to time something that takes longer. Instead of timing a single call to factorial, time a thousand, or a million.
If you are actually interested in implementing a fast factorial function, for integer inputs, then you should use a lookup table.
For what it is worth, I think that TStopWatch in the Diagnostics unit is more convenient for timing than the date/time functions.
Use a profiler. Recent versions of Delphi include limited functionality versions of AQTime, but a search for profiler Delphi here turns up Profiler and Memory Analysis Tools for Delphi here at StackOverflow.
Profilers allow you to evaluate your code in several different ways, including the precise amount of time spent executing various parts of it. You can use the results to determine which takes more (or less) time.
if its just for testing, could you put a TimeGetTime() instead of GetTime() before the loop and one after. then just save the value in a list box to see how long it takes.
if that is too slow try QueryPerformanceCounter/QueryPerformanceFrequency

Resources