mrnutty 761 Senior Poster

It looks like depending on what the string contains you want to do certain action. You should look into the command pattern. Anyways here is one way.

#include <iostream>
#include <string>
#include <vector>

using namespace std;

struct Command{
    virtual void execute(const std::string& commandString) = 0;
    ~Command() {}
};

struct StoreCommand : Command{
    string& registerA;
    string& registerB;
    
    StoreCommand(string& regA, string& regB): registerA(regA), registerB(regB){}
    
    void execute(const std::string& commandString){
        //get string to store
        size_t startPos = commandString.find_first_not_of("store");
        size_t endPos = commandString.find("in");
        string data = commandString.substr(startPos, endPos - startPos - 1);
        //get which register to store in
        bool storeInRegA = commandString.find("registerA") != string::npos;
        
        if(storeInRegA) registerA = data;
        else registerB = data;
        
    }
};


//other commands...

//the dispatcher
void dispatch(string& regA, string& regB, const std::string& cmdStr)
{
    if(cmdStr.find("store") != string::npos){
        StoreCommand cmd(regA,regB);
        cmd.execute(cmdStr);
    }else{
        //command not supported
      
    }
}
int main (int argc, const char * argv[])
{
    using namespace std;

    string regA;
    string regB;

    string cmdStr = "store Hello World in registerA";
    
    dispatch(regA, regB, cmdStr);
    
    cout << "regA = " << regA << endl;
    cout << "regB = " << regB << endl;

    return 0;
}

Of course there are different ways of doing it. The basic logic is to find the keywords and from those keywords take the appropriate course of actions.

mrnutty 761 Senior Poster

What exactly do you need help with?

mrnutty 761 Senior Poster

>> omp_get_max_threads ( ) Spacing issue I think. Try omp_get_max_threads( )

mrnutty 761 Senior Poster

using namespace std;

your probably confused about what the above does. Look up 'C++ namespace'. In short, it makes public data that is in std namespace in your current scope. So instead of doing std::cout << "hello" you can simply do cout << "hello";. Notice I didn't have to specify the namespace std when using the cout object. Thats because when you write using namespace your basically telling the compiler to find variable in std namespace if not found in current scope. Of course thats a oversimplification.

mrnutty 761 Senior Poster

>>So here it is, what do you think:

Honestly, its crap (take it as a helping tip). If you didn't want to use isdigit, then at least use something simpler.

bool isDigit(const std::string& str){
 const std::string digitList = "0123456789";
 bool isValid = false;
 for(int i = 0; i < str.size(); ++i){
    if( digitList.find( str[i] ) == string::npos){ //if not found
         isValid = false;
         break;
    }
 }
 return isValid;
}
mrnutty 761 Senior Poster

Um... you have to check it for all character

//check if str contains only digits
bool isDigits(const std::string& str){
 bool isValid = true;
 for(int i = 0; i < str.size(); ++i){
    if(!isdigit(str[i])){
         isValid = false;
         break;
     }
 }
 return isValid;
}

Note, this code might be ambiguous in some compilers so a better way to do this is with functors

mrnutty 761 Senior Poster

>>Rewrite the Student_info structure to calculate the grades immediately and store only the final grade.

Seems like you want to do this in the constructor. Here is an example.

#include <iostream>

struct Sum{
 int total;
 Sum() : total(0){}
 Sum(int max): total( _calculate(max) ) { /*sum calculated already */}
 int _calculate(int m){
    return (m*m + m) / 2;
 }
};

int main(){
 using namespace std;
 Sum s(100);
 cout << s.total << endl;
 return 0;
}
mrnutty 761 Senior Poster

>I got lucky I guess!!!

Luck has rarely anything to do with it. People who are successful tend to follow a certain flow of action. For example, if you landed that job without any prior knowledge of computing/programming... THAT would be lucky.

Chances are you worked hard with programming, sometimes even completely failing with what you were trying to put across. But you learned from those mistakes and have become the person you are today.

That's what separates the winners from the losers. It's pretty much the same in all walks of life, whether you want to be the CEO of some super organisation or whether you want to have a hot chick down on her knees grabbing on your junk.

Without a strategy and without following through you're just another nodding-jack-who-knows-it-all, but hasn't really achieved anything substantial.

I'm sure we all know a person like this...

