Alex Edwards 321 Posting Shark

Whenever you use malloc() then free the memory using free().
Whenever you use new, then free the memory using delete.

Thank you very much for the clarification.

I made the changes. Here are the files with the revisions.

Alex Edwards 321 Posting Shark

After a quick look into it, I suggest that you get rid of malloc() usage. You are using 'delete' on memory that has been malloc'ed - that must not happen.
Then about 'delete', you only can delete something that has been allocated by 'new', consider

class a
{
public:
    a(){}

} instance; // an instance of class a

void somefunction(a* aptr)
{
    delete aptr;
}
int main()
{
    a * aptr = new a;

    somefunction(aptr);  // this is OK

    somefunction(&instance);    // <- must not happen

    return 0;
}

There were some other issues too, but I think first you could make sure that the basic memory operations are in order.
When I tried the program, addObject(adephi); causes the run-time to report damaged heap.

Oh that's interesting. I was told to delete memory that was dynamically allocated and that malloc was one of the types that you could delete?

On a side note I'm using Dev-Cpp 4.9 and I haven't updated my compiler so I don't get those kind of warnings unfortunately.

Alex Edwards 321 Posting Shark

i just remembered one of the more powerful reasons that ordinary parsing will not work for this project.

say instead of predefining x i wanted the actual multiplied form of 2(x+2)(x+2)(2x^2+2x+2). (^==to power of) i do not believe that ordinary parsing would suffice here, as anything in the ordinary JDK cannot multiply x*x to x^2.

sorry about the *bump*

Thats why I referred to using PEMDAS and substring.

Substring from the String class returns a particular "fragment" of the String inquestion.

What you can do is make a recursive method that pulls a chunk of information out of your String, solves it then places that solved chunk back into the original String.

You'd have to do this in order of operations, of course.

Either way it shouldn't be hard.

Right now I'm working on a C++, C# and Java project. Once I have some free time I will supply some code to help you understand what I'm getting at.

Edit: Also you should most likely use an enum type for all of your constants listed above. Either that or a final array but the array would be more difficult since you don't have a way of knowing what the constant is for without making an adjacent String array.

Alex Edwards 321 Posting Shark

I don't understand what is happening to my program...

I have a feeling that private members are marked private for a reason, because I'm having a serious error with accessing base-class data types via inheritance and declaring friends within classes...

If you run the test program after attaching the header in your include file you'll understand what I mean... the code is attached.

Sorry, I would actually post it but it's far too long and I have a feeling that the error may exist in more places since I used the friend modifier extensively =/

