StuXYZ 731 Practically a Master Poster

A multitude of errors, mostly caused by trying to write everything in on go.

(a) Patient includes an instance to Doctor. Therefore you must have a declaration of Doctor before Patient is declared. If it was just a reference or pointer you could have used a forward declaration e.g class Doctor; BUT you can't in this instance.

(b) Lots of typos. you use doc to mean doctor etc e.g. in the copy constructor for Patient. You write doctor1() in the main() { } section.

(c) Failure to call the base constructor in derived constructors and in the assignment operator.

(d) Lots of inconsitancy in format/layout which itself is not wrong but makes it difficult to see what is going on. For beginners I would recommend:
(i) Never use using namespace std; (ii) Don't put names of variables within declarations.
(iii) Consistent set/get naming so it is clear
(iv) copy Constructors are build like this e.g.

Doctor::Doctor(const Doctor& A) : Person(A),
  hour_fee(A.hour_fee),reg_num(A.reg_num)
{}

and the assignment operator like this

Doctor&
Doctor::Doctor(const Doctor& A)
{
   if (this!=&A)
     {
         Person::operator=(A);
         hour_fee=A.hour_fee;
         reg_num=A.reg_num;
     }
    return *this;
}

(v) Don't use a general protected, if that is what you have then change your model to a pure virtual inheritance.

(vi) Validate input.

esesili commented: it was very helpful +1
StuXYZ 731 Practically a Master Poster

If you are writing a Pong game, I think that you are going to learn a lot, so well done.

Second AI in Pong is interesting, there are at least three models:

(a) pure deterministic. That is the computer calculates exactly where is wants to be and tries to go there. TWO things need to be calculated in this (i) the ball position and (ii) the humans bat position because (normally, the edges of the bat give different angles to the ball exit tragectory).

(b) Pseudo random. The computer plays with perfect play but the information has a random error. It is often better to have larger random error from based on the distance that the ball is from the computers bat. The exact weighting value between 0 and 1 (ie. completely random and perfect info) give an excellent human/computer game play. [Adjust the value on each won point/game]

(c) Use a neural network to determine the position that the computer bat should go to, this again, can give excellent results, but the neural network can but untrained after each win to give excellent human/computer playability.

Just some thoughts on stuff I have tried in a couple of game simulations [not actually pong but very close]

athlon32 commented: Thanks DUDE!!!! +1
StuXYZ 731 Practically a Master Poster

If you don't want to post your code, then maybe a cut down version. But the quickest way to do it yourself is to compile with debug info on and then run and wait till it crashes. The backtrace will tell you what memory component has been corrupted. It may take a little to work out what has actually happened as another array may have over writen it. The debugger can help listing the symbol and memory addresses.

You can also try valgrind. http://valgrind.org. Which finds memory errors/leaks etc. [with a few false positives.] This is also very good at finding array boundary errors.

Typical things you will find are memory that is assigned but not deleted. Memory that is created with new but deleted with free() and vis-vera. Array over runs. e.g

// runtime error
int A[10];
for(int i=0;i<=10;i++)
  A[i]=i;

etc.
Similar things happen in char* because people overwrite the end of the array. If all the warnings are not on then you can do this

// WRONG code:
char *A="Enter key"
std::cout<<"A == "<<A<<std::endl;
std::cin>>A;

This works if the entry is less than 9 characters long.

tux4life commented: Nice post, nice link :) +9
StuXYZ 731 Practically a Master Poster

while you are fixing this. Please note that you often write

for (int count=0;count<customer;count++);
   {
      // Stuff
   }

Observe the semi colon after the for loop that should not be there since the body is not going to get executed until after the pointless loop. gcc gives warnings about this, as I expect every other modern compiler does, so please fix both errors AND warnings unless you are really absolutely certain the warnings are harmless. [Even then I fixe them to avoid output noise].

tux4life commented: Good observation! +8
StuXYZ 731 Practically a Master Poster

This thread is getting a bit messy. So I am going to write a quick summary and how I would tackle the problem.

First: Coordinates are almost never integers, and once you have solved a 2d problem you often need a 3d solution, and sometimes higher dimensions.

What has been missed (I think), is a clear understanding of what can be done with coordinate transforms and vectors.

Considers a triangle defined by 3 points A, B ,C and each point
is A is (ax,ay) , B is (bx,by) etc...

Any linear translation or rotation or scaling, does not change the angle . For example triangle if you cut a triangle from paper and then drop it on your desk. You can rotate it any way you like cand you can place it anywhere you like and the angles don't change.

That relates to the problem in that you can translate the triangle to an origin. e.g after entering three points A,B,C as above, you shift the triangle by -A to get three new points which include the origin (0,0).

However, you can find the vector displacement that connects the points. For example, if you want to go from A to B, then you need to move (bx-ax,by-ay), likewize B to C is (cx-bx,cy-by) and going from C to A is (ax-cx,ay-cy), these vectors can be written as
[tex]\vec{AB}[/tex] etc.

