Given the following recursive method:
/∗∗ Returns the product of integer elements in given array. ∗/
public static int product(int[] arr, int low, int high) {
if (high < low)
return 1;
if (low == high)
return arr[low];
return arr[low] * product(arr, low+1, high-1) * arr[high];
}
I determined the recurrence equation: T(n) = T(n - 2) + c
and the corresponding base case equation: T(0) = 1
To work out the closed form solution I do the following:
T(n) = T(n - 2) + c
T(n - 2) = T(n - 4) + c
//Substitute T(n - 2)
T(n) = T(n - 4) + 2.c
T(n) = T(n - 2k) + k.c
//Select k = 1/2.n and substitute
T(n) = T(0) + (1/2n).c
T(n) = 1 + (1/2n).c
1) Is my recurrence equation and base case correct and why?
2) Is my closed form solution correct and why?
Related
Given the problem of distinct integers, generate all subsets.
https://www.interviewbit.com/problems/subset/
I have found two solutions.
first solution::
void helper_subsets(vector<vector<int>> &res , vector<int> &A ,
vector<int> &subset ,int current)
{
if(current == A.size())
res.push_back(subset) ;
else
{
helper_subsets(res,A,subset,current+1) ;
subset.push_back(A[current]) ;
helper_subsets(res,A,subset,current+1) ;
subset.pop_back() ;
}
}
vector<vector<int> >subsets(vector<int> &A) {
vector<vector<int>> res ;
sort(A.begin(),A.end()) ;
vector<int> subset ;
helper_subsets(res , A , subset , 0 ) ;
sort(res.begin(),res.end()) ;
return res ;
}
Second solution ::
void helper_subsets(vector<vector<int>> &res , vector<int> &A ,
vector<int> &subset ,int current)
{
res.push_back(subset) ;
for(int i = current ; i < A.size() ; i++)
{
subset.push_back(A[i]) ;
helper_subsets(res,A,subset,i+1) ;
subset.pop_back() ;
}
}
vector<vector<int> > subsets(vector<int> &A) {
vector<vector<int>> res ;
sort(A.begin(),A.end()) ;
vector<int> subset ;
helper_subsets(res , A , subset , 0 ) ;
sort(res.begin(),res.end()) ;
return res ;
}
The problem is that I am able to calculate the time complexity of the first solution mathematically as well using recursion tree.
t(n) = 2t(n-1) + c (i.e 2 recursive calls with size n-1 and some constant time for each n)
t(n) = O(2^n) by solving the above recurrence relation.
But with the second solution, I am not able to define recurrence relation to finally use back substitution to get the time complexity and could not get it by recurrence tree method.Please help me find time complexity of second solution.
The analogous recurrence relation for problem 2 is:
n - 1
T(n) = Σ T(n - i) + c
i = 1
– which follows from the for-loop from current to A.size(). To solve this, expand the first term:
T(n) = T(n - 1) + T(n - 2) + T(n - 3) + ... + T(1) + c
--------
|
= | T(n - 2) + T(n - 3) + ... + T(1) + c +
---> T(n - 2) + T(n - 3) + ... + T(1) + c
= 2 * [T(n - 2) + T(n - 3) + ... + T(1) + c]
= 2 * T(n - 1)
i.e., a very similar recurrence relation differing only by a constant. It still evaluates to O(2^n), taking the base case to be T(1) = O(1).
I created this piece of code to get the intersection of two 3d line-segments.
Unfortunately the result of this code is inaccurate, the intersection-point is not always on both lines.
I am confused and unsure what I'm doing wrong.
Here is my code:
--dir = direction
--p1,p2 = represents the line
function GetIntersection(dirStart, dirEnd, p1, p2)
local s1_x, s1_y, s2_x, s2_y = dirEnd.x - dirStart.x, dirEnd.z - dirStart.z, p2.x - p1.x, p2.z - p1.z
local div = (-s2_x * s1_y) + (s1_x * s2_y)
if div == 0 then return nil end
local s = (-s1_y * (dirStart.x - p1.x) + s1_x * (dirStart.z - p1.z)) / div
local t = ( s2_x * (dirStart.z - p1.z) - s2_y * (dirStart.x - p1.x)) / div
if (s >= 0 and s <= 1 and t >= 0 and t <= 1) and (Vector(dirStart.x + (t * s1_x), 0, dirStart.z + (t * s1_y)) or nil) then
local v = Vector(dirStart.x + (t * s1_x),0,dirStart.z + (t * s1_y))
return v
end
end
This is example of Delphi code to find a distance between two skew lines in 3D. For your purposes it is necessary to check that result if small enough value (intersection does exist), check that s and t parameters are in range 0..1, then
calculate point using parameter s
Math of this approach is described in 'the shortest line...' section of Paul Bourke page
VecDiff if vector difference function, Dot id scalar product function
function LineLineDistance(const L0, L1: TLine3D; var s, t: Double): Double;
var
u: TPoint3D;
a, b, c, d, e, det, invdet:Double;
begin
u := VecDiff(L1.Base, L0.Base);
a := Dot(L0.Direction, L0.Direction);
b := Dot(L0.Direction, L1.Direction);
c := Dot(L1.Direction, L1.Direction);
d := Dot(L0.Direction, u);
e := Dot(L1.Direction, u);
det := a * c - b * b;
if det < eps then
Result := -1
else begin
invdet := 1 / det;
s := invdet * (b * e - c * d);
t := invdet * (a * e - b * d);
Result := Distance(PointAtParam(L0, s), PointAtParam(L1, t));
end;
end;
As far as I can tell your code is good. I've implemented this in javascript at https://jsfiddle.net/SalixAlba/kkrc9kcf/
and it seems to work for all the cases I can think of.
The only changes I've done is to change things to work in javascript rather than lua. The final condition was commented out
function GetIntersection(dirStart, dirEnd, p1, p2) {
var s1_x = dirEnd.x - dirStart.x;
var s1_y = dirEnd.z - dirStart.z;
var s2_x = p2.x - p1.x;
var s2_y = p2.z - p1.z;
var div = (-s2_x * s1_y) + (s1_x * s2_y);
if (div == 0)
return new Vector(0,0);
var s = (-s1_y * (dirStart.x - p1.x) + s1_x * (dirStart.z - p1.z)) / div;
var t = ( s2_x * (dirStart.z - p1.z) - s2_y * (dirStart.x - p1.x)) / div;
if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {
//and (Vector(dirStart.x + (t * s1_x), 0, dirStart.z + (t * s1_y)) or nil) then
var v = new Vector(
dirStart.x + (t * s1_x),
dirStart.z + (t * s1_y));
return v;
}
return new Vector(0,0);
}
Mathmatically it makes sense. If A,B and C,D are your two lines. Let s1 = B-A, s2 = C-D. A point of the line AB is given by A + t s1 and a point on the line CD is given by C + s s2. For an intersection we require
A + t s1 = C + s s2
or
(A-C) + t s1 = s s2
You two formula for s, t are found by taking the 2D cross product with each of the vectors s1 and s2
(A-C)^s1 + t s1^s1 = s s2^s1
(A-C)^s2 + t s1^s2 = s s2^s2
recalling s1^s1=s2^s2=0 and s2^s1= - s1^s2 we get
(A-C)^s1 = s s2^s1
(A-C)^s2 + t s1^s2 = 0
which can be solved to get s and t. This matches your equations.
Drawn a line from a point A to point B. Let d be offset. Let C be point to be tested.
I am going to do a kind of hit testing around the line with offset.
How can i do the hit testing around the line with the given offset.
Ex: A = (10,10), B (30,30), offset = 2. choose C as any point. Please Refer the image in the link please.
http://s10.postimg.org/6by2dzvax/reference.png
Please help me.
Thanks in advance.
Find offset for C.
e.g. dx1 and dy1. If dy1/dx1=dy/dx then your C hits the line.
For segment you should also check if whether dx1 < dx or dy1 < dy.
In other words, you want to check if that point C is inside a certain rectangle, with dimensions 2*d and |A-B|+2*d. You need to represent the line as u*x+v*y+w=0, this can be accomplished by
u = A.y-B.y
v = B.x-A.x
w = A.x*B.y - A.y * B.x
Then the (signed) distance of C from that line would be
d = (u*C.x + v*C.y +w) / sqrt( u*u+v*v)
You compare abs(d) to your offset.
The next step would be to check the position of C in the direction of the line. To that end you consider the orthogonal line u2*x+v2*y+w2=0 with
u2 = v
v2 = -u
w2 = -u2*(A.x+B.x)/2 - v2*(A.y+B.y)/2
and the distance
d2 = (u2 * C.x + v2 * C.y + w2 ) / sqrt( u2*u2+v2*v2 )
This distance must be compared to something like the length of the line+offset:
abs(d2) < |A-B| / 2 + offset
A convenient trick is to rotate and translate the plane in such a way that the segment AB maps to the segment (0, 0)-(0, L) (just like on the image), L being the segment length.
If you apply the same transform to C, then it a very simple matter to test inclusion in the rectangle.
That useful transform is given by:
x = ((X - XA).(XB - XA) + (Y - YA).(YB - YA)) / L
y = ((X - XA).(YB - YA) - (Y - YA).(XB - XA)) / L
maybe you can use this function to count the shortest distance of the point to the line. If the distance is <= offset, then that point is hitting the line.
private double pointDistanceToLine(PointF line1, PointF line2, PointF pt)
{
var isValid = false;
PointF r = new PointF();
if (line1.Y == line2.Y && line1.X == line2.X)
line1.Y -= 0.00001f;
double U = ((pt.Y - line1.Y ) * (line2.Y - line1.Y )) + ((pt.X - line1.X) * (line2.X - line1.X));
double Udenom = Math.Pow(line2.Y - line1.Y , 2) + Math.Pow(line2.X - line1.X, 2);
U /= Udenom;
r.Y = (float)(line1.Y + (U * (line2.Y - line1.Y ))); r.X = (float)(line1.X + (U * (line2.X - line1.X)));
double minX, maxX, minY , maxY ;
minX = Math.Min(line1.Y , line2.Y );
maxX = Math.Max(line1.Y , line2.Y );
minY = Math.Min(line1.X, line2.X);
maxY = Math.Max(line1.X, line2.X);
isValid = (r.Y >= minX && r.Y <= maxX) && (r.X >= minY && r.X <= maxY );
//return isValid ? r : null;
if (isValid)
{
double result = Math.Pow((pt.X - r.X), 2) + Math.Pow((pt.Y - r.Y), 2);
result = Math.Sqrt(result);
return result;
}
else {
double result1 = Math.Pow((pt.X - line1.X), 2) + Math.Pow((pt.Y - line1.Y), 2);
result1 = Math.Sqrt(result1);
double result2 = Math.Pow((pt.X - line2.X), 2) + Math.Pow((pt.Y - line2.Y), 2);
result2 = Math.Sqrt(result2);
return Math.Min(result1, result2);
}
}
I have almost everything working except for solving for X in line 25 i keep getting an error saying " term does not evaluate to a function taking 1787 arguments" i had it giving me a 1 or a 0 but as i kept messing with it i lost where i was at and saved over the copy. still new to posting sorry if its hard to read
#include <stdio.h>
#include <math.h>
void quadratic_function()
{
int a,b,c; // variables
long int result; // my X in the quadractic function
long int y,x; // the result
long int quadratic;
printf("enter values for a,b,c\n");
scanf("%i\n %i\n %i", &a,&b,&c);
printf("A=%i B=%i C=%i\n", a,b,c); //Displays Variables
y= pow(b, 2);
result= (y)*-4*(a)*(c); // b^2-4ac
printf("\n%li\n",result);
if (result<0)
printf("Imaginary Number"); // if negative
else (result>0);
x=(-b/2*(a)) +- (sqrt(pow(b, 2)) (-4*(a)*(c))) / (2*(a));
//solving for x
printf("\n %li\n",x);
a = a*x;
b = b*x;
quadratic=pow(a, 2)*(b)*(c); // if positive
//printf("Quadratic equation equal to %li",quadratic); // result
}
int main()
{
quadratic_function();
return 0;
}
The first thing I noticed is that you were trying to do the + and - portions of the quadratic equation at the same time. The equation
x = (-b +- sqrt(b^2 - 4ac)) / 2a
means the same as
x = (-b + sqrt(b^2 - 4ac)) / 2a AND x = (-b - sqrt(b^2 - 4ac)) / 2a
In other words, the equation has two answers if b^2 - 4ac is greater than 0, one answer if it is 0, and no answer if it is negative.
Another thing, the line else (result>0); doesn't really do anything. The rest of the code after that will execute even if you get b^2 - 4ac < 0
Finally, I wasn't entirely sure about your groupings or C++'s precedence with the negative sign, so I changed your parentheses around a bit.
y = pow(b, 2);
result = (y) - (4*a*c); // b^2-4ac
printf("\n%li\n", result);
if (result < 0) {
printf("Imaginary Number"); // if negative
} else if (result == 0) {
x = (-b) / (2 * a); // sqrt(0) = 0, so don't bother calculating it
a = a*x;
b = b*x;
quadratic=pow(a, 2)*(b)*(c);
printf("Quadratic equation equal to %li",quadratic); // result
} else if (result > 0) {
// solve for (-b + sqrt(b^2 - 4ac)) / 2a
x = ((-b) + sqrt(pow(b, 2) - (4 * a * c))) / (2 * a);
printf("\n %li\n",x);
a = a*x;
b = b*x;
quadratic=pow(a, 2)*(b)*(c);
printf("Quadratic equation equal to %li",quadratic); // result
// do it again for (-b - sqrt(b^2 - 4ac)) / 2a
x = ((-b) - sqrt(pow(b, 2) - (4 * a * c))) / (2 * a);
printf("\n %li\n",x);
a = a*x;
b = b*x;
quadratic=pow(a, 2)*(b)*(c);
printf("Quadratic equation equal to %li",quadratic);
}
I have a set of coupled equations for the variables H, W, P, & T (below) that I need to non-dimensionalize. Is there a way of achieving this in Mathematica as doing it manually is proving difficult.
{(a 1/(1 + R T[t]) - b) H[t] - (ap + bp) P[t] - bt T[t] == H'[t],
L P[t] - g W[t] - B W[t] H[t] == W'[t],
B W[t] H[t] - (up + b + bp + bt T[t]/H[t]) P[t] -
bp (P[t]^2)/H[t] ((k + 1)/k) + phi T[t] == P'[t],
H[t] (theta) - (b + bp P[t]/H[t] + bt ) T[t] -
bt (T[t]^2)/H[t] ((k + 1)/k) - v P[t] == T'[t]}
Parameter units: a = /H/unit time; b = /H/unit time; B = /H/unit time; theta = T/H/unit time; ap = /P/unit time; bp = /P/unit time; up = /P/unit time; v = /P/unit time; L = W/P/unit time; R = /T/unit time; bt = /T/unit time; phi = /T/unit time; g = /W/unit time; k = constant.
This package may help you to use the Pi-theorem.
I never used it, though.