Note: I was trying to create a Game Creation library (well, namely for RPG's so I was going to rename it) by using a menu-type cluster object as well as "action" objects clustered together to be fired all at once, or select firing or both. Basically the purpose of the program is to allow flexibility for users to create their own games.

Edit: To be more clear, the information I'm trying to access isn't appearing on the screen properly or not at all.

Alex Edwards 321 Posting Shark

I am studying stacks, queues, and heaps at the moment but i dont know how i can apply this in real life. Well my question is how can these may i say operations helpful and when are they really needed as opposed to others. I hope you can get my question well. Thanx a bunch

If you need an easy way to relate to the data structures, you can think of a Queue as a type of line to wait in...

for example, when you're at the grocery store (or any place that gives some type of customer service) you're considered to be in a Queue-based system. If you were the first person in line, you are the first person to be served.

On the other hand, Stacks are Last-in first-out. Many businesses would not be successful if their lines were based on a "stack" system, even though it would be crazy funny to see people trying their hardest to be last in line just so they could be served first while people who came first would be waiting forever (or close to it).

A good example of a stack would be a set of heavy boxes. You stack one heavy box on top of another, and realize the first one (on the ground) is impossible to lift, so your best bet to be productive with the boxes it to remove the lightest one, which should always be the one on the top of the stack - …

Alex Edwards 321 Posting Shark

Hi all,

Thanks for your help so far ! I hope you wont mind if I ask you for help again..Being brutally honest I must admit that I didnt study the later material of the course properly what now effects in huge lacks in my knowledge...:'( after the Map and other Collection interface, the Streams have been introduced. I understand the whole concept of using them but I really struggle when it comes up to writing the method. I will post what I have come up with but am aware there are a lot of mistakes. I would appreciate if someone could check it and point me to the right direction.(the class OUFileChooser has been provided by the university)

The question:
Consider the following method comment and header defined for a
hypothetical class called FrogIO.
/**
* Prompts the user for a pathname which is then used to create a File
* object. The method then attempts to open a stream on that file.
* The method then writes the details of the frogs held in the argument
* frogCollection to the stream in CSV format
*/

public static void saveStateOfFrogs1(Collection<Frog> frogCollection)
Write the code for this method. Your code must make use of the File and
FileWriter classes. To achieve full marks your solution should make
appropriate use of buffering, inform the user of any exceptions that might
occur, and include a finally statement to ensure that …

Alex Edwards 321 Posting Shark

Wrong!

long double is stored in 80 bits. So their numbers have approximately 19 digits of precision in a range from 3.37 x 10-4932 to 1.18 x 10+4932 !

The poor problem is that neither printf nor cout of M$ visual c++ is able to print out long double values! So you need to changes compilers to do your homework. This is the result of 255 ! computed and printed out from a program compiled with well designed compiler:

1 Faculty is 1.00000000000000E+0000
2 Faculty is 2.00000000000000E+0000
3 Faculty is 6.00000000000000E+0000
4 Faculty is 2.40000000000000E+0001
5 Faculty is 1.20000000000000E+0002
6 Faculty is 7.20000000000000E+0002
7 Faculty is 5.04000000000000E+0003
8 Faculty is 4.03200000000000E+0004
9 Faculty is 3.62880000000000E+0005
10 Faculty is 3.62880000000000E+0006
11 Faculty is 3.99168000000000E+0007
12 Faculty is 4.79001600000000E+0008
13 Faculty is 6.22702080000000E+0009
...
21 Faculty is 5.10909421717094E+0019
22 Faculty is 1.12400072777760E+0021
23 Faculty is 2.58520167388850E+0022
. . .
100 Faculty is 9.33262154439442E+0157
101 Faculty is 9.42594775983836E+0159
102 Faculty is 9.61446671503513E+0161
. . .
200 Faculty is 7.88657867364791E+0374
201 Faculty is 1.58520231340323E+0377
202 Faculty is 3.20210867307452E+0379
. . .
249 Faculty is 1.29314250436364E+0490
250 Faculty is 3.23285626090911E+0492
251 Faculty is 8.11446921488186E+0494
252 Faculty is 2.04484624215023E+0497
253 Faculty is 5.17346099264008E+0499
254 Faculty is 1.31405909213058E+0502
255 Faculty is 3.35085068493298E+0504

Happy computing !

krs,
tesu

If you're going to make a statement …

Alex Edwards 321 Posting Shark

The type long double can hold up to 19 digits.

If that's not enough you could declare your own data type/class. Call the new class BigInt or HugeInt or whatever and use a string, as suggested, to hold char representations the individual digits. Overload the math operator *, and maybe the + operator, too, for the class and you should be set.

255! is 3.3 * 10^503, long double wont be enough =/

You'll definitely have to do "character addition" where--

you'll have to set up a class or method that accepts a number and calculates it via chars.

maybe something like...

const int MAX = /*number of digit locations for 255!*/, index = 0;
char *aString = new char[MAX];

//assuming factorial(int) is the method to do the factorial...
for(int i = 0; i < factorial(255); i++)//so long as I doesn't reach the max value...
{
        if(aString[index] != '9')
        {
             //Increment the first position by 1
             aString[index] = (char)(static_cast<int>(aString[index] + 1);
        }
        else
        {
                //check the current characters
               for(int j = 0; j < current; j++)
               {  
                    //if the number to increment is 9, set to 0 and increment the one after it by 1
                    if(aString[i] == '9')
                    {
                        aString[i] = '0';
                        aString[i + 1] = (char)(static_cast<int>(aString[i + 1] + 1);
                    }//process will repeat for chars equal to 9 after increment
               }
         }
}

If the above code works, cool. If not, be warned that I DIDN'T compile, but the idea is simple--

-> Make …

Alex Edwards 321 Posting Shark

Put in your mind that the result from the factorial will be added to a formula (i.e. I will add it or multiply it by another values, so the will program will calculate the factorial as a part of the complete formula “the big formula”). I am saying that to let you know that the array solution is not helpful in my case.


I have searched for the available data types that can handle the result but nothing until now.

thanks.

I wonder if you can calculate the value and immediately return/store it in a string?

But now I'm seriously beginning to think that you'll need scientific notation. This is an interesting assignment...

Alex Edwards 321 Posting Shark

I was just going to say "wouldn't implementing a scientific notation class be optimal?" But I guess we're staying away from STL's so... I think your instructor may expect you to represent the factorial as a collection of other factorials or.... as a string.

Either that or you will have to subtract the MAX VALUE of the positive number storing data type (a long long I believe), as you increase the factorial...

For example...

if you overshoot the amount a long long can hold, store the value in another long long variable after subtraction the max value of a long long...

You'll have to keep doing this until you finally get the number... but I suppose that's too much work.

It might be better to just search for an API that will handle this. This is obviously a lesson about data types and how to work around their limits.

Alex Edwards 321 Posting Shark

I created my own string class with a tokenizer method included, here's the code--

/**
   defined as header file myString.h

    a my_string class object takes 3 parameters--
    
    -a String literal
    -a character pointer
    -an object that inherits from the class ToString (a pure virtual class)
    */      
    class my_string
    {
          
          private:
                  char* theName;
                  
                  my_string()
                  {
                     //main initialization here
                  };
                  
          public:
                  my_string(char *name)
                  {
                      my_string::my_string();
                      theName = name;
                  };
                  
                  my_string(my_string *ms)
                  {
                       my_string::my_string();
                       theName = ms->getString();    
                  };
                  
                  my_string(ToString *ts)
                  {
                      my_string::my_string();
                      theName = ts->className();
                  };
                  
                  char *getString(){return theName;};
                  
                  friend std::ostream &operator<< (std::ostream &os, my_string &ms)
                  {
                      return os << ms.theName;    
                  };
                  
                  friend std::istream &operator>> (std::istream &is, my_string &ms)
                  {
                      return is >> ms.theName;
                  }
                  
                  void operator= (char *arg)
                  {
                       theName = arg;
                  };
                  
                  /**
                  Splits the string into several peices based on the token.
                  */
                  static my_string *tokenizer(char *value, char token){
                        int peices = 1;
                        
                        std::cout << "attempting to tokenize!" << std::endl;  
                            
                        for(int i = 0; value[i] != '\0'; i++)
                        {
                             if(value[i] == token)
                                 peices++;
                        }    
                        
                        my_string *strPtr;
                        strPtr = (my_string*)malloc((peices) * sizeof(my_string));
                        
                        int trailer = 0, current = 0, position = 0;
                        bool done = false;
                        
                        char *theString = 0;
                        
                        for(int i = 0; !done; i++)
                        {
                             if(value[i] == token || value[i] == '\0')
                             {
                                 current = i;
                                 
                                 theString = (char*)malloc(((current) - trailer) * sizeof(char));
                                   
                                 for(int j = (trailer); j <= (current); j++)
                                 {
                                      if(value[j] != token)   
                                          theString[(j) - trailer] = value[j];
                                      else theString[(j) - trailer] = '\0';
                                      std::cout << "j is: " << j << std::endl;
                                      std::cout << "trailer …
Alex Edwards 321 Posting Shark

Can you post the rest of your code? I have a feeling it has something to do with the way you've created your primHashTable class.

Alex Edwards 321 Posting Shark

Maybe you should try leaving out the parenthesis?

Also, why aren't you posting the error? You should at least do that if you want people on here to help X_X

Alex Edwards 321 Posting Shark

Did you even start/try?

Honestly these look like more than just beginner questions to me. In order to understand data structures, file io, and string manipulation you need to be pretty far into the course.

Are you telling me that you haven't been paying attention this entire time?

Alex Edwards 321 Posting Shark

That's the beauty of c++ though, learn how to custom build your own "helper" classes and you'll become more efficient at programming.

Alex Edwards 321 Posting Shark

Why not make an inner class extend from the color class and overwrite the toString() method?

Alex Edwards 321 Posting Shark
char FilePath[] = "C:\\Dev-Cpp\\keylogger.exe";

I think your problem is here, where you use \\ instead of // for your file path checking.

Try this--

char FilePath[] = "C:/Dev-Cpp/keylogger.exe";

Although I'm not too sure why you have two slashes instead of one.

also when creating an array like that, you may want to initialize it in this manner--

char FilePath[] = {'C',':','/','D','e','v','-','C','p','p','/','k','e','y','l','o','g','g','e','r','.','e','x','e','\0'};

I think I did that right, hopefully I didnt miss a char-symbol...

either that or just do it the symple way...

char *FilePath = "C:/Dev-Cpp/keylogger.exe"

whew..

Alex Edwards 321 Posting Shark

Wow please allow me to apologize. I wrote the solution inverted (slightly dyslexic @_@ )

#include <cstdlib>
#include <iostream>
#include <math.h>

/**
Successful!!! Whoo!
*/

using namespace std;

class Point;
class Triangle;
class P2DVector;

class Point{     
      private:
             double xP;
             double yP;
             
      public:
             Point(double x, double y){
                   xP = x;
                   yP = y;
             };
             Point() {xP = 0; yP = 0;}
             void Set(double x,double y) {xP = x; yP = y;}
             double getX(){return xP;};
             double getY(){return yP;};
             void showCoord(){
                  cout << getX() << ", " << getY() << endl;
             };
};

class P2DVector{
      private:
             Point points[2]; 
      
      public:
             P2DVector(Point& first, Point& second){
                      points[0] = first;
                      points[1] = second;        
             };
             P2DVector() {points[0] = Point(0,0); points[1] = Point(0,0); }
             void Set(Point& first, Point& second){
                      points[0] = first;
                      points[1] = second;        
             };
             static double power(double value, int exponent){
                    if(exponent < 0)
                    {
                        cout << "Negative powers currently unsupported.";
                        cout << "\nRetrying with positive value." << endl;
                        return power(value, -exponent);
                    }
                    else if(exponent == 0)
                        return 1;
                    else
                        return value * power(value, exponent - 1);
             };
             double getXDir(){
                    return (points[1].getX() - points[0].getX());
             };
             double getYDir(){
                    return (points[1].getY() - points[0].getY());
             };
             double magnitude(){
                    return sqrt( (power( points[1].getX() - points[0].getX() ,2) 
                                 +power(points[1].getY() - points[0].getY() ,2)));
             };
             Point startPoint(){
                   Point p(points[0].getX(), points[0].getY());
                   return p;
             };
             Point endPoint(){
                   Point p(points[1].getX(), points[1].getY());
                   return p;
             };
             P2DVector unitP2DVector(){      
                    Point unitPoint[2];
                    
                    unitPoint[0].Set(points[0].getX() / magnitude(), points[0].getY() / magnitude());
                    unitPoint[1].Set(points[1].getX() / magnitude(), points[1].getY() / magnitude());
                    
                    P2DVector temp(unitPoint[0], unitPoint[1]);
                    
                    return temp;
             };
             void displayLocation(){
                  cout << "This P2DVector Starts-> " << points[0].getX() << ", " …
Alex Edwards 321 Posting Shark

Thanks Alex,

I now understand how virtuals work, i thank you very much for your effort.
And one more question: So can virtual fuctions actually perform actions when they are not overwritten?

Thanks in advance,
Tigran

Only if they aren't pure virtual.

Alex Edwards 321 Posting Shark

Virtual functions mark the function declared to be overwritten by a class such that the method will perform the functionality of the derived class when the base class is called...

For example...

#include <cstdlib>
#include <iostream>

using namespace std;

class ToString
{
      public:
                virtual char *className(){return "No Name Set!";};
};

class Person : public ToString
{
      private:
               char *myName;

      public:
              Person(char *nameArg){myName = nameArg;};
              char *className(){return myName;};
      
};

int main()
{
    Person matt ("Matt");
    ToString *ts = &matt;
    cout << ts->className() << endl;
   
    cin.get();
    return 0;
}

This should print out "Matt," despite the upcasting of Matt into ToString.

This is because we marked the method of className() in the base class virtual- a derived class's data that overrides the method with the same name and arguments will, at runtime, force the base class to call the derived class's method.

This is particularly useful if we want to make an array (or pointer) to objects of many types and we only want to call one method to perform various kinds of functionality.

Alex Edwards 321 Posting Shark

Hi guys,
1) Why do some people set a "_" before things like function names?
I've seen this a few times, and asked myself if it had or didn't have any use.

A lot of this _class naming is done for library purposes, but it isn't restricted to that.


2) For this one, you should look at a simple code:

class TutorialApplication : public ExampleApplication
{
protected:
public:
    TutorialApplication()
    {
    }

    ~TutorialApplication() 
    {
    }
protected:
    void createScene(void)
    {
    }
};

First i'd like to say that this isn't my code, second i'd like to say that somewere in the source code there is a class definded with the name ExampleApplication.
Now comes my question:
As you can see in the first line, after class TutorialApplication comes something else.
but what is the function of that? It confuses me.

the : denotes an extension from another class. Since TutorialApplication extends from ExampleApplication, it will inherit all of the public and protected member fields of ExampleApplication and can be used as an ExampleApplication object.

3) My last question:
as you can see, there are 2 public functions defined:
TutorialApplication()(which i think is a constructor)
But there is also "~TutorialApplication()" which confuses me, what does it do? i mean with that strange "~" which i've seen for the first time...

The tilde ~ by the classname (like a destructor) denotes a Destructor. a Destructor is called when the delete operator or ~ObjectName::ClassName() …

Alex Edwards 321 Posting Shark
/*line 116*/    return time1 >= 0 && time1 <=1 && time2 >= 0 && time2 <=1;

Had to change line >= 0 to account for vectors at start-points of collision.

Alex Edwards 321 Posting Shark

YES!!! YES!!! It works!

#include <cstdlib>
#include <iostream>
#include <math.h>

/**
Successful!!! Whoo!
*/

using namespace std;

class Point;
class Triangle;
class P2DVector;

class Point{     
      private:
             double xP;
             double yP;
             
      public:
             Point(double x, double y){
                   xP = x;
                   yP = y;
             };
             Point() {xP = 0; yP = 0;}
             void Set(double x,double y) {xP = x; yP = y;}
             double getX(){return xP;};
             double getY(){return yP;};
             void showCoord(){
                  cout << getX() << ", " << getY() << endl;
             };
};

class P2DVector{
      private:
             Point points[2]; 
      
      public:
             P2DVector(Point& first, Point& second){
                      points[0] = first;
                      points[1] = second;        
             };
             P2DVector() {points[0] = Point(0,0); points[1] = Point(0,0); }
             void Set(Point& first, Point& second){
                      points[0] = first;
                      points[1] = second;        
             };
             static double power(double value, int exponent){
                    if(exponent < 0)
                    {
                        cout << "Negative powers currently unsupported.";
                        cout << "\nRetrying with positive value." << endl;
                        return power(value, -exponent);
                    }
                    else if(exponent == 0)
                        return 1;
                    else
                        return value * power(value, exponent - 1);
             };
             double getXDir(){
                    return (points[1].getX() - points[0].getX());
             };
             double getYDir(){
                    return (points[1].getY() - points[0].getY());
             };
             double magnitude(){
                    return sqrt( (power( points[1].getX() - points[0].getX() ,2) 
                                 +power(points[1].getY() - points[0].getY() ,2)));
             };
             Point startPoint(){
                   Point p(points[0].getX(), points[0].getY());
                   return p;
             };
             Point endPoint(){
                   Point p(points[1].getX(), points[1].getY());
                   return p;
             };
             P2DVector unitP2DVector(){      
                    Point unitPoint[2];
                    
                    unitPoint[0].Set(points[0].getX() / magnitude(), points[0].getY() / magnitude());
                    unitPoint[1].Set(points[1].getX() / magnitude(), points[1].getY() / magnitude());
                    
                    P2DVector temp(unitPoint[0], unitPoint[1]);
                    
                    return temp;
             };
             void displayLocation(){
                  cout << "This P2DVector Starts-> " << points[0].getX() << ", " << points[0].getY();
                  cout << "\nEnds-] " << points[1].getX() << ", " …
Alex Edwards 321 Posting Shark

Can you post your code please? It's unlikely that we can help you if you don't.

Alex Edwards 321 Posting Shark

I think I figured out the solution symbolically...

time2 = (((x2-x1)+((Vx)((y2-y1)/(-Vy))))/((Ux)+((Uy)/(-Vy))))

and therefore...

time1 = ((y2-y1)-((Uy)(time2)))/(-Vy)

Where Vx and Vy are the component directions of the 2nd vector and Ux and Uy are the component directions of the first vector, and the x and y are just specifying points.

I'm going to implement this code soon and see if it works. Hopefully it will, but I must study for my final.

Even if it doesn't work, I must admit that your advice turned out incredibly helpful.

I was capable of breaking down the problem algebraically and doing reverse-solving. These values wont be hard to implement in a function at all!

Alex Edwards 321 Posting Shark

Hello,

I'm getting a compile-time error in jdk1.2.1 which says "Identifier expected" and points to this line in the code:

Vector<Fish> fishes = new Vector<Fish>();

Aren't vectors supported in jdk1.2.1? I'm unable to catch the problem.

Vectors may be supported in jdk, but they may not be supported with Generics.

Try--

Vector fishes = new Vector();

Or update your development kit to a more recent version.

Alex Edwards 321 Posting Shark

ok folks, i couldn't find anything that wasn't crazy overly complicated, so I wrote it myself:
http://doriad.myrpi.org/ObjReader.cpp

The triangle intersection is a bit harder to post because it uses a big geometry library that I have written, but I'll post the main intersection function once I test it.

Dave

I've actually come up with a formula to solve for all intersections, however it's harder to implement than I thought.

Alex Edwards 321 Posting Shark

in the 2x2 case you can get away with taking shortcuts. I would warn you though, that you want to be careful not to divide by zero...

if you get anything higher than 2x2, it is time to do matrix operations.

hth

Yes I just noticed that doing division won't help... I either get a division-by-zero problem or the matrices cannot be multiplied =/

Damn...

Edit: For now I'm going to put this off... need to study for an upcoming final. Hopefully I'll be able to make some kind of algorithm for solving "string equations" and simply making this into one and solving it each time. Seems more ideal programming-wise.

Alex Edwards 321 Posting Shark

You could have an array filled with coefficients.

for example your 2x2 matrix A

a[0][0] a[0][1]
a[1][0] a[1][1]

Just for example,
if you have an nth degree polynomial with coeficients a0,a1,a2,...an

an * x^n + a(n-1) * x ^ (n-1) +... + a1 * x^ 1 + a0 * x^0

have an array a

int a[n+1];//populate with your (n+1) coefficients.

Actually, if there's a way to do matrice division (basically like multiplication, but backwards) then I think that would be a more ideal solution...

for example instead of--

|3 2| * |t| = |1-0|
|4 -1| _ |s| _ |0-0|

--I'd have something like--

|3 2| / |1 - 0| = |t|
|4 -1| _ |0 0| _ |s|

--Either way I have to somehow tell the computer to pause and then check for potential solutions if I am to use your coefficient method, otherwise if I use a coefficient array and do matrice multiplication I expect the computer to calculate the answer before solving for s in terms of t and vice versa.

I may have to create a separate program for this that reads the direction and position of the vector and solves for the collision... a major pain but it really seems necessary at this point.

Alex Edwards 321 Posting Shark

A note regarding clipboard usage, whenever you successfully open the clipboard, don't forget to close it by calling CloseClipboard() when you're done with the clipboard operations.

I swear to god I'm starting get my coding confused after seeing that...

Feels like CSharp when you use uppercased methods, when really it's C++...

Or maybe it's not, since I've heard that the Windows API isn't meant specifically for the C language.

Alex Edwards 321 Posting Shark

It's a damn shame I didn't take Linear Algebra during this quarter =P

Even so I believe I already have an algorithm for computing matrices.

Yes I'm aware of matrices, yes I know how to do matrice multiplication and no I didn't know you could transcribe vectors into matrices.

Now it's just a matter of programming this. It's not like you can use variable names as coefficients. Variables in programming store values, they are not considered scalars.

By the way, thank you for the intuitive response.

Alex Edwards 321 Posting Shark

Here is a better example, with more prints to show what is occurring in the tree--

#include <cstdlib>
#include <iostream>

using namespace std;

struct Tree{
       public:
              Tree *left;
              Tree *right;
              int item;
                     
              Tree(int value, Tree *leftNode, Tree *rightNode){item = value; left = leftNode; right = rightNode;};
};

int maxDepth(Tree* node){
  if (node==NULL){
  cout << "Reached a null node! Unwrapping!" << endl;
    return(0);
  }
  else{
    // compute the depth of each subtree
    cout << "Checking the left of " << node->item << endl;
    int lDepth = maxDepth(node->left);
    cout << lDepth << ", Recursing from maxDepth(node->left): " << node->item <<endl;
    cout << "Checking the right of " << node->item << endl;
    int rDepth = maxDepth(node->right);
    cout << rDepth << ", Recursing from maxDepth(node->right): " << node->item <<endl;

    // use the larger one
    if (lDepth > rDepth) return(lDepth+1);
    else return(rDepth+1);
  }
} 

int main(int argc, char *argv[]){
   Tree *a,*b, *leftsub, *rightsub, *d,*e, *f, *mytree;
   e=new Tree(14,NULL,NULL);
   d= new Tree(15,NULL, NULL);
   leftsub= new Tree(18,e,d);
   b= new Tree(22,NULL,NULL);
   f= new Tree(80,NULL, NULL);
   rightsub = new Tree(30, b,f);
   mytree = new Tree(20, leftsub, rightsub);
   cout << maxDepth(mytree) << endl;
   
   delete mytree;
   delete rightsub;
   delete f;
   delete b;
   delete leftsub;
   delete d;
   delete e;
    
   cin.get();
   return EXIT_SUCCESS;
}
Alex Edwards 321 Posting Shark

From what it looks like, your ints ldepth and rdepth are declared then initialized to a value returned by a function.

Because the function must perform functionality/calculating, the variable doesn't receive a value until the function is complete.

The variable will never be "complete" until one of the nodes it encounters is null (basically, it will return zero when it hits a null node of a leaf node) then it will return whichever variable is greater before that node since the function returned zero.

Even if the two nodes at the "bottom" were identical (same depth) it wont matter, the right depth variable will be incremented one. Then the function will keep returning and incrementing rdepth by 1 until it reaches the node that first called the function (which should be the root) and then the function will finally return the depth of your tree.

Edit: Also keep in mind how the tree is being traversed. It checks the left nodes first then the right nodes, so eventually all of the nodes in the tree are scanned and it will keep going as "low" as possible to get the deepest node and then eventually start returning values based on whichever is deepest.

I redid your code some to emulate the tree. Forgive me if I'm supposed to make Tree derive from the node struct, I wasn't certain. Anywho...

#include <cstdlib>
#include <iostream>

using namespace std;

struct Tree{
       public:
              Tree *left;
              Tree *right;
              int item; …
Alex Edwards 321 Posting Shark

Okay so I have a program that tests for collisions using a complicated and 80% accurate method, but I want 100% accuracy.

Like someone posted earlier about shapes colliding into each other, I realized that there will be cases where my method wont work.

However, I've looked into a calculus book and found a seemingly "easy" solution to the problem.


To be more descriptive...

If I have two vectors, and their cross product is not zero (they're not parallel) then they have the potential to intersect, or collide. So I know I have to implement a cross product (which wont be hard for 2D vectors).

That part is fine.

Here's where things get hard though - I need to determine the collision point for the two vectors.

Say vector a is defined to to have a direction of <3, 4> from point (0, 0). (3, 4) is the end point.
Also vector b is defined to have a direction of <-2, 1> from point (1, 0). (-1, 1) is the end point.

Linearly the two vectors can be defined as--

<3t, 4t> from time 0 to time 1 (where time can be seconds or whatever, doesn't matter).
<-2s + 1, s> from a separate time 0 to time 1 (where time can be anything again, doesn't matter. It just defines the point that vector is from "birth" to full existence.)

Here's the problem. I need to …

Alex Edwards 321 Posting Shark

I am preety lazy to use merge sort. The trick is to have an array of index which originally has numbers from 1 to n. and sort it along with the array. Here is a simple code.

#include<iostream>
using namespace std ;
int main ( )
{
    int a[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 } ;
    int index[11] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
    int i, j; 

    for ( i=0; i<10 ;i++ )
        for ( j = i+1 ; j < 11 ;j++ )
            if( a[i] > a[j] ) 
            {
                a[i] = a[i]+a[j] ; index[i] = index[i]+index[j] ;
                a[j] = a[i]-a[j] ; index[j] = index[i]-index[j] ;
                a[i] = a[i]-a[j] ; index[i] = index[i]-index[j] ;
            } 
     for ( i = 0 ; i < 11 ; i++ )
         cout << i+1 << "." << a[i] << " " << index[i] << endl ;
     getchar ( ) ;
}

end quote.

That seems like the hard way of doing it...

Why not simply make an array of nodes and sort the nodes by their value while incrementing their index at creation time?

Then when sorted, their natural index will always be retained.

Alex Edwards 321 Posting Shark

Interesting.

To check the array that is made of Strings, you just go

if(wordlist[1] = "whatever the name is")

Not quite, you never want to use the assignment operator for a boolean expression since it will always be true if the value stored isn't null.

You may want to use syntax such as--

if(wordlist[1].equalsIgnoreCase("whatever the name is"))


Thats how you check the array of Strings you made.
Your code is very complicated.

char array[]=wordList[0].toCharArray();

What does that above line mean? Your creating an Array called array and it is of char values and of no size. Then you are saying it is equal to the value of wordList[0]. Why are you doing this? It sounds kind of redundent don't you think?

Actually toCharArray() returns an array of the size of the amount of characters in the String value (not including the null terminator).

So if wordList[0] contains the String "Value" then toCharArray of that would be a char array of size 5 from indices 0-4.

The declaration char array[] means that the variable array is of type char[]. Size is later listed either directly or indirectly.

Alex Edwards 321 Posting Shark

When I try to use PI[n]->title, it won't let me access it because it's a private member. It only lets me access the public member functions. The problem is that the professor wants us to have the data private, so there must be another way. Ugh.

You could simply make a method with a return type that is exactly the same type of title.--

__typeof__(title) getTitle(){return title;};

Then access it--

PI[n]->getTitle()

--but from what I know __typeof__(element) is not a standard modifier and is frowned upon by programmers unless you're creating a library, so just return the type of title. Since it's string you'd use--

string getTitle(){return title;};

Alex Edwards 321 Posting Shark

Keep in mind that no matter which object you create, you must increment n so that your inventory is updated with the amount of objects created.

Basically whenever you add a book, CD or DVD you have to increment n. Just take a look at your destructor, it deletes pointers in the array up to n amount, where n cannot be or exceed 200.

Also to allocate memory to a pointer from an array of pointers you can use the syntax--

PI[n] = new [Whichever Inventory Item]( Parameters, if any)

--for each create/add method in Inventory.


Lastly you won't be able to allocate memory for an object of any type until you override the pure-virtual functions in the base class InventoryItem.

If you're inclined with Java or C#, you can think of the pure-virtual function as a marking of an interface or abstract class. If anything inherits from that class it cannot be instantiated until you override the pure-virtual methods.

Alex Edwards 321 Posting Shark
Alex Edwards 321 Posting Shark

Could you just put a simple if-statement in your mouseExited method?

public void mouseExited(MouseEvent e)
{
  if (e.getSource() != this.closeButton)
  {
    // do your current code here
  }
}

Either that or create a thread in your mouse-exited to wait a certain amount of seconds before making the close button invisible again.

Alex Edwards 321 Posting Shark

Thank you for the clarifications.

Now that I have a better understanding of pointers and reference-variables I'll be able to code much more efficiently.

Alex Edwards 321 Posting Shark

This is really sad... the page has been flooded so now we can't see the other replies X_X

Alex Edwards 321 Posting Shark

Oh I didn't realize that stack space wasn't a problem.

My instructor told me that the stack typically holds less information than the heap. That is the reason why I felt more inclined to learn pointers, but I suppose that isn't entirely true.

I also saw someone else's program where they used reference variables for their assignment and had trouble using them due to the variables being deleted the moment they were assigned... something along the lines of..

/*some code here*/ = Triangle (3, 4);

Where I guess Triangle was being declared, instantiated and then deleted and a null object was returned.

It's also confusing to get used to some of the reference-variable syntax compared to pointer syntax, such as--

Triangle tri (3,4); //looks like a drifting object

as opposed to

Triangle *triPtr = new Triangle(3, 4); //looks like an appropriate assignment.


Also when you redid my program Ancient Dragon I noticed that you declared 3 arrays without assigning them, so I guess the entire array was initialized via the default constructor?

If that's true, can I do something like--

Point myPoints[3] (2, 2);

or maybe

Point myPoints[3] = (2, 2);
--where all of the points are initialized to be (2, 2)?

Sorry for all of the questions but I'm still trying to get my head around appropriate usage of the types.

In all honesty I just want to increase the performance …

Alex Edwards 321 Posting Shark

Stack overflow usually occurs when you attempt to use recursion and the method never reaches a sentinel (or stopping case) because you're using the stack to calculate information per method call.

You'll have to find the recursive method in your code and find out why it isn't stopping when it needs to.

Alex Edwards 321 Posting Shark

Right, but I was wondering if anyone has this implemented? I would rather spend time on my actual work instead of implementing this that has surely been implemented 1000 times before!

You know, the funny thing is that when you mentioned this I worked on it right away since it seemed like an interesting project.

I have a program that creates triangles on a particular location in the imaginary Cartesian plane and can detect collisions using an equals assignment, however I'm still trying to figure out the accuracy of the collision-detecting operation.

So far it seems very accurate but more testing needs to be done.

Alex Edwards 321 Posting Shark

Correct me if I'm wrong but...

Each time I declare an object without assigning it a value, I am instantiating it (so long as the valid constructors is called upon doing so--)

like...

Triangle tri1 (3, 4);

and this object exists on the stackk but only for the duration of its life (which I still don't understand).

But if I do something like this...

Triangle *triPtr = new Triangle (3, 4);

it exists in the heap as dynamically allocated memory. Of course you have to delete (make the memory unallocated, or free) after using it should the program continue to run so you don't cause memory leaks..


My questions are...

-Why use the stack of the space is so limited?
-What are the advantages to using the stack over the heap?
-Is it really so bad to use pointers vs "reference variables?"
-What's the program's efficiency using a stack object over a heap object?
-What exactly is the life of a stack object? I hear that the existence of the object is dependent on its life or its declaration, which still confuses me...

Alex Edwards 321 Posting Shark
public ref class Form1 : public System::Windows::Forms::Form
	{
	public:
		Form1(/*void*/) //notice here that void is commented out... do that
		{
			InitializeComponent();
			CCenter^ Engine = gcnew CCenter();
			//
			//TODO: Add the constructor code here
			//
		}
...
Alex Edwards 321 Posting Shark

Unfortunately you will get flamed for making a post like that here.

Just fyi.

Alex Edwards 321 Posting Shark

i see your idea, but what about "2*sin(x+1)-log(90)"? that presents a mess of other problems, that i have slight idea on how to solve, but i am unsure of the way i should do it. and order of operations?

PEMDAS is your best friend

Paranthesis first, then Exponents, then Multiplication/Division then Addition/Subtraction.

What you want to do is create a stack that accepts parenthesis characters and then check the entire char-array for parenthesis.

If there is an uneven amount of parenthesis on one side of the char array than the other, throw an exception...

otherwise...

find the innermost expression from the parenthesis and substring it. From there find out what your variables are and what they are suppose to be when you encounter them (i.e., you'll have to make a String cosine = "cos", String sine = "sin").

When you run into a parenthesis char and it isn't aligned with a sin or cos then do an evaluation of the expression, solve it (by replacing variables if possible) by parsing it as a double or int argument (or long, etc) then concatenate the value into a String and replace that argument in parenthesis that you evaluated with the new evaluated String.

Rinse and repeat.

Alex Edwards 321 Posting Shark

>>To tell you the truth I was purposely trying to use pointers since they're very adjacent to Java's reference variables
I think you misunderstood the relationship. From what I understand Java doesn't have the concept of a pointer like what is in c++ pointers. The reference variables in Java are equivilant to the referneces in C++, not pointers. See line 45 of the code I posted.

In java the "reference variables" can be thought of as either references or pointers because you can dynamically allocate memory to these "reference variables" or assign them the address of another value... or the value will be automatically unboxed if it is a class type (that is the class representation of a primitive type) thrown into a primitive type, and vice versa.

The only differences I've seen is that you have no access to the stack in java like you do in c++ (since all reference-variables handle data in the heap) and that you can't use incremental operations on the java "reference variables."

It's part of the reason I felt comfortable with using pointers, but next time I'll be more cautious and take the time to study between when to use c++ reference-variables and pointers.

Thanks a million.