For two vectors, the dot product is defined as.
[tex]\vec{A}.\vec{B}=|\vec{A}||\vec{B}|\cos(\theta)[/tex]

Nick Evan commented: Sounds like a plan! +17
StuXYZ 731 Practically a Master Poster

Sorry, but most of these solutions are inelegant and that is because to achieve randomness they require an excessive number of random number calls:

(a) Shuffling the stack by selecting two cards and exchanging requires about 7 times the deck of length to get to nearly random on a 52 deck set, and more on a later deck. It is because you can't ensure that you avoid leaving pairs (do this with a deck of 1,2,3,4 ... etc and shuffle and see how many consecuative pairs you have.

(b) If you loop through the deck index in the forward direction and then swap, you definately want the possibility that a card does not move. BUT this shuffle is flawed. Take a deck of 26 0 + 26 1 in that order ie. 0,0,0,0.....,0,1,1...1 and then shuffle. If you do the shuffle once and then add the first 5 cards you get about 2.55 and 2.45 for the sums as you repeat to an infinite number of tests. [i.e. shuffle the deck, sum, reset the deck] * infinity. That is a significant fraction for a casino to lose. The drift to pure randomness is asymptotic.

(c) Use the algorithm shuffle. Depends on implementation but normally very good

(d) something that is random is this: [ well significantly better than either (a) or (b) ]

int deckIndex[52];
int deck[52];
for(int i=0;i<52;i++)
   deckIndex[i]=i;

for(int i=52;i>=1;i--)
  {
     // ugly: Use a proper random number system e.g
     // Mesene Twister. …
jephthah commented: nice +6
StuXYZ 731 Practically a Master Poster

You can't copy it to a set and back again without breaking the order.
Sets store on a compiler defined manor but normally red-black trees.
Hence you will destroy the order.

The easiest way is to copy to another vector sort, unique
and then find the copies.

Another slightly more involved way is to copy to a map in which you have the positions in the vector as the second component. The remove the clashes. Depending on the vector type a hash map may work better.

robotnixon commented: thanks for the help +2
StuXYZ 731 Practically a Master Poster

Below I am going to post a working set of code.

The requirements are simple. You write an implimentation of foo and you put template class Foo<float> in that implimentation.
This is 99% portable and 100% within the standard. It works on portland, IBM, and g++. I don't have VC++ to test it against but I guess it will work there if you have it.

Next: The compile sequence is something like this:

g++ -c class1.cpp
g++ -c ultra.cpp
g++ -c foo.cpp

g++ -o ultra ultra.o class1.o foo.o

You compile one and only one instance of foo.cpp, which builds one and only one version of Foo<float>.

This route completely avoids the problem of hundreds of implimentations on each instances. Speeds compile time up hugely.
This is the normal route for any LARGE class which is only likely to have a few template instances. Sure with something like std::vector, you need to include it in a .h file since it (a) is a small class (b) has many different template instances in a code base.

// foo.cpp
#include <iostream>
#include "TemplatedFoo.h"

template <typename T>
//inline  <- works if uncommented
T Foo<T>::getValue() const{
  return m_value;
}

template <>
//inline  <- works if uncommented
Foo<float>::Foo(const float value ) {
  std::cout << "I do floats:\n";
  m_value = (value);
}

template <>
Foo<std::string>::Foo(const std::string val)
{
  std::cout << "I don't do strings:\n";
}

//THE BIT YOU KEEP MISSING: GOES HERE
template class Foo<float>;
// Templatedfoo.h
#ifndef TEMPLATED_FOO_H …
monkey_king commented: very helpfull and throughly +1
StuXYZ 731 Practically a Master Poster

Please note that the code you have is 99% wrong.

Consider

Polynominal A;
A=A;

And before you say you would never do that, be very very careful of compiler opimization, double loops that i=j (e.g. for(int i=0;i<N;i++) for(int j=0;j<N;j++) and many other places.

You should write FOR EVERY operator= (-- with a MINIMUM of a paragraph of comment if you break the rule) this:

Polynomial&
Polynomial::operator=(const Polynomial& A)
{
    if (this!=&A)
      {
          // coping stuff
      }
    return *this;
}

Additionally, since you are actually in the class I stronly suspect that you don't need the

for (int i = 0; i <= rtSide.degree(); i++)
		this->setCoefficient(i, rtSide.coefficients.at(i));

which is ugly since you use setCoefficients but access coefficient directly.

but rather just

coefficients=rtSide.coefficients;

you might need to add a little index/other parameter control etc
but it is likely to be much quicker AND much less error prone.

StuXYZ 731 Practically a Master Poster

That is no fun comatose!!!! The program should write itself without reference to the source code!!!

You want to look up quine

e.g.http://prokutfaq.byethost15.com/Cquine

I distinctly remember the first time I saw a quine program,. fortran-77 -- I am getting old :) -- and I was very happy when I finally groked it.

Comatose commented: :) +10
StuXYZ 731 Practically a Master Poster

