How do I get a variable from one function into another? - c++

Exactly like the title says, how can I get my disc variable from my discr function into my calcRoots function?
// Function calculating roots
bool calcRoots(double coeffs[], int coeffLength, double roots[], int rootLength) {
if(disc >= 0) {
roots[rootLength - 1] = ((-(coeffs[coeffLength - 2]) + sqrt(disc)) / (2*(coeffs[coeffLength - coeffLength])));
roots[rootLength - rootLength] = ((-(coeffs[coeffLength - 2]) - sqrt(disc)) / (2*(coeffs[coeffLength - coeffLength])));
return true;
}
else {
return false;
}
}
// Solves the discriminant
double discr(double coeffs[], int coeffLength){
double disc = (pow(coeffs[coeffLength - 2],2)-4*coeffs[coeffLength - coeffLength]*coeffs[coeffLength - 1]);
return disc;
}

You didn't mention nay language but i supose to be C++.
Inside calcRoots you can make a call to discr and get the value to a variable like this:
double disc = discr(coeffs[], coeffLength);
Then use the value store in the variable. Hope this help.

Related

How to use std::any_of inside a class with lambda expression?

I'm coding a small simulation in c++ with robots and I need to check if the robot are colliding. I implemented this function in my simulation's class:
bool World::isRobotColliding(Robot *r) {
for (Robot *other_robot: robots) {
double d = distance(r->getX(), r->getY(), other_robot->getX(), other_robot->getY());
if ((r->getRadius() + other_robot->getRadius()) >= d) return true;
}
return false;
}
double World::distance(const double &x_1, const double &y_1, const double &x_2, const double &y_2) const {
return sqrt((x_1 - x_2) * (x_1 - x_2) + (y_1 - y_2) * (y_1 - y_2));
}
Here my IDE suggested me to replace the for loop with the std::any_of() method. However, I was unable to use it properly. This is what I tried:
return std::any_of(robots.begin(), robots.end(), [r, this](const Robot *&other_robot) {
return
(r->getRadius() + other_robot->getRadius())
>=
distance(r->getX(), r->getY(), other_robot->getX(), other_robot->getY());
});
How can I use std::any_of() in my context?
Thank you
Thank you everyone for your advise,
The issue was the pointer passed by reference.
return std::any_of(robots.begin(), robots.end(), [r, this](const Robot *other_robot) {
double d = distance(r->getX(), r->getY(), other_robot->getX(), other_robot->getY());
if(d == 0) return false;
return
(r->getRadius() + other_robot->getRadius())
>=
d;
});
This snippet do exactly what I was expecting.
I needed to pass the first robot r in the context as well as this. I could have declared a distance function in my robot and ommiting the this.

calling if statement and not updating it until it's finished

