String-numeric variable name in Pascal - pascal

I want to create a loop from i := 1 to n which takes a random number from the procedure and assigns its value to the variables named x1,x2,x3,x4...xn
So it could look like this:
for i:=1 to 100 do begin
GenerateRandomNumber(x); // this procedure gives the updated value of x
xi := x;
end
I want to solve it by creating an array[1..n] of string and then assign this random number to the ith element of the array. But to be honest, I don't like this solution. Is there any faster way? I was thinking about concatenating a string with a number, or converting "x" (the string) to a number and then somehow merging it with the consecutive values of i. What do you think?

Related

Golang BigInt division

I have a problem with function and i don't understand why it happen. The problem is: i have a big number, but when i'm trying to make some operations of division - I have zeros.
The code is:
for {
fmt.Println("number is", number)
// key := number % 10
key := number.Mod(number, big.NewInt(10))
fmt.Println("key", key)
// number = number / 10
first := new(big.Int).Div(number, big.NewInt(10))
fmt.Println("first ", first)
number = first
fmt.Println(number) //number = 0 always as a fisrt variable too
... }
The example of exit is:
number is 6689502913449127057588118054090372586752746333138029810295671352301633557244962989366874165271984981308157637893214090552534408589408121859898481114389650005964960521256960000000000000000000000000000
key 0
first 0
0
Number is getting on correnctly, Mod operation is seems correctly too. Div operation is not. What the point is? How can i calculate basic divisions of big numbers?
The problem is this line:
key := number.Mod(number, big.NewInt(10))
You call number.Mod() which is Int.Mod() which modifies the receiver which is number, it sets it to the modulus which is 0, so after this number will be zeroed.
You have to use a new big.Int, just as you used for the Div() operation:
key := new(big.Int).Mod(number, big.NewInt(10))
Try it on the Go Playground.
Also note that there is Int.DivMod() which performs both these 2 operations (Div() and Mod()).
Also note that to speed up your loop, you should create and reuse *big.Int values, and not create and throw them away in each iteration. The most trivial is to create and reuse 10:
var ten = big.NewInt(10)
Also create and reuse values for the mod and div results.

Why is a 3rd variable necessary in this arithmetic progression sum’s code?

Why do I need a local variable result in this code? I guess I'm having an infinite loop when I try to use only 2 variables, but I don't get how to recognize this issue in the code and use debug to understand the issue.
# Write a method that takes in an integer num and returns the sum of
# all integers between zero and num, up to and including num.
def sum_nums(num)
result = 0
i = 0
while i <= num
result += i
i += 1
end
return result
end
So, in order for this code to work, you need to know three things: the number you are counting up to (num), the current value of the number (i), and the current sum from 0 to i. result is the variable keeping track of the sum from 0 to i.
However, this isn't a very ruby way of writing this method. while loops are meant to be used in situations where you don't know how many times you need to loop. In this case, you know the number of loops, so an iterator is better for this purpose.
def sum_nums(num)
(0..num).reduce(:+)
end
The above method will return the same result as your method.
In your function you use three variables:
num which holds the range over which you want to do the summing (or the number of times you need to loop)
i which holds the specific integer you are adding to the sum within each loop
result which holds the sum so far (and at the end of the final loop, holds the answer you want). Without this variable, the next loop would 'lose track' of how much all the previous loops had already added to the sum of integers.
You could get rid of the i variable as follows
result = 0
while num > 0
result += 1
num -= 1
end
return result
This relies on the fact that if you count down from num you know to stop at 0. Alternately you could get rid of both the i variable and the result variable as follows
return num*(num+1)/2
This relies on an algebraic formula for the sum of integers rather than explicitly carrying out the sum. Both of these snippets will produce the same return as your function.
In summary, you need the num variable, otherwise your function won't 'know' what range to do the sum over. You can get away without the i variable (but the meaning of the code may not be so obvious), but you can only get away without the result variable if you can find a method that doesn't need the loop.

How to insert the probability of randomizing a specific number in pascal