errh... sorry Ancient Dragon, but the last line of the file is just "="?
Which was what I was trying to allude to.

The probelm seems to me to be that you read that with a statement while(partin >> charInput >> numInput) Now you get charInput set to "=", which is correct BUT then the program has to get an input into numInput. If the stream is empty then you just wait. So the program just sits. The while loop condition does not get tested because stream::operator<<(int&)
simply never returns.

The better way to do it is to read whole line of input and then divide the line up.

StuXYZ 731 Practically a Master Poster

Ok the usual rant: I hate system("PAUSE") and CLS. They are non-portable, and I can clear my own screen if that is what I want!

Beyond that you haven't given us much to go on.
You don't test if displayData2 is successful? Does "userInformation.database.txt" exist / get opened, have Windows throw a fit about two dots in the name ?
Use if (disPlayData2.good()) to find out.

Then the lines

while (displayData2 >> tempData)
      {
	<< number <<"\n";

do not compile. Did you mean to pass the number to std::cout, and what is tempData??

You need something like

class userInfoRecord
{
   //stuff
};

std::istream&
operator>>(std::istream&,userInfoRecord&);

and then
tempData should be a userInfoRecord and your test should be if (tempData.getNumber()==number)

StuXYZ 731 Practically a Master Poster

Returning to the problem asked:

The problem is that you have created a class that does nothing.
If you take the trouble to create a class don't ignore the values.
You can put tar=100000; and it will make ABSOLUTE NO difference to the code. I think you have confused yourself by using tar in the class AND tar in the function calculate tip. These are DIFFERENT varaibles

What you might like to do:

class Tip
 {
    private:

        const double taxRate;
        double totalTips;
        double totalBill;
   public:
       Tip(const double TR) : taxRate((TR>=0.0) ? TR : 6.50) {}

       void addBill(const double,const double);
};

void Tip::addTip(const double bill,const double tipRate)
{
  //Your code here -- check for 
  totatBill+=bill;
  totalTips+= // your code;
}

also you might like to note that (for a taxRate in percentage) tax=bill*taxRate/100.0; Finally, money is calculated to the nearest cent/penny, and some care is needed about double giving you 0.3333 etc.

StuXYZ 731 Practically a Master Poster

Please be VERY CAREFUL with this code.

Consider

// THIS IS VERY VERY WRONG!!!!
char * getName(){
    char buf[YOUR_ARRAY_SIZE];
    sprintf(buf,name);
    return &buf[0];
}

The code above is a runtime error, the problem is the you have a local variable (buf) and that goes out of scope at the end of the function. BUT you are passing the pointer to that memory, which you expect to use!!! It is possible/likely that sometime later the program will use that space for something else. Then you will have corrupted the string you are looking at, or even worst you might actually change it!!!!

The orginal is correct, if you want a copy (to manipulate) then make a local copy out of the methods. If you want to change a buffer in the class use a class method.

Sorry for the rant but this kind of error, is normally (a) Very difficult to debug, (b) dormant for a long while so it ends up in customers code.

vmanes commented: Very good point. +7
Salem commented: well spotted +27
StuXYZ 731 Practically a Master Poster

I think that the problem is not the code, but your maths.

Let us start with a number, e.g 89 as use used. What does writing 89 actually mean: that there are 8*10 + 9.

If you write in base 4 , say 31, you are saying that you have 3 groups of 4 + 1 extra. ie. 3*4+1.

The code you are having trouble with is bascially to convert from a normal base 10 system to the required base.

So put simple, for base4 you need to use multiples of 4 e.g.
4, 16, 64 etc. and express the number in multiples of them plus a units number.

e.g. 47 : well you could write (47) units, but what about : (11) lots of four and 3 units. Then you might like (2) lost of sixteen and (3) lots of 4 and 3 units. i.e in base 4: 233.

To get that number in computer code you, first see what the remainder is when you do Number/Base e.g. 47/4 the remainder is 3. (In C++ that is expresses as 47 % 4). Then you see what you get when you divide by 4 but ignore the remainder e.g.
47/4 = 11. (In C++ with integers , that is 47/4). Now you also have a shorthand that is that you could write a=47; a=a/4; but you can also write a/=4; which is the same.

Hope that helps.

C++ is the …

StuXYZ 731 Practically a Master Poster

Please do us all a favour and don't double post on multiple forums
E.g.

http://www.codeguru.com/forum/showthread.php?threadid=469551

You were shown short shrift there, because you code is absolutely awful, and you didn't follow their forum rules either.

In addition you didn't take the time to read ANY of this forums rules.

Putting Richard Chaaya's name on the post wasn't to clever either.

Salem commented: *agrees* +27
Comatose commented: *also agrees* +9
Ancient Dragon commented: Awesume answer +36
StuXYZ 731 Practically a Master Poster

This a mess, and the main reason is that you have tried to do WAY to much in one go.

So, you really really need to start again. I can assure you that it will help. Open a clean editor window and start again. The problems of your code are many and most are that you didn't have a short piece of code to test and get right before moving on.

So what to do this time that will prevent the mess of the first one:

Start with one component. Let us say you are going to read some data from the census. What about creating a class for that information. e.g.

class censusRecord
{
   private:

     std::string Name;
     int frequency;
        
   public:
     censusRecord();
     censusRecord(const censusRecord&);
     censusRecord& operator=(const censusRecord&);
     ~censuRecord();

     int getFreq() const;
     const std::string& getName() const;

      void write(std::ostream&) const;
      int read(std::istream&); // returns -1 on failure / 0 success
};

Quick comment on the class (a) it can readily be extended as extra information is required. You can easily add comparison operators if you want to go down the route of stl sort and such like. It lets you get the data so that comparison functors or simple functions to do comparison are easy to write. (b) I have provided read/ write so that you can write operator<< if you wish or just a getline and check the line against the read , if good store the result.

Then you have a class for reading and …

StuXYZ 731 Practically a Master Poster

I wish to comment again, since I now have understood what you are doing!!!! -- Well at least the problem, the code that is a different problem.

Let me see you want to get a position were the columns/ rows AND diagonals all sum up to numbers as a factor 3.

Now let us do this on a piece of paper. Then you will see that you really don't need much computer code.

First question should be given 9 random numbers CAN it be done.
Let us consider the problem: There are three rows, three columns and two diagonals. To get all of them to add up correctly, you need
to change the problem to a matrix of remainders. It doesn't matter if the number is 983231 or 2 both have the same remainder on division by 3.

Convert the numbers to 0,1,2 (or I prefer -1,0,1 but it is unimportant).
Now you add everything up, if the sum is not 0,9 or18 then you can't do the problem.

Next you have to find a solution:
You are aided by the fact that the contributions are
4 points (2 times) [outside middles]
4 points (3 times) [corners]
1 point (4 times) [centre]

The solution has to be symmetric, and the solutions (with the multiplication for occurance must again be a factor of 3).

There are a small set of symmetric graphs and it is quick to …

VernonDozier commented: Simplifies the problem well! +11
StuXYZ 731 Practically a Master Poster

I was the original person who suggested using a sieve of eratosthenes. Now does this still hold? I believe so and here is why.
You were required to find the factors. The only factors of importance are prime factors, all other factors will be bigger since they are a combination of two or more prime factors. Hence you only need to test prime factors.

You now need a way to generate prime factors upto (at a maximum) the sqrt of the number. Then test them.

The SIMPLEST TO CODE method of finding prime factors is the sieve of eratosthenes.

In addition, the SoE is progressive, so after finding a new prime, it is tested and if a factor, the target number is divided and if the new target number is less than the square of the newly found factor, then the new target number is prime and the problem is finished.

I did then suggest that testing if a number is prime is easier than factoring and it is a good idea to test the target number first (because if it is prime then that is the end of the problem). [but this is a refinement of the original problem solution]

If you look a typical Pollard Lenstra number sieves, code for finding prime factors you are at >1000+ lines, that is serious code.

So Rashakil Fol please explain to us WHAT else you would do? you have said that I am dumb …

arun_lisieux commented: Very patient and helps out well. +1
StuXYZ 731 Practically a Master Poster

This is a problem that requires thought NOT code.

The answer can be easily found on a piece of paper.

So without giving you the whole solution try thinking about this
Obviously 20! (20x19x...1) is a solution but it is not the minimum.

Now you have two types of numbers primes and non-primes:
2,3,5,7,11,13,17,19 : so your solution has to be a factor of
2x3x5x7x11x13x17x19 == 9699690
[Sorry I actually did that on calculator ;) ]