How can I call an if statement (or any other function) without calling it again, until it's finished executing? I have an update function that calls another function (in another class) but because it executes every update, the user doesn't get the time to actually complete the IF statements (the if statements rely on user input) so therefor it returns nothing or only the first part.
Code (where the update is):
public void Update(){
if(Mouse.isButtonDown(0)){
changeTile();
}
while(Keyboard.next()){
if(Keyboard.getEventKey() == Keyboard.KEY_RIGHT && Keyboard.getEventKeyState()){
moveIndex();
}
if(Keyboard.getEventKey() == Keyboard.KEY_LEFT && Keyboard.getEventKeyState()){
moveIndexBack();
}
}
}
changeTile function:
public void changeTile(){
boolean start = true;
if(start){
while(Mouse.next()){
if(Mouse.getEventButton() == 0 && Mouse.getEventButtonState()){
//system uses tileTypes because player textures are tiletypes itself, so in the end we can let them swim by changing tiletypes
int xCoord = (int) Math.floor(Mouse.getX() / 64);
int yCoord = (int) Math.floor((HEIGHT - Mouse.getY() - 1) / 64);
tileType tile1 = map[xCoord][yCoord].getType();
System.out.println("first tile is set to:" + tile1);
start = false;
}
}
}
if(!start){
while(Mouse.next()){
if(Mouse.getEventButton() == 0 && Mouse.getEventButtonState()){
int xCoord2 = (int) Math.floor(Mouse.getX() / 64);
int yCoord2 = (int) Math.floor((HEIGHT - Mouse.getY() - 1) / 64);
tileType tile2 = map[xCoord2][yCoord2].getType();
System.out.println("second tile is set to:" + tile2);
}
}
}

Variable inside lambda function is showing garbage value

I am using this method in a Cocos2d X game.
void OpponentNode::discard(int cardNum)
{
log("\nOpponentNode::discard <%d>\n", cardNum);
for (int i = 0; i < vecOpponentHand.size(); i++)
{
if (vecOpponentHand.at(i) == cardNum)
{
vecOpponentHand.erase(vecOpponentHand.begin() + i);
break;
}
}
CardSprite * discardedCard;
for (int i = 0; i < vecOpponentCards.size(); i++)
{
if (vecOpponentCards.at(i)->getTag() == cardNum)
{
discardedCard = vecOpponentCards.at(i);
vecOpponentCards.erase(vecOpponentCards.begin() + i);
break;
}
}
log("\nOpponentNode::discard <%d>\n", cardNum);
discardedCard->makeFaceUp();
RotateTo * rotate = RotateTo::create(0.4 * SPEED_MULTIPLIER, 0);
MoveTo * move = MoveTo::create(0.4 * SPEED_MULTIPLIER,
origin + Vec2(visibleSize.width * 0.75, visibleSize.height * 0.6));
Spawn * spawn = Spawn::create(rotate, move, NULL);
CallFunc * callFunc = CallFunc::create(
[&]()
{
log("\nOpponentNode::discard <%d>\n", cardNum); //this one shows garbage/different value
if (delegate)
{
delegate->opponentNodeDidFinishDiscard(this, cardNum);
}
this->removeChild(discardedCard);
});
discardedCard->runAction(Sequence::create(spawn, callFunc, NULL));
log("\nOpponentNode::discard <%d>\n", cardNum);
}
Strangely, when I log the integer cardNum like above, I get different value from the log inside the lambda function. For example, I get "OpponentNode::discard <402>" from the top 2 logs and the bottom most log but get "OpponentNode::discard <64>" from the log inside the lambda function.
Other points:
The lambda block is executed last.
I mostly get values like 64 or garbage values like -15493456.
My guess is the integer cardNum is getting deallocated before the execution. Can anyone point me to the right direction?
You're capturing a reference to the cardNum parameter. I would think you want to capture that one by value.
It's not clear to me what delegate is. Assuming it's a class member then I think you just need [this, discardedCard, cardNum]. Which you could abbreviate to just [=], although I think the explicit one is clearer.

optimize octree octant_determination function in c++

I am building a spacial octree. In order to determine in which branch/octant a certain point (x,y,z) should be placed, I use this function:
if (x>x_centre) {
xsign = 1;
}
else {
xsign = 0;
}
if (y>y_centre) {
ysign = 1;
}
else {
ysign = 0;
}
if (z>z_centre) {
zsign = 1;
}
else {
zsign = 0;
}
return xsign + 2*ysign + 4*zsign;
It returns a number between 0 and 7 unique for every octant. It turns out this snippet is called a big many times. It gets quite time consuming when building large trees.
Is there any easy way to speed this proces up?
This allready gives a 30 percent speed up:
xsign = x>x_centre;
ysign = y>y_centre;
zsign = z>y_centre;
return xsign + 2*ysign + 4*zsign;
Any other tips?

NSObject PerformSelector Issue

Hooooookay so here's another "I just have no idea what's going on" problem:
The first time I make a call to getFullWL() below, I get all my values as expected. Each subsequent call, however, returns nan instead of the true value(-nan(0x400000000) in XCode or something)
Furthermore, if I put my "debug" lines in SFLog the value prints as nan but returns the correct value! If I comment out SFLog (which is just a #define for NSLog depending on a level I set - nothing special), then the value is not caught by isnan() in View but is checked as isnan() in Window
Window and View are sitting on one thread, while DataModule and DCMPix are sitting on another (main thread, I believe). DCMPix also gets some data from a Core-Data object (fImage I believe).
void Window::PopUp()
{
// Grab the View from the Pipe Thread and cast it to my local namespace subclass View
View *view = static_cast< View* >(getPipe()->getView(event.context.view));
float fullww = view->getFullWW();
float fullwl = view->getFullWL();
//SFLog(#"WindowLevel Window %f", wl);
// set SLider Values
if (!isnan(fullwl)){
[[vc winLevel] setMinValue:fullwl];
[[vc winLevel] setMaxValue:(-1.0f*fullwl)];
}
}
float View::getFullWL()
{
float wl = _callPixMethod(#selector(fullwl)).floatValue;
if ( isnan(wl) ) wl = _wl * 2.0f; //<-- is never detected as NaN here
//SFLog(#"WindowLevel View %f", wl); //<-- but is *printed* as NaN here
return wl;
}
// A Union to "cast" the return from the [object performSelector:] method.
// Since it returns `id` and (float)(id) doesn't work.
union performReturn {
id OBJC_ID;
int intValue;
float floatValue;
bool boolValue;
};
performReturn View::_callPixMethod(SEL method)
{
DataModule* data;
DataVisitor getdata(&data);
getConfig()->accept(getdata);
performReturn retVal;
retVal.OBJC_ID = data->callPixMethod(_datasetIndex, _datasetID, method);
return retVal;
}
id DataModule::callPixMethod(int index, std::string predicate, SEL method)
{
DCMPix *pix =[[getSeriesData(predicate) pixList_] objectAtIndex:index];
pthread_mutex_lock(&_mutex);
id retVal = [pix performSelector:method];
pthread_mutex_unlock(&_mutex);
return retVal;
}
// DCMPix.m (from API, can't change)
- (float) fullwl
{
if( fullww == 0 && fullwl == 0) [self computePixMinPixMax];
return fullwl;
}
- (void)computePixMinPixMax
{
float pixmin, pixmax;
if( fImage == nil || width * height <= 0) return;
[checking lock];
#try
{
if( isRGB)
{
pixmax = 255;
pixmin = 0;
}
else
{
float fmin, fmax;
vDSP_minv ( fImage, 1, &fmin, width * height);
vDSP_maxv ( fImage , 1, &fmax, width * height);
pixmax = fmax;
pixmin = fmin;
if( pixmin == pixmax)
{
pixmax = pixmin + 20;
}
}
fullwl = pixmin + (pixmax - pixmin)/2;
fullww = (pixmax - pixmin);
}
#catch (NSException * e)
{
NSLog( #"***** exception in %s: %#", __PRETTY_FUNCTION__, e);
}
[checking unlock];
}
Help! Why would I not be getting the correct value in Window?
I also get no nan's when calling view->getFullWW() even though it follows the same execution path. (but calls #selector(fullww))
No Errors or exceptions are thrown. Just that bizarre behavior.
Thanks!
After further testing, the following change makes all the difference:
float View::getFullWL()
{
float wl = _callPixMethod(#selector(fullwl)).floatValue;
if ( isnan(wl) ) wl = _wl * 2.0f; //<-- is never detected as NaN here
NSLog(#"WindowLevel View %f", wl); //<-- is *printed* as NaN here
return wl; //<-- returns expected value
}
float View::getFullWL()
{
float wl = _callPixMethod(#selector(fullwl)).floatValue;
if ( isnan(wl) ) wl = _wl * 2.0f; //<-- is never detected as NaN here
return wl; //<-- returns `nan`
}
After more testing, it doesn't matter where I put the NSLog() statement, if it occurs before float fullwl = is assigned.
void Window::PopUp()
{
// Grab the View from the Pipe Thread and cast it to my local namespace subclass View
View *view = static_cast< View* >(getPipe()->getView(event.context.view));
float fullww = view->getFullWW();
NSLog("Putting this here, makes fullwl work. Removing it, stores fullwl as nan");
float fullwl = view->getFullWL();
//SFLog(#"WindowLevel Window %f", wl);
Whelp, Here I am answering my own question again but the answer is... RTFM.
The aSelector argument should identify a method that takes no arguments. For methods that return anything other than an object, use NSInvocation.
So the answer is, use NSInvocation and not [obj performSelector:]