about pointers in c++ - c++

In the following questions, p1,p2, abd p3 are pointers to intergers. In the BEGINNING of each question *p1 and *p2 will both have the value 10.
after executing the following statements, what is the value of *p1 and *p2
p3 = NULL
p3 = p1
p1 = p2
p2 = p1
The way I did it i ended up getting 10 for both the same way they started.
p3 = NULL
p3 = p1 ;now p3 is set to 10
p1 = p2 ;now p1 is set to 10
p2 = p1 ;now p2 is set to 10
but I don't think I'm understanding it correctly.

The last line sets p2 to p1, which was just set to p2; so both p1 and p2 point to the original target of p2, which contains the value 10.

Don't confuse pointers to what they point to. *p1 and *p2 have value 10, that is, both p1 and p2 point to memory locations that have 10 written in it (although the memory locations may not be the same). It doesn't mean that p1 and p2 point to the same memory location!
Line by line:
p3 = p1; // p3 points to the memory location of p1, *p3 = *p1 = 10
p1 = p2; // p1 points to the memory location of p2, *p1 = *p2 = 10
p2 = p1; // p2 points to the memory location of p1, *p2 = *p1 = 10
So at the end of the day, you end up with: p3 taking the value of the original p1, then p1 taking the value of the original p2, and p2 being left unchanged.

This is really like playing a shell game.
So lets start with that.. here is the state after each line:
p1=orig1, p2=orig2, p3=orig3
p3 = NULL
p1=orig1, p2=orig2, p3=NULL
p3 = p1 (currently set to orig1)
p1=orig1, p2=orig2, p3=orig1
p1 = p2 (currently set to orig2)
p1=orig2, p2=orig2, p3=orig1
p2 = p1 (currently set to orig2)
p1=orig2, p2=orig2, p3=orig1
And as it said.. the original value of *p2 and *p1 is 10, so they will all be 10.

Related

Concurrent programming: synchronization of three theads using semaphores

We have three processes, which run concurrently and consist of the following statements:
P
Q
R
p1 p2 p3
q1 q2 q3
r1 r2 r3
Synchronize P, Q and R, fullfilling all of the conditions
simulatenously:
p1 must execute before q2
q1 must execute before r2
r1 must execute before p2
r3 must execute after p2 and q2
First I tried this:
pCompleted = Semaphore(0)
qCompleted = Semaphore(0)
rCompleted = Semaphore(0)
bothCompleted = Semaphore(0)
P:
Q:
R:
p1 pCompleted.signal() rCompleted.wait() p2 bothCompleted.signal() p3
q1 qCompleted.signal() pCompleted.wait() q2 bothCompleted.signal() q3
r1 rCompleted.signal() qCompleted.wait() r2 bothCompleted.wait() bothCompleted.wait() r3
It is needless to say this is extremely ineffective, maybe even wrong.
I think I can drop at least one semaphore without causing a deadlock:
P:
Q:
R:
p1 pCompleted.signal() rCompleted.wait() p2 pCompleted.signal() p3
q1 qCompleted.signal() pCompleted.wait() q2 qCompleted.signal() q3
r1 rCompleted.signal() qCompleted.wait() r2 pCompleted.wait() qCompleted.wait() r3
Still, I highly doubt this is a good solution.
Could somebody suggest an optimal solution?
I think this can be achieved quite easily with four CountDownLatches. For example,
CountDownLatch p1q2 = new CountDownLatch(1);
controls the synchronization between threads P and Q for the first bullet. Q waits on p1q2 before entering q2, and P countdowns p1q2 after exiting p1. And so on.
Note that the r3p2q2 would have to wait for two countdowns.
(And, obviously, you also need a thread D, with statements d1 and d2, where d2 must execute after r2 ;) )

runner technique for weaving elements of linked list