Then it is easy, all you have to do is find all the prime factors of each other number and find the lowest common addition to the prime list that you already have. Then you have your answer.

E.g. for the above consider 6: it is 2x3 so no addition is required.
But 4: is 2x2 so you have to add at lease one 2.

That is a much much better way of solving the problem, particularly because if I was setting the problem, next week I would add that I want the lowest 1-1000, and brute force methods will die.

Salem commented: Excellent, think the problem first, then write code. +27
StuXYZ 731 Practically a Master Poster

The obvious stuff is wrong : use of '\n' rather than std::endl. the complete lack of tests for input values.

e.g Would this be wrong

IntStack stack(-40);

so that is why you have a problem with IntStack stack(0) since you initialize p=new int[0]; and then things are not good.....

You should have checks on all the input of the public function, that includes the constructor.

Also it is normal in stacks to have a separate top() and pop() function. That is because what should you return if the stack is empty ?

Comatose commented: Great Explaination Along With Solution. +9
StuXYZ 731 Practically a Master Poster

Before you get strangled with compiler errors. Please note that in c++
you write public: Then all things below are public (until either the end of the class or one of private: or protected: The reason I am flagging THIS error up, is that the compilation error you generate is likely to be completely indecyferable.

Complete diversion : [P.I.M.P please ignore (sorry)].
VernonDozier said:

There's no function in C++ that can retrieve the length of an array.

Now I would have agreed for the last 20 years BUT last week I saw this:

template<typename T, int size>
int getArrayLength(T(&)[size]){ return size; }

And that works in a simpler context (ie the given situation)

#include <iostream>

template<int size>
int
func(int (&X)[size])
{
  std::cout<<"X == "<<size<<std::endl;
 return 0;
}

int main()
{
  int A[50];
  int B[80];

  func(A);
  func(B);
  return 0;
}
VernonDozier commented: Nice. +11
StuXYZ 731 Practically a Master Poster

Let me see now your first post you were told that we don't help with assignments unless effort is shown.

THIS post you decide to ignore that reality and persist in asking please do my assignment for me.

The ONLY way you are going to get help is to actually show some effort.

The only good thing about your post is that you are likely to be competing with me for a job when you leave university and I fancy my chances since you can neither code nor learn. [Although I am worried about some of the other very knowledgeable posters ;) ]