I've been trying lately to write a program(a text based game) but I only know some commands and don't understand every command very well.
What I am trying to do is a hit chance. Lets say that I want the program to have
90% chance of choosing number 1 (which means hit) and
10% to choose number 0 (which means miss).
I saw the same question Here but I don't understand the commands because I've never used them (I'm talking about set.seed and sample). Could someone explain to me how do they work? Is there another way (easier to understand? I don't mind if it consumes more resource)
program Project1;
{$ASSERTIONS ON}
function getProb(aProbability: Integer): boolean;
begin
result := aProbability > (100 - random(100));
end;
procedure miss;
begin
writeln('miss');
end;
procedure hit;
begin
writeln('hit');
end;
var
i, success, probability, errorMarge: Integer;
const
combat: array[boolean] of procedure = (#miss, #hit);
begin
// show that getProb() is reliable
errorMarge := 4;
success := 0;
probability := 80;
for i in [0..99] do
Inc(success, Byte(getProb(probability)));
assert(success >= probability - errorMarge);
success := 0;
probability := 50;
for i in [0..99] do
Inc(success, Byte(getProb(probability)));
assert(success >= probability - errorMarge);
// example usage
combat[getProb(20)];
combat[getProb(80)];
combat[getProb(90)];
readln;
end.
Not knowing what "commands" you know, this is hard to answer w/o generalizing.
If you only need to choose between two values, then generate a random value in whatever range you know how to, and compute the dividing line based on your probability. So, for your example, if you can generate a value between 0 and 1, if it is <= 0.9, hit.
This can be extended to multiple values by adding the successive probabilities. So if you have 4 values to choose between, each with 25% probability, get you random value between 0 and 1: if it is less than 0.25, choose 0 else if less than 0.5, choose 1 else if less than 0.75 choose 2 otherwise choose 3.

Maximum Value of subarray

Is there any function that returns the maximum number from a subarray of a longint array?
For example:
I have the array: [2,3,6,2,9,4,2,4]
I want the maximum value of the first 5 elements [2,3,6,2,9] of the array (9)
Which is the best solution?
You don't need to create another array.
The 1st solution that would come up is to loop inside your array, taking the first value as 'tempMaxValue', and then fetching your array comparing each value to the 'tempMaxValue'.
If the value is greater than 'tempMaxValue', update 'tempMaxValue' with that particular value and then jump to the next value in the array, otherwise just jump to the next value.
With this solution, you can manage the number of items you want to search into (here you wanted the greatest number within the 5 first elements, so your loop will go from 0 to 4)
Edit : (as #TLama said)
More concretly this is the easy solution: write a function which takes an array, the lowest and the highest indexes as parameter.
program Project1;
uses sysutils;
type TIntegerArray = array of Integer;
function maxInRange(const anArr: TIntegerArray; boundLow, boundHi: Integer): Integer;
var
i: Integer;
begin
result := anArr[boundLow];
for i := boundLow + 1 to boundHi do
if anArr[i] > result then
result := anArr[i];
end;
const
arr: array[0..7] of Integer = (2,3,6,2,9,4,2,4);
begin
writeln(intToStr(maxInRange(arr,0,4)));
readln;
end.

How to get a random number in pascal?

I want to get a random number in pascal from between a range. Basically something like this:
r = random(100,200);
The above code would then have a random number between 100 and 200.
Any ideas?
The built in pascal function only lets you get a number from between 0-your range, while i need to specify the minimum number to return
Just get a random number with the correct range (ie 100 to 200 would be range 100) then add the starting value to it
So: random(100) + 100 for your example
As already pointed out, you should use
myrandomnumber := random(span) + basenumber;
However, to get better quality random numbers, you should call
randomize();
once, on start of your application, to initialize the random number generator.
Couldn't you just declare a starting variable and an end variable and pass random those? e.g.
var
varMyRandomNumber, x, y := extended;
begin
x := 100;
y := 200;
varMyRandomNumber := random(x,y);
ShowMessage(IntToStr(varMyRandomNumber));
end;
?
There's a good example here of using a for loop to set starting and end values : http://www.freepascal.org/docs-html/rtl/system/random.html
Use RandomRange or RandomFrom:
function RandomRange(const aFrom: Integer; const aTo: Integer): Integer;
RandomFrom returns a random element from the array AValues. The return value has the same type as the type of the array elements.
first of all, i recommend you to use Randomize at the beginning of the program (it changes the algorithm of selecting the number).
To get a random number between some two numbers you need this:
Result:=Min+random(10000)mod max + 1;
I don't remember the maximum value for random, so you can change it (it don't changes anything).
By using 'mod' you get module from division Random and max. +1 is needed, because you never get the number that = max, only the number that =max-1, so you need to write +1.
Good luck!
You can make it like
Int:=Random(100);
it give's 100 random numbers.
then when you display it or use it just add 101 to that integer so its between 100 and 200

Resources