Thanks for information but I was trying to be modest lol. Of course in actuality, I have spent my college years plus my hobbies time to learn and better myself at this profession, where the first 2 years were pure obsession. Anyways, virtual drinks on me!

*                           )   *
                  )     *      (
        )        (                   (
       (          )     (             )
        )    *           )        )  (
       (                (        (      *
        )          H     )        )
                  [ ]            (
           (  *   |-|       *     )    (
     *      )     |_|        .          )
           (      | |    .  
     )           /   \     .    ' .        *
    (           |_____|  '  .    .  
     )          | ___ |  \~~~/  ' .   (
            *   | \ / |   \_/  \~~~/   )
                | _Y_ |    |    \_/   (
    *     jgs   |-----|  __|__   |      *
                `-----`        __|__
mrnutty 761 Senior Poster

Ok. So then you would have to parse the string :

string line;
while(getline(fileIn,line)){
 //assume each class is in its own line
 if(line.find("PosA") != string::npos){
    createObjectA(line);
 }else if(line.find("PosB") != string::npos){
    createObjectB(line);
 }else{
   /* error object not recognized */
 }
}
mrnutty 761 Senior Poster

>>Even though both variables have the value 30 in it, the if-condition gets satisfied and exception is thrown

The int gets promoted and you are now doing a floating comparison. When doing floating comparison, as of right now you can do a simple range comparison :

//checks if lhs is equal to rhs given an epsilon
//that is returns true if lhs \in (rhs-epsilon,rhs+epsilon)
bool isEqual(const double lhs, const double rhs, const double epsilon = 0.0001){
  return lhs > rhs - epsilon && lhs < rhs + epsilon ;
}
mrnutty 761 Senior Poster

So you need to perform a check. Something like so :

while(fileIn){
 const char peekChar = fileIn.peek();
 switch(peekChar){
   'A': createObjectA(fileIn); break;
   'B': createObjectB(fileIn); break;
   default: /* error, object not supported */ break;
 }
}

cin.peek() just peeks at the next character but doesn't 'read' it. So you can use that to your advantage.

mrnutty 761 Senior Poster

I got lucky I guess!!!

mrnutty 761 Senior Poster

Line 14-18 set all pointers to null.
Line 21 check if driver is null
comment out line 23 and see if it runs fine.

mrnutty 761 Senior Poster

Have you learned about for-loops? If so then using for loops is the correct way to solve this problem.

mrnutty 761 Senior Poster

Modern games are usually made with OpenGL, DIrectX, XNA or something else than win32. My advice to you is to not worry about win32 and pick up either opengl or directx

mrnutty 761 Senior Poster

Thats one approach.
1) You calculate the frequency of each letter in the ciphered text.
2) You have a frequency map for the english text
3) Get the highest frequency character in the ciphered text, and replace it with the highest frequency character in the map form step 2.
4) Then repeat step 2 for the next highest occurring character and so on...

Note you can also do this on a word based approach instead of letters or mix-and-match both styles.

mrnutty 761 Senior Poster

If the order doesn't matter then what you can do is
1) find the element A
2) If A does not exist then exit
3) Else if A does exist, then swap A with the last element in the array
4) Then simply set the last element to 0, and decrease the list's size

Then your done.

For me that notation is just a little annoying and sometimes can be in the way rather than helping me.

mrnutty 761 Senior Poster

Or maybe its conceptually better to have one boolean :

bool done = false;
bool validMove = true;
bool shouldContinue = true;
do{
 //...
 shouldContinue = done && validMove; //should continue only if all test are passed
}while(shouldContinue);
mrnutty 761 Senior Poster

In line 16 and 19, you are using State2 and State3, respectively, without defining State2 and State3 previously. At that line, the compiler doesn't know that State2 and State3 is. So it spits out an error.

mrnutty 761 Senior Poster

You got the first step correct -- to create a enum list.

Now your next task is to create a function that given a Enum Planet, it returns the string version of its name. here is a start.

#include <iostream>
#include <string>
using namespace std;

enum Planet {MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE, PLUTO};

string toString(const Planet& p){
 string str = "";
  switch(p){
   case MERCURY: str = "MERCURY"; break;
   //...
   case PLUTO : str = "PLUTO"; break;
   default : //..error none of the case mathced!
 }
 return str;
}
int main(){
 //...
}
mrnutty 761 Senior Poster