Ancient Dragon commented: good advice :) +36
Salem commented: Nicely put +26
StuXYZ 731 Practically a Master Poster

The question should be asked "how do I delete a pointer if I allocate the memory using xxxx?"

Let us review:

if you write

double* Ptr=new double[50];    // Allocate space for 50 double s
// ... other code
delete [] Ptr;                             // Delete the pointer to 50 doubles
// CARE:
// Ptr is still pointing to a value

but if you write

double* Ptr=new double;        // allocate 1 double 
//.... other code
delete Ptr;                       

Note as pointed out, delete removes the memory for the pointer BUT does not change the value of the pointer variable. e.g.

double *Ptr=new double[50];
std::cout<<"Ptr memory location == "<<reinterpret_cast<long int>(Ptr)<<std::endl; 
delete [] Ptr;
std::cout<<"Ptr memory location == "<<reinterpret_cast<long int>(Ptr)<<std::endl; 
// 
// THIS CAUSES A RUNTIME ERROR:
// DO NOT DELETE TWICE
//
delete [] Ptr; 

Note in the above example , if you set Ptr=0; after the first delete then all is well.

Finally::

double X[50];        
//.... code
// NO DELETE Required:
// THIS CAUSES A RUNTIME ERROR:
delete [] X;    

If the pointer is from an object that is not allocated via a new then don't delete it.

Note: that if you are using malloc etc, then you must use free. If you are not using malloc, then don't start using it.

Hope this helps

StuXYZ 731 Practically a Master Poster

Looks like you are coping the pointer BUT not coping the array.
[This is often called weak-copy].
What happens is the memory for array1 is overwritten with something else and you have a copy of the memory location.
You need something like this

void sceneObject::setPositionMatrix(float* nPositionMatrix)
{
       if (!positionMatrix)
	  positionMatrix = new float[16];
        for(int i=0;i<16;i++)
          positionMatrix[i]=nPositionMatrix[i]; 
}

Note: You can use memcpy but the loop is self explanatory.

If postionMatrix is defined float positionMatrix[] you will not need the if
construct. If it is not you must remember to delete [] it later

midimatt commented: Explained this very well for me, Thank you +1
StuXYZ 731 Practically a Master Poster

Well having been away (sorry). But I would like to make a summary of were I think we all are.

As is my custom, it will be with examples. Now the discussion is really about scope. In C++ it is possible to have many different variables called the same thing. But the compiler will only allow one variable name per scope. Once you understand the arcane magic called scoping rules all is easy. (Although true understanding of all scoping rule requires a very very long beard ;)

So to an example. I would like to post complete programs. copy them an run them and see the stangeness on your own computer.
In this case we are going to use the variable name X to mean all the many different X I am going to produce.

#include <iostream>

class A
{
private:
  int X;
  int Y;
public:

  A(int X) : X(17),Y(X+A::X)
    { }
  void setY(int X) { Y=X; }
  int getX() const { return X; }
  int getY() const { return Y; }
};

int X=9;

int
main()
{
  int X=8;
  A xv(20);
  std::cout<<"X in class = "<<xv.getX()<<std::endl;
  std::cout<<"Y in class = "<<xv.getY()<<std::endl;
  xv.setY(455);
  std::cout<<"Y in class= "<<xv.getY()<<std::endl;
  std::cout<<"X = "<<X<<std::endl;
  std::cout<<"X (globally) = "<<::X<<std::endl;
}