I've been reading the cracking the coding interview book. I am a bit stuck on implementing the runner technique for weaving elements of a linked list. The book goes as follows:
"Suppose you had a linked list a1->a2....->an->b1->b2....bn, and you want to rearrange it into a1->b1->a2->b2->.....an->bn. You don't know the length of the linked list but all you know is that it is an even number.
You could have one pointer p1 (fast pointer) move every two elements for every one move that p2 makes. When p1 hits the end of the linked list, p2 will be at the endpoint. Then, move p1 back to the front and begin "weaving" the elements. On each iteration, p2 selects an element and inserts it after p1."
Now I understand the technique up to the point before weaving starts. So, right before weaving, we basically have (for n=4 elements)
p1 p2
a1->a2->b1->b2
Now, if I understand correctly, I have to move the element pointed to by p2 (i.e. b1) and insert it after p1, in other words
p1.next = p2
which would result in the following list (?)
a1->b1->b2
How does the algorithm proceed from here?
I found this question but it seems to suggest that the above step would result in
a1->b1->a2->b2
which I do not see how. I am probably missing something fundamental here.
If A1 -> A2 -> ... -> AN -> B1 -> B2 ... -> BN is your original linked list, after the first step you'll have P1 and P2 pointing at A1 and B1 respectively. Let's say AN points to null, this can be done easily in the first step.
At each iteration, do these steps:
temp1 = P1.next
temp2 = P2.next //1
P2.next = P1.next //2
P1.next = P2 //3
P1 = temp1
P2 = temp2 //4
Here are the changes at the four positions in the first iteration:
1:
P1 P2
⬍ ⬍
A1 → A2 → ... → AN B1 → B2 ... → BN
⬍ ⬍
temp1 temp2
2:
P1 .–––––––––––––––.
⬍ ↓ ↑
A1 → A2 → ... → AN B1 B2 ... → BN
⬍ ⬍ ⬍
temp1 P2 temp2
3:
P1 .–––––––––––––––.
⬍ ↓ ↑
A1 A2 → ... → AN B1 B2 ... → BN //P2 points on B1
↓ ⬍ ↑ ⬍
↓ temp1 ↑ temp2
·––––––––––––––––––––·
This is equivalent to:
P1 P2
⬍ ⬍
A1 → B1 → A2 → ... → AN B2 ... → BN
⬍ ⬍
temp1 temp2
4:
P1 P2
⬍ ⬍
A1 → B1 → A2 → ... → AN B2 ... → BN
⬍ ⬍
temp1 temp2
And you repeat the same until P1 reaches AN.
The algorithms presented by Adam Stelmaszczyk, Igor Tandetnik and four_lines are correct; one only has to take care with the terminating condition otherwise the final nullptr that terminates the list can become lost. four_lines advocates handling this before doing the weaving. Or it can be done during the weaving by checking:
#include "stdafx.h"
#include <iostream>
namespace
{
struct elem
{
int val;
elem* next;
elem() : val(-1), next(nullptr) {}
};
}
int main()
{
// setup single-linked list of elements (an array here makes it easy...)
const int SIZE = 12; // even number
elem elems[SIZE];
for (int x = 0; x < SIZE - 1; ++x) { elems[x].next = &elems[x + 1]; }
for (int x = 0; x < SIZE; ++x) { elems[x].val = x; }
// divide the list using ptrs pf, ps to point at first part, second part
elem* pf = elems;
elem* ps = elems;
do
{
pf = pf->next;
pf = pf->next;
ps = ps->next;
} while (pf != nullptr);
pf = elems; // move pf back to start
// weave first and second parts of list using pf and ps
do
{
// update pf element next-ptr to point at ps, then move pf to its original next element
elem* oldpfnext = pf->next;
pf->next = ps;
pf = oldpfnext;
// if ps element is not at end, update ps element next-ptr to point the new location of pf
elem* oldpsnext = ps->next;
if (nullptr != ps->next)
{
ps->next = pf;
}
// now move ps to its original next element (even if null)...
ps = oldpsnext;
} while (nullptr != ps); // ... and stop if we are now at end
return 0;
}

What happens when we calculate this-(object of current class)

i have class name DPPoint what happens when we calculate this-(object of DPPoint) in same class and assign value to a variable of type int
If I understand correctly the question is about this:
DPPoint* p1 = new DPPoint;
DPPoint* p2 = new DPPoint;
int k = p1 - p2; // what is k?
That's perfectly valid code. It's called "pointer arithmetic". It will give you distance between p1 and p2 in sizes of DPPoint.
DPPoint array [10];
int k = &array[5] - &array[3]; // k = 2
int n = (int)&array[5] - (int)&array[3]; // n = 2 * sizeof (DPPoint)
(&array[5] == &array[3] + 2); // true
(&array[5] == array + 5); // also true
The pointers don't have to be in the same array. Can be two random addresses in memory (skipping alignment issues for simplicity).

Orthogonal Projection of Point onto Line