Among other things, you may have NULL pointers in your vector, which can't be delete d. Verify what's in your vector before you worry about what's wrong with your deletion code, e.g.:

// changed to while() loop to make logic more obvious
vector<T*>::iterator iter = x.begin();
while (iter != x.end()) {
    T* ptr = *iter;
    if (! ptr) {
        // NULL pointer in your vector
    }
    else if ( /* test to see if element should be removed */ ) {
        delete ptr;
        iter = x.erase(iter);
    }
    else
        iter++;
}

its perfectly fine to delete a null pointer

mrnutty 761 Senior Poster

Congratulations!

I just got word that I might be recalled from furlough next week - if it happens we should have a celebratory beer together in different bars.

hahah good luck man. As for the bar, I started a little early. Hope you don't mind!

mrnutty 761 Senior Poster

Make sure what you are deleting is something that should be deleted!. Anyways, the key point to take is that vector::erase returns a iterator pointing to the next element after the one deleted. If possible, put up the whole context(i.e full code )

mrnutty 761 Senior Poster

>>((i-2)/i);

your doing integer division. You want sum += (float)(i - 2) / i;

mrnutty 761 Senior Poster

Are you trying to delete a vector of pointers?

std::vector<x*>::iterator begin = x.begin();

while(!x.empty()){
 x* tmp = x.back();
 x.pop_back();
 delete tmp;
}
x.clear();
mrnutty 761 Senior Poster

Welcome to the world of pointers; a place where evil hides behind tricky beings.

mrnutty 761 Senior Poster

Oh! This really makes sense. Thanks so much. By the way, what does "r" mean?

"r" stands for read. Check out the documents for fopen

mrnutty 761 Senior Poster

>> Should I include the whole path name or just the image name?

If the file is in the same directory as your source file, then you can just use the filename, else you can either use relative path or full path. However it needs to be a valid path.


>>file = fopen(filename, "C:\\Users\\annette\\My Pictures\\face.png");

You want, file = fopen(filename,"r"); and the call can be GLuint texture = LoadGLTexture("C:\\Users\\annette\\My Pictures\\face.png", 396, 734);

BoBok2002 commented: This post was helpful and well explained. I understood it clearly +2
mrnutty 761 Senior Poster

You need to put line 69-70 in line 72.

bool isPrime(int num){
 for(int i = 2; i < num; ++i){
     if(num % i == 0) return false;
 }
 return true;
}
mrnutty 761 Senior Poster

Maybe give openGL a look. Not sure how well Embarcadero's tools would fit into that.

mrnutty 761 Senior Poster

Keywords, "Bode-plots", "Graphics"

Response: Use Matlab, that's what it was made for.

mrnutty 761 Senior Poster

Paste code here, People (including me) are too lazy to download

mrnutty 761 Senior Poster

Just some few comments/questions first.

1) you might want to think twice on that hungarian notation.
2) Does the order of the elements in the string matter? For example does the last element has to be the last ? So does the element position matters relative to its neighbors?

mrnutty 761 Senior Poster

Google Pascal's triangle, which is what I think essentially you are creating using 2d array.

mrnutty 761 Senior Poster

How would I do it in C++?

you can't do that with just pure C++. You will have to use external libraries like ncurses

mrnutty 761 Senior Poster

I'm assuming by internal node you mean all nodes except the leaf nodes? If so then possibly give this a try( haven't tested it )

bool hasLeftChild(const Node*const p){
 return p->left != NULL;
}
bool hasRightChild(const Node* const p){
 return p->right != NULL;
}
bool isLeaf(const Node* const p){
 return !hasLeftChild(p) && !hasRightChild(p)
}

int countInternalNode(const Node*const p){
 if(p == NULL | isLeaf(p)) return 0;
 else return 1 + countInternal(p->left) + countInternal(p->right);
}

EDIT: modularized a little

mrnutty 761 Senior Poster

Of course he means, http://latex.codecogs.com/gif.latex?sin^2(\pi*x/4))

mrnutty 761 Senior Poster

To determine the volume you use this formula general volume formule

where:

h = any dimension of the figure,
A(h) = area of the cross-sections perpendicular to h described as a function of the position along h. a and b are the limits of integration for the volumetric sweep.
(This will work for any figure if its cross-sectional area can be determined from h).

check wiki for more info. What are you having problem with? The formation of the integral?

mrnutty 761 Senior Poster

Couple of points.