Well I had better have a go an explaining the mess. First off
let us look at class A. It has a class variable X.
I have complicated the thing by calling the constructor with a local method variable …

StuXYZ 731 Practically a Master Poster

The problem here is that g++ knows that only 64 bit can effectively be handled at the processor level. So the authors/steering committee have decided that if long int (which is 8 bytes long) is insufficient then you should be using the gmp (gnu multiple precision library).

Since this is a prerequisite to compile gcc/g++ (well, you can avoid it but it is more work than downloading and compiling gmp). You are likely to have it. If not then http://gmplib.org/ (this site also has the manuals).

It is very easy to use:

#include <iostream>
#include <gmpxx.h>

int main()
{
  mpz_class a,b,c;
  a="4567890237498712303247829734";
  b="4356789023749871231827348234";
  c=567423;
  std::cout<<"A = "<<a*b*c<<std::endl;
}

Then use g++ testProg.cpp -lgmpxx -lgmp to test it

Note that you use a string to initialize if you initialization is very very big.

You can compare / use it in conjunction with int etc. Note that you need to use a suitable get_xx function to convert back to int. You can check the number is suitable for the conversion as well.

Anyway if you get stuck post a bit of code and I hope we can help. If it is open source (and much of the astronomy code is -- then just the link will do)

mrboolf commented: Useful pointer :-) +2
StuXYZ 731 Practically a Master Poster

You haven't looked at the messages at the top of the forum.

You haven't looked at google.

You haven't actually done any reading.

You haven't read the forum rules.

Therefore:

I haven't decided to post any examples/links or other help until you show some effort.

Salem commented: Good +24
StuXYZ 731 Practically a Master Poster

Sorry but your errors include : else {player = 'O' && num++;} And that is equivilent to

player = ('O' && num);
num++;

That means that player == 1 or 0, and both of those are interesting ascii characters to print :)

hope that helps.

Overall, laying out the code cleanly will greatly reduce errors like this.

Salem commented: Nice catch +24
StuXYZ 731 Practically a Master Poster

Given the HUGE size increase, if you have a calculation that can be done out to a large number, then the iterator route is best, (calculating the next on the fly). However, I haven't needed that by n=4 the quantum mech path calculation is (a) decaying to nothing (b) getting very inaccurate [numerically] (c) getting to take a very very long time.

mrboolf commented: This is giving me much to think to - iterators and such :-) +2
StuXYZ 731 Practically a Master Poster

First of all thanks for posting something that isn't a homework question :) [or at least doesn't read like one].

Secondly, I assume that you are writing this to do something. So I am guessing to how you want to use them.

Next: I have used partitions in real code, but I never store them, I use them as iterators. I want a begin() and end(), so that I can do the correct path integral in a loop. Yes your code can do that but it is a bit of a drag to store all that memory. Having said that it isn't a big problem

The most important thing is to sort the list. In a normal QM path integral 1+1+1+1 is normally much bigger than 4. So it is possible to calculate the first few in the set and ignore the remaining ones. The ordering is normally problem specific.

Algorithmically, you can do you construction loop by recursion, or just by counting up. It is easier (I think). That way the previous solutions on the vector can all be used, and just copied in.

Finally, return const references from both getPartition and getPartitions..

Overall thanks for the post.

mrboolf commented: thank you for the interesting reply +2
StuXYZ 731 Practically a Master Poster

Your problem is the overloading of the instance of number.

Let me illustrate.

int num=6;
{
   int num;      // This num is not the same as above
   num=7;
}
// In this scope 
cout<<"num =="<<num;

In your case you have put void definenum(int num) {} and this has produced a new local variable (called num) and it does nothing with it.

you could write

void definenum(const int X) 
{
    num=X;
}

Then that should work as intended.

Hope this helps. If not please feel free to repost / or ask different questions.

Murtan commented: nice, simple, straightforward +1
StuXYZ 731 Practically a Master Poster

I guess you want to write this

def vocabtest():
    for value in testwords:
        print "What word does the following definition correspond with?"
        print value
        answer = raw_input("> ")
        if (answer == testwords[value]):
          print "Correct!"
        else:
          print "No the answer is ",testwords[value]
SoulMazer commented: Perfect answer. +1
StuXYZ 731 Practically a Master Poster

Sorry but I am going to disagree with Freaky_Chris for the second time in two days! I hope he realizes the I agree with him most of the time :)

Anyway, you MAJOR sin is to think that reading into a class which may or may-not allocate memory will work. Let us take an example:

class X
{
   int * array;
};

Now the size of class is undetermined. You don't know when the size will change. So NEVER do a binary read into a class/struct unless you have absolute certainty about the size. Practically that means no pointers to memory, no STL object (e.g. vector or string) since these reserve an unknown amount of memory, no classes with static objects.