I'm referencing a mathematics paper, but the terminology is strange, and I'm unsure of how to code the following:
Return if the orthogonal projection of Point P exists on S(P2, P3).
I found std::inner_product but not sure if thats the correct method to use.
The concept is that you project P onto S and then check whether that projection P' is between P2 and P3.
To make it a little easier you say that P2 is the support-vector of S and P3-P2 is the direction-vector. You then project P-P2 onto the normalized P3-P2 (you compute the scalar-product between them) which gives you the distance D of P' to P2.
Now in your case you only want to know if P' is between P2 and P3. That is true if D is between 0 and 1.
You want the orthogonal projection of P (on the line given by P2 and P3) to be inside the segment [P2,P3]. Mathematically, it writes simply (I'm noting vect(A, B) the vector AB, because I do not know how to use the arrow notation):
0 <= vect(P2, P) . vect (P2, P3) <= vect(P2, P3) . vect(P2, P3)
You can indeed use std::inner_product but if your points are something as simple as:
struct Point {
double x;
double y;
};
You could just use
double operator - (const Point& a, const Point& b) {
return a.x - b.x + a.y - b.y;
}
double operator * (const Point& a, const Point& b) {
return a.x * b.x + a.y * b.y;
}
And the mathematical formula just gives:
bool is_proj_inside(const Point& P, const Point& P2, const Point& P3) {
double p_proj = (P - P2) * (P3 - P2);
double p3_proj = (P3 - P2) * (P3 - P2);
return (p_proj >= 0) && (p_proj <= p3_proj);
}
Yes, you may use inner_product (dot product) to take the result in very simple way.
Make vectors
V2 = P - P2
V3 = P - P3
V = P3 - P2
Find signs of dot products
D2 = Dot(V2,V) and D3 = Dot(V3,V)
Projection of Point P lies at S(P2, P3), if
D2 >=0 and
D3 <=0
Note - there is no need in normalizations, square roots etc. Just some subtractions, multiplications and additions.
(Explanation - angles P-P2-P3 and P-P3-P2 should be acute or right)

Projecting an arc through two points about a sphere

I'm trying to solve a problem where I need to essentially project an arc from P0 some distance through P1 about a sphere of a known radius, however I have a fairly limited knowledge solving this sort of problem outside of the standard Cartesian context.
To simplify, if I were doing this on a plane I would simply do the following
float distance = 30;
Vector3 direction = (P1 - P0).Normalize();
Vector3 endPoint = P0 + (direction * distance);
I'm essentially trying to see if there is a way I can solve that same sort of problem, only on a sphere instead of on a plane. This get's conceptually difficult as I need to account for the fact that P0 and P1 can (and will) be at arbitrarily different altitudes on the sphere.
I have a feeling that I will potentially need to convert from Cartesian to spherical space, but finding a jump off point here has proven very difficult.
Thoughts?
Let P0 and P1 be points, and consider a sphere of radius r.
First, say that P0 and P1 lie on the sphere, and that we want to travel a distance d. First note that we need P0 ≠ P1, just like in the linear algebra case. (otherwise, P0 = P1 and so there is no unique arc through P0 and P1.) Similarly, we need P0 ≠ -P1, as otherwise there is no unique arc through P0 and P1.
Now the arc from P0 to P1 lies on what is known as a great circle of the sphere. Basically, this is an intersection of the sphere with some plane through O = (0,0,0). More precisely, this is the unique plane through the points O, P1 and P2.
Some basic linear algebra will show you that this is the plane perpendicular to the vector P0 × P1, the cross product of P0 and P1. Note that the order of P0 and P1 is important in this product: in general, P0 × P1 ≠ P1 × P0, and if we took P1 × P0 instead then the direction of motion would be reversed. (i.e. we would be going from P1 to P0 instead.) Therefore the "direction" of P0 to P1 is given by a rotation about P0 × P1.
Now consider general points P0, P1. As melak47 points out, we can first project P0 and P1 onto the sphere, so we can get the rotation above in the "direction" P0 to P1. To project these onto the sphere, we further need that both P0 and P1 are non-zero, i.e. are not the origin. We also run into a problem when P0 and P1 lie on the same line through the origin, because then they project to the same point (or antipodal points) on the sphere and so don't define a unique arc: so in general, we need to check that P0 and P1 are linearly independent. Now note that P0 lies on the sphere of radius ||P0||, where ||P0|| is the norm of the vector P0.
Note that the radius r introduced above hasn't actually been used anywhere yet, and so we can set r = ||P0||. To travel a total distance of d on the arc P0 to P1', where P1' is P1 projected onto the sphere of radius ||P0||, the angle becomes d/||P0||, as above. The good news is that P0 × P1 is still a valid axis of rotation.
So in summary, you want to rotate P0 about P0 × P1 by d/||P0|| radians. In pseudo-code,
float d;
Vector3 P0, P1;
float r = norm(P0);
float angle = d / r;
Vector3 axis = crossProduct(P0, P1);
Matrix3 rotationMatrix = RotationMatrix(angle, axis);
Vector3 endPoint = rotationMatrix * P0;
Checking that P0 and P1 are linearly independent is the same as checking that P0 × P1 is non-zero, so in general you may want to check that axis != Vector3(0,0,0) before constructing the rotation matrix.
If you instead want to travel in the direction P0 to P1 on the arc P0' to P1, where P0' is P0 projected onto the sphere of radius ||P1||, we first need to replace r = norm(P0) by r = norm(P1) (obviously). Further, P0' = ||P1||/||P0|| * P0, and so we also need to replace rotationMatrix * P0 by rotationMatrix * (r / norm(P0) * P0), or rotationMatrix * r * normalize(P0) if you prefer.
IMO, your question doesn't have a single answer. It seems to be a 2D problem that occurs in the plane formed by the two given points and the center of the sphere.
But you need to give more constraints on the trajectory. It could be a straight line, an Archimedean spiral, a logarithmic spiral, a spline... or whatever you like.