1) Remove char arrays and use std::string.
2) Looking at the problem you can see that every different enemy will have different stats but in general will have same functions(i.e attack defend ), hence this suggest to create a polymorphic behavior. So I would suggest to do something like so,

//using struct for demonstration
enum EnemyType{ ARCHER, GOBLIN };
struct IEnemy{
 virtual void attack(IEnemy& opponent);
 virtual void takeDamage(int damageToTake); 
 virtual void getHealth();
 virtual void getPower();
 bool isDead()const{ return getHealth() <= 0; }
 EnemyType getType()const;
 virtual IEnemy() {}
};
struct Archer : IEnemy{
 int health;
 int power;
 
 Archer(): health(100) , power(10){}
 int getHealth()const{ return health; }
 int getPower()const{ return power; }
 EnemyType getType()const{ return ARCHER; }

 void attack(IEnemy& opponent){
     opponent.takeDamage( power ); //assume Archer give 10 points of damage
 }
 void takeDamage(int damageToTake){
    health -= damageToTake;
 }

}

//..and so on for other enemies
//..and go on from there
mrnutty 761 Senior Poster
mrnutty 761 Senior Poster

Thanks everyone.


>>how did you get the offer anyway?

It started from the carrer fair in my school, the liked my resume. Did a phone interview; passed it. Did a onsite interview with like 20 other candidates, and thankfully I got the job!


>>One of the things I've noticed that you don't run into with school work or working on your own projects...

I'm not sure what you are trying to convey with your previous post?

mrnutty 761 Senior Poster

I'm graduating this december and I got a job offer!!! Will be working for FactSet. I can't believe it. This is so crazy. Thanks everyone for helping me when in need. I'm just so happy :)

regards firstPerson

Ancient Dragon commented: Good work :) +0
mrnutty 761 Senior Poster

Man its been a while since this snippet. As to a response to your comments,

1) The title was misleading and incorrect. As you can see in line 84

if(!isValidNum(num1,base) || !isValidNum(num2,base) || base <= 0 || base > 36)  
  return "NULL";

that it rejects invalid bases and data.

2) Sure you can use int64_t but that still has the same fundamental issue as you said with int. If I wanted this to be general I could have use std::string. But this snippet was not to be used for production to handle every case. Its just a snippet to handle more cases.

Thanks for the input tho.

mrnutty 761 Senior Poster

>>Most of the time you'll see encapsulation rolled up along with data hiding, which while appropriate, is technically incorrect

care to expand?

mrnutty 761 Senior Poster

Yup I agree. Copy line 21 and place it in line 3

mrnutty 761 Senior Poster

>>

IMO, and this is just an opinion, the only time you should use exit() is when you have an error deep enough in your calling structure that getting back to main() is problematic. Like in a 4th level function that can't find a required file, and returning with an error up through the 2 other functions makes the code too messy. From main() itself, why call a function? Just return. It's simpler with fewer resources.

My 2 cents...

Usually, its rare to have such deep structures, at least for me since I never had the need for one. I would advice one to only use exit when the program cannot proceed any further because of a internal error like file not existing and such.

mrnutty 761 Senior Poster

Actually with the assumption of being a complete full binary tree, this problem turns out to be pretty easy. No need to reconstruct any tree at all.

Some more test cases:

in-order: 1 2 3
output: 2 1 3

in-order: 1 2 3 4 5 6 7
output: 4 2 6 1 3 5 7.

in-order: A B C D E F G
output: D B F A C E G

mrnutty 761 Senior Poster

>>for(int high = n-1; i= low; high-- )

Check the condition. The expression syntax is for(variable decleration,condition, operations) When you say "i = low" as a condition, you are saying "i = 0" since low is 0, which is false since 0 is considered false.

mrnutty 761 Senior Poster

No takers? Need hint?

First try to think of how you can use the information given to convert it back into a tree. Then worry about displaying it.

mrnutty 761 Senior Poster

line 27 is problematic because main variable doesn't exist there. What you want is something like this:

#include <iostream>
using namespace std;

void doOperation(){ /* do nothing for now */ }

int main(){
 bool shouldContinue = true;
 while(shouldContinue){
     doOperation();
     cout << "Repeat again<y/n> : ";
     char ch = 0;
     cin >> ch;
     if(ch == 'y' || ch == 'Y') shouldContinue = true;
     else shouldContinue = false;
 }
}