In your case you read from User. And look it has std::string. And wait, std::string often uses reference counting and static members, so that you corrupt memory is no surprise.

Your best bet is to read each item one by one. e.g.

void write(std::ostream& OutS)  const
{
    OutS<<username<<std::endl;
    OutS<<password<<std::endl;
    OutS<<verified<<std::endl;
    return;
}

void
User::read(std::istream& Input)
{
    Input.getline(username,'\n');
    Input.getline(password,'\n');
    Input>>isVerified;
    return;
}

That will actually give you LESS bytes of output than a binary dump.

p.s. you had better add some error checking to the read method, and you could implement some operator<< and operator>> methods if you like.

[Note: To the experts: I know you can do the binary writing and reading but that is because you know exactly how to do …

Freaky_Chris commented: Hehe, agree with me when you have a reason. I' self taught so i lack alot of knowledge and college takes alot of time of my ability o read around. I always appreciate extra material to read +1
StuXYZ 731 Practically a Master Poster

This is easy.... Count
If you get below zero then you have failed,
and if you get not-zero at the end you have failed.
You might want to check scope bridges. I.e.
icode}[/icode] which I would pass as fail.
but that is easy to modify the code below to include.

Example of pseudo code for JUST ( and ).

string A = "(expession) with ) ( ";
int b(0);
for(int i=0;i<A.length();i++)
 {
   if (A[i]=='(') b++;
   if (A[i]==')') 
     {
       b--;
       if (b<0) failed();
     }
} 

if (b!=0) failed();
success();

Additionally, I am sorry BUT you cannot use boolean values as suggested by freaky_chris since
the expression ((x+y)) would fail. And that is not acceptable.

StuXYZ 731 Practically a Master Poster

You haven't posted enough to figure thst out certainly.
My guess is that x and/or bestP are double/float etc and you are committing the cardinal sin of using == with floating point numbers.

I am guessing that x is very very close to bestP but that one is held in a register. The printf causes x to be dropped out of the register onto a memory location (i.e from 80 bit to 64 bit) and then == returns true. It should also work with any other complex command.

If this is the case, please read my post in http://www.daniweb.com/forums/thread160698.html

If not, please post a little more code including the definitions of the variables. Maybe make a short test case.

p.s. Please use preview post to get the [ code ] sections correct.

StuXYZ 731 Practically a Master Poster

I am going to comment on the maths/computing interface.

You have two problems here, first is that although mathematically correct, the formula [tex]\frac{-b\pm\sqrt{b^2 - 4ac}}{ 2a}[/tex] is is awful as a computational base, since, as you partially discovered, if a or c are very small you get junk.

So you set
q=-\frac{1}{2}(b+sgn(b)\sqrt{b^2-4ac} )
and the roots are q/a and c/q. (sgn is the 1 if b>0 and -1 if b<0)

Note: additionally you need to check the condition that
b^2-4ac\ge0 or do the calculation in the complex plane.

Additionally, this still holds if the coefficients (a,b,c) are themselves complex or quaternions. (the condition is different).

There are many numerical discussions in scientific literature on
(a) approximating this (to speed up the calc at the cost of accuracy)

(b) the issue of machine accuracy. google scholar is helpful, but a membership of the ACM digital library is also going to help [and it is expensive].

(c) Numerical Recipes for X, have a discussion in chapter 5. http://www.nrbook.com/a/bookcpdf.php Note: I have given the link to the free to download pdf of the 2nd edition. You pay money for the third editions and NEVER put NR code in production code, as it is rarely robust.

p.s. I am not a proper mathematician. So if you talk to a REAL mathematician he/she will complain at my imprecision.

vmanes commented: Good comments on the math +7
StuXYZ 731 Practically a Master Poster

Please read the posting FAQ. Then try again AFTER cutting down this junk to a small testable sub-program that shows the same errors.

Also I am not answering post that put "Please help as soon as possible , as i have to complete the project". It is your assignment and your problem.

Finally, describe the problem AND things you have tried. (e.g. after googling your error message, you will see 500 suggestions (all the same)).

[While you are at it -- google about the physics you are describing so badly.]

mrboolf commented: good advice :) +2
Salem commented: Absolutely! +23
StuXYZ 731 Practically a Master Poster

But can you inform me why that worked now? I want to be able to understand what im writing instead of copy and pasting. Thanks!

Ok, well you have gone up in my estimation. So let me see what I can do to answer the question. [feel free to ask for clarifications/questions]

The C++ standard says that you cannot jump over an initialization statement (implicit or explicit). [ISO C++ 2003 6.7]

Interestingly, this means you cannot write

// This code will fail to compile
goto label;
int a=4;       // NOT OK.
int x;            // OK 
label:
int b=10;
// .. more stuff

