It can be regarding any programming language.
For example in PHP:
if($x > 2) { $x=2; }
Is there any way to not use a condition, but use some mathematical expression to reach the same result?
I found the answer
$maxval = 2;
$x = $maxval - (abs($maxval - $x) + $maxval - $x) / 2;
so if $x > $maxval, this expression (abs($maxval - $x) + $maxval - $x) / 2; becomes 0 and $x becomes equal to $maxval
else this expression is equal to $maxval - $x, and the whole equation becomes
$x = $x
but the shortest solution is
$x = min($x, 2);
Related
Mostly I have heard that if you can make a recursion code , you can convert it to a Dynamic programming code, but what is the need to do the same ? And how to convert a recursion code to DP ?
In dynamic programming there are 2 approaches, top-down and bottom-up.
lets take Fibonacci sequence as an example:
f(0) = 0 : x = 1,
f(1) = 1 : x = 1,
f(x) = f(x-1) + f(x-2) : x > 1
The top-down approach:
It uses recursion + memoization(storing the calculated states to avoid the recalculation):
int memo[1000];//initialized by zeroes
int f(int x) {
if (x == 0 || x == 1) return 1;
if (memo[x] != 0) return memo[x]; //trying to avoid recalculation
memo[x] = f(x - 1) + f(x - 2); //storing the result
return memo[x];
}
As you notice here to calculate the value f(x) we have to break it down into
f(x-1) and f(x-2), this why it is called top-down.
The bottom-up approach:
It uses loops(for,while...) rather than recursion and stores the values inside an array:
int memo[1000];
int bottom_up(int x) {
memo[0] = 1;
memo[1] = 1;
for (int i = 2; i < 1000; i++)
memo[i] = memo[i - 1] + memo[i - 2];
}
As you notice we calculate the values of Fibonacci sequence starting from the smaller values up to the bigger ones and this is why it is called bottom-up.
Converting the code from recursion to loops is considered converting the recursive code to an iterative code.
The recursive code will call itself multiple times and you should know that each function call will be stored inside the stack of your memory, so it is preferred to use the iterative approach as it will be better for memory and performance.
This function is a school practice problem (it is running but does not work properly).
My task is to call for a integer from the user.
When the number arrives, my task is to write out (with a recursive algorithm)
what is the sum of the number with the numbers before the given number.
For example if our number is 10 then the upshot is 55 because 1+2+3+4+5+6+7+8+9+10 = 55, etc.
I've already tried to write this code:
function egesszamosszeg(n:integer) : integer;
begin
egesszamosszeg:=0
if n=1 then
egesszamosszeg:=1
else
for n:=1 to egesszamosszeg do
begin
egesszamosszeg:=egesszamosszeg+1;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var egesszam:integer;
begin
egesszam:=strtoint(Inputbox('','Give an integer please!',''));
Showmessage(inttostr(Egesszamosszeg(egesszam)));
end;
My problem is that I do not know what is the main problem with this code.
I do not know what is the main problem with this code.
There are several problems with your code: it's iterative, not recursive; it's way too complicated; this loop:
for n:=1 to egesszamosszeg do
is effectively:
for n:=1 to 0 do
Consider this simple function which effectively implements the gist of your problem:
function egesszamosszeg(n:integer) : integer;
begin
egesszamosszeg := n;
if (n > 1) then
egesszamosszeg := egesszamosszeg + egesszamosszeg(n - 1);
end;
begin
writeln(egesszamosszeg(10));
end.
You are simply trying to increment egesszamosszeg (couldn't you use an easier name?), instead of adding the consecutive numbers to it. But your loop is wrong: eggesszamosszeg is 0, so you are in fact doing for n := 1 to 0 do. That loop will never run. Don't re-use n, use another variable for the loop index:
for i := 1 to n do
egesszamosszeg := egesszamosszeg + i;
But you say it must be recursive, so it must call itself with a different parameter value. Then do something like:
function egesszamosszeg(n: integer): integer;
begin
if n = 1 then // terminating condition
egesszamosszeg := 1
else
egesszamosszeg := n + egesszamosszeg(n - 1); // recursion
end;
In most Pascals, you can use the pseudo-variable Result instead of the function name. Often, that makes typing a little easier.
FWIW, did you know that you could make this a little simpler and do not need recursion or iteration at all? The result can be calculated directly:
function egesszamosszeg(n: Integer): Integer;
begin
result := n * (n + 1) div 2;
end;
For 1..10, that will give 10 * 11 div 2 = 55 too.
See: https://www.wikihow.com/Sum-the-Integers-from-1-to-N
In effect, you count (1+10) + (2+9) + (3+8) + (4+7) + (5+6) = 5 * 11 = 55. You can do the same for any positive number. Same with 1..6: (1+6) + (2+5) + (3+4) = 3 * 7 = 21.
That leads to the formula:
sum = n * (n + 1) div 2
(or actually:
n div 2 * (n+1) // mathematically: n/2 * (n+1)
which is the same).
I was wondering if you can have more than just one base case on a recursive procedure/function in Pascal.
If so, can you please give me a simple example? And please explain why this is possible?
The simple Fibonacci sequence has two base cases:
f(0) = 0
f(1) = 1
f(n) = f(n - 1) + f(n - 2)
And, of course, you can write it in Pascal:
function Fib(n: integer): integer;
begin
if n = 0 then Fib := 0
else if n = 1 then Fib := 1
else Fib := Fib(n - 1) + Fib(n - 2)
end;
I have read a lot of XQuery position, but all examples are about >, <, or =. But you can also use x - y and I am confused as to what is inclusive and what is not.
[position() = $startPosition to $endPosition]
Let's say $startPosition is 1 (as I have read that position does not start with 0 but with 1), what will return the first hit? $endPosition set to 1 as well, or to 2?
In other words, given an expected return of n, what would be the formula for both variables? To make things more clear, we can add an incrementing loop ($iteration). Basically we are generating a search that will find all subsequent hits with position. (As an example.)
$endPosition = 1 + ($iteration * n);
$startPosition = $endPosition - n;
This is what I came up with. This will result in the following outcome, for $iteration starting from 1 and incrementing, and n of 3.
1:
$endPosition = 1 + (1 * 3); // 4
$startPosition = 4 - 3; // 1
2:
$endPosition = 1 + (2 * 3); // 7
$startPosition = 7 - 3; // 4
3:
$endPosition = 1 + (3 * 3); // 10
$startPosition = 10 - 3; // 7
But, is this correct? I am not sure. Is the $endPosition included? If not, my code is correct, if not - it isn't, and then I am interested in the correct formula.
The expression $sequence[position() = $a to $b] is equivalent to the following FLWOR expression (where $position start at 1):
for $x at $position in $seq
where $position >= $a and $position <= $b
return $x
So to skip the first two items and then return the following five, you need $seq[position() = 3 to 7].
Here is how you can go from this to a subsequence function that uses a 0-based offset and the number of items to return:
declare function local:subsequence(
$seq as item()*,
$offset as xs:integer,
$length as xs:integer
) as item()* {
let $start := $offset + 1,
$end := $offset + $length
return $seq[position() = $start to $end]
};
local:subsequence(1 to 100, 0, 5), (: returns (1, 2, 3, 4, 5) :)
local:subsequence(1 to 100, 13, 3) (: returns (14, 15, 16) :)
It's unclear the specific problem you're trying to solve, so I don't know if this answers your question, but let's unpack that expression first:
[position() = $startPosition to $endPosition]
Say $startPosition is 1 and $endPosition is 3. That will evaluate to:
[position() = (1, 2, 3)]
That predicate will return true any time position() equals any of the values in the sequence on the right.
In the last few days I try to solve this problem. I even have the solution but I can't figure it out. Can someone help me?
Here the problem:
You are given two rectangles on a plane.
The centers of both rectangles are located in the origin of coordinates
(meaning the center of the rectangle's symmetry).
The first rectangle's sides are parallel to the coordinate axes:
the length of the side that is parallel to the Ox axis, equals w,
the length of the side that is parallel to the Oy axis, equals h.
The second rectangle can be obtained by rotating the first rectangle
relative to the origin of coordinates by angle α.
Example:
http://i.imgur.com/qi1WQVq.png
Your task is to find the area of the region which belongs to both
given rectangles. This region is shaded in the picture.
Input
The first line contains three integers w, h, α (1 ≤ w, h ≤ 106; 0 ≤ α ≤ 180). Angle α is given in degrees.
Output
In a single line print a real number — the area of the region which belongs to both given rectangles.
The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 6.
Sample test(s)
input
1 1 45
output
0.828427125
input
6 4 30
output
19.668384925
Here a possible implementation:
<?php
list($w, $h, $alphaInt) = explode(' ', '34989 23482 180');
if ($alphaInt == 0 || $alphaInt == 180) {
$res = $h * $w;
}
else if ($alphaInt == 90) {
$res = $h * $h;
}
else {
if ($alphaInt > 90) $alphaInt = 180 - $alphaInt;
$alpha = $alphaInt / 180.0 * M_PI;
//echo '$alpha:' . $alpha . "\n";
$cos = cos($alpha);
$sin = sin($alpha);
//echo '$cos: ' . $cos . "\n";
//echo '$sin: ' . $sin . "\n";
$c = $w / 2 * $cos + $h / 2 * $sin - $w / 2;
//echo '$c: ' . $c . "\n";
$r1 = $c / $cos;
$r2 = $c / $sin;
//echo '$r1: ' . $r1 . "\n";
//echo '$r2: ' . $r2 . "\n";
$c = $w / 2 * $sin + $h / 2 * $cos - $h / 2;
//echo '$c: ' . $c . "\n";
$r3 = $c / $cos;
$r4 = $c / $sin;
//echo '$r3: ' . $r3 . "\n";
//echo '$r4: ' . $r4 . "\n";
if ($r1 < 0 || $r2 < 0 || $r3 < 0 || $r4 < 0) {
$res = $h * $h / $sin; //$res = $w * $w / $cos;
}
else {
$res = $h * $w - $r1 * $r2 - $r3 * $r4;
}
}
echo '$res: ' . $res . "\n";
Small alpha
When w*sin(alpha) < h*(1+cos(alpha)) (i.e., before the vertices of the new rectangle meet the vertices of the old one for the first time), the area of the intersection is the area of the original rectangle (w * h) minus 4 triangles (2 pairs of identical ones). Let the bigger triangle have hypotenuse a and the smaller hypotenuse b, then the area is
A = w * h - a*a*cos(alpha)*sin(alpha) - b*b*cos(alpha)*sin(alpha)
The sides of the original rectangle satisfy a system of equations:
a + a * cos(alpha) + b * sin(alpha) = w
a * sin(alpha) + b + b * cos(alpha) = h
Using the half-angle formulas,
a * cos(alpha/2) + b * sin(alpha/2) = w/(2*cos(alpha/2))
a * sin(alpha/2) + b * cos(alpha/2) = h/(2*cos(alpha/2))
thus (the matrix on the LHS is a rotation!)
a^2 + b^2 = (w^2 + h^2) / (2*cos(alpha/2))^2
and
A = h * w - (w^2 + h^2) * cos(alpha)* sin(alpha) / (2*cos(alpha/2))^2
(this can be simplified further a little bit)
Bigger alpha
When alpha is bigger (but still alpha<pi/2), the intersection is a parallelogram (actually, a rhombus) whose 2 altitudes are h and 4 sides h/sin(alpha) and the area is, thus, h*h/sin(alpha) (yes, it does not depend on w!)
Other alpha
Use symmetry to reduce alpha to [0;pi/2] and use one of the two cases above.
You might try describing both rectangles as solutions to a system of four linear insqualities.
The set of points in their intersection is the set of solutions to both sets of linear inequalities.
You want the area of that set of solutions. You can find all points at which at least two of your eight inequalities are tight. Filter out those that don't satisfy all of the inequalities. Then take their convex hull using Graham's scan and compute the area using the surveyor's formula.
This method works to find the intersection of any two convex polygons. Slightly modified, it generalises (in the form of Fourier-Motzkin elimination and the double description method for computing the intersection and determinants for volume calculation) to convex polyhedra in any dimension.