The switch statement is such a code block (effectively). As I understand the reason, it is because the case points are actually effective labels. The worst example of that I have seen is Duff's device. It is on line everywhere and it is in the C++ book (as a question!!). . But is uses a do { } while block with case statements within the do while!.

This is a start on a long road of strangeness. C++ has a strong tension between compiler writers / low-level access / high order coding. It is places like this that it comes to the fore.

Salem commented: reps for analysis, and mentioning Duff :) +23
StuXYZ 731 Practically a Master Poster

You have missed that you could have 2 aces e.g.
AAK45 would be 21 but you will not score it as such.

So ADD 10 if you have an ace. Since you can't have two. as AA+ 20 == 22.
e.g. lines 42-46 become

if ((dHand < 12) && (Ace == true))
{
 dHand += 10;
}

Notice you have also made the beginners error of writing ace=true which is always true and sets ace to true. But any modern compiler gives warnings about that.

StuXYZ 731 Practically a Master Poster

I think a little care in needed here. Poster #4 suggested making a heap object of A. [new A(5)] but that is maybe not what you want. It adds a level of complexity that might not be needed. You have to delete ob in B's destructor and manage the memory carefully in the copy constructor.

So what about

class A
{
  private: 
    int value;
  public: 
    A(int);        // constructor taking a value
};

class B
{
   private:
       A obj;
  public:
     B();           // Default Constructor
};

A::A(int v) : value(v)
{}

B::B() : Obj(5)
{}


int
main()
{
  A ob(8);
  B bItem;
}

That way you have a A object in each B, and it goes out of scope on with with the corresponding B object.

It you want to pass parameters to B from A, try this.

class B 
{
 private:
       A obj;
       A secondObj;
  public:
     B(int,int);           // Constructor
};

B::B(int a,int b) : 
   Obj(a),SecondObj(b)

int
main()
{
   B bItem(3,4);       // Make Obj(3) and secondObj(4)
}
mrboolf commented: you're right, it's probably better in this case. thanks for pointing it out +1
StuXYZ 731 Practically a Master Poster

Ok. There are two problems with this.

First, you cannot declare variables within the outer scope of a switch statement. Hence lines 16 and 19 are illegal.
Second you have declared "enumerator" both at 16/19 (a local copy)
and at line 6. So you need

enum daysinweek em;
	switch(whatday)
	{
	case 0:
	  em=monday;
	  break;
	case 1:
	  em=tuesday;
	  break;
	}
	cout<<em;

I have used em, instead of enumerator, and this way em is in scope
for the cout<<em line.

Hope this helps.

CPPRULZ commented: helpful +1
StuXYZ 731 Practically a Master Poster

Hi,

There is a tiny bit of a trick to doing this. Basically, you need to get enough memory for the characters AND enough memory for a pointers to it.

This assumes that both the 501 and 41 in your example are effectively variables that are only known at run time.
So

int m(501);   // obviously this can be set elsewhere
int n(41);      
...

char *tmpC=new char[m*n];
char **OutPtr=new char*[m];
 for (int i=0;i<m;i++)
    OutPtr[i]=tmpC + (i*n);

Now just use OutPtr. (or return it from a function).

Obviously, I had better give the delete method.
it is just

delete [] *OutPtr;
delete [] OutPtr;

Hope that helps.

Salem commented: Nice way, #2 +23
StuXYZ 731 Practically a Master Poster

First off I am going to deal with the minor errors. The the major problem.

Number of minor errors:

(A) Only constructors take the ":" assignment . Error in line 18 in
destructor. It should read ~BinaryNode() {delete left; delete right;} (B) Maybe delete line Compare compare . Use it as a direct functor if (node == NULL || Compare()(key, node->key)) Major:

This code is unlikely to behave as expected. If you put say in keys
3,5,1 then when it inserts a new node, it does no re-attach the
existing items to the tree. (as well as not working, this is a memory leak)

Additionally, I feel that you are being let down by your compiler. It is not reporting useful error messages. It really helps to have another compiler sometime (e.g. gcc) [likewise if you use gcc most of the time, something like Portland or IBM etc].

Finally, it is strange to include the .cpp file in the .h file. That is because you want to use the header without including all the code. If you need a template instance, then sometimes it needs to be done
but not all the time.

I look forward to the next installment :)

StuXYZ 731 Practically a Master Poster

Ok the problem, that doesn't actually occur until you try to create a version of the BinaryNode (from BinarySearchTree) is that you have written:

BinaryNode(Key k, T i) : data(i), Key(k)

Note that Key is now a type [From Line 6].

You need to use key. Or please use a different word. (I like "key" for
your key name that is fine but the word "Key" as the template typename does not convey the sense of type)

Additionally, please use the references uniformly, for example if you have a key (say a string) by not having BinaryNode take a reference,
there is additional coping. Although, some compilers will help you on the optimization pass.

Hope this helps.