StuXYZ 731 Practically a Master Poster

First off the error that you have made is that in C++

void print(char*);
void print();  

are two different functions/methods.

Thus you HAVE NOT defined a print() method in class IVM.
You defined some weird function called void print(IVP* iv) and that is not void print()

That is why the program does not call it.

Second, the huge number of errors/warning from using istream, cstdlib and cstring etc in the include are because the compiler is trying to help you write better code.

I strongly suggest that you get a copy of gcc. Code your assignments in that and it will help a lot more. (gcc is free). If you are sticking with windows there are several other free compilers as well, but gcc is so universal and very very picky about writing to the standard. (something that university professors can get very mark happy about!)

StuXYZ 731 Practically a Master Poster

The short answer is yes, BUT it does not do the obvious thing.

Let me explain a bit. It is the same as:
(assumes that matrix[][] is of type char.)

bool X=  (matrix[1][1]==matrix[2][2]);

bool Ans  = (matrix[0][0] == static_cast<char>(X))

Note that it is VERY unlikely that is what you really want since bool
will only give you char(0) or char(1).

Also that you are using matrix[][] is completely unimportant e.g.

int a(5),b(5),c(5);
if (a==b==c)
  {
     std::cout<<"This is never written"<<std::endl;
  }
else
   {
      std::cout<<"Surprised??"<<std::endl;
   }

hope that helps.

p.s. you need to do (matrix[0][0]==matrix[1][1]) && (matrix[1][1]==matrix[2][2])

StuXYZ 731 Practically a Master Poster

First off I want to second MosaicFuneral's comment it really depends.

BUT consider even your example of basketball. A simple point centre model is easy, however, you might now want spin (angular momentum/friction coupling etc) so that when the ball hits the hoop/backboard it bounces realistically.

One thing I have found, is that your initial model/program is then required to go the the next step. If you had the basic maths, you would have easily predicted both that and air resistance, and put the ability to modify the physics model to handle that. If not then it is a code re-write for you...

A similar problem also exists in knowing what is difficult and what is easy. For example, you suddenly want a battleship game. Not a problem, same physics, but air resistance dominates!! [Particularly if you go from super-to-subsonic], and angle of impact is paramount. It is also nice to know that if resistance is proportional to velocity then it is analytic. The correction go on and on. The problem normally determines the level of approximation required.

In summary, I think that there is a class of interesting computer problems that are being done more and more by people with good maths skills. There seems to be hundreds and hundreds of computer people out there but the difficult to recruit people are the people who actually understand the problem. A Phd in maths goes in the call to interview pile regardless of programming ability, and …

StuXYZ 731 Practically a Master Poster

I think that vector methods, cross/dot product etc. Polynomial intersections (Bezout matrix methods etc) for 3d-surface-3d-surface intersections rate as minimally essential. Trigonometry is just a given. If you can't handle basic quaternions and vectors don't even think about 3d games.

There are all the specialist discrete numerics stuff for approximations etc. [not my field].

And then we have functional calculus, statistics and matrix theory, not your obvious requirement for 3d games but the one of the underlying basis for the AI.

There never seems any bad maths to learn. Every time I have understood some new maths, I seem to suddenly keep running into it and using it.

I also want to say that if you can do trig, really do trig, understand how the integrals work (e.g. solid angle calcs) and understand the identities work and the basic expansion and transforms (taylor etc. fourier / lorentz etc) [Yes, mathematica will do if for you BUT if you don't understand the basics it is almost impossible to use well].

StuXYZ 731 Practically a Master Poster

In comment to ddanbe:

Yes I fully agree BUT I can (just about) remember learning 6502 assembler because I too wanted (a) crack the Elite (a game) protection system [they locked each block on the tape!] (b) to do the split mode screen display. In that process I learnt about indirect references and lots of stuff that made C an easy language to learn.

So who am I to say that your code is worthless.

N.B. 6502 is a 1Mhz 8 bit processor with 3 registers.

StuXYZ 731 Practically a Master Poster

Hi

Well, I am not going to comment on the purpose of the code. It does make me very very glad I don't use windows for anything (including work).

So things that I would pick you up on if you worked for me. .

The first problem is for a c++ example there are no user defined classes. That really shows were the problem lie in understanding.

Second : Comments!!!!! -- What this problem is doing functionally is not documented. Yes you wrote it for yourself, but please consider what happens in ten years time.

Third: Too much work is done in main, that would be better in a function. Along with global variable that really don't need to be.

Forth: Way to little use of clear constants. Particularly directory names etc could be in const string block at the top, or in a namespace. (Just one place to look for it)

Fifth: strcpy(startup, exePath.c_str()); why bother, you only use this once and then you could have put
exePath.c_str() ?? [If you HAD to have an array of MAX_PATH then add a comment. ]

Sixth: Very inconsistent use of lines like d=d+"ab"; and d+= Seventh: Consider

else if(!exe.is_open()) 
{
    exe.close();  // how do you close something that is not open?
    return(-1);
}

well that is a summary of things that quickly come to mind.
I STRONGLY recommend that you use a much more open spacing for your …

StuXYZ 731 Practically a Master Poster

First off I would like to apologies about my previous post.
I mistakenly thought that gettimeofday was more accurate than clock.
It is not. Sorry. Both are similar accuracy.

CLK_TCK is the old Posix-1998 standard but is included in <ctime> and the posix standards since 2000 say that CLOCK_PER_SEC is required to be 1000000 (1million).

Second I have done a little research and found the following. On Linux there is a nano-second accurate clock. [It is not actually THAT accurate but it is tied into the machine tick rate]. However, it seem that it is as good as you are going to get.

On Windows, there are a number of ugly assembler hacks (compiler dependent) [But they have the advantage of being quicker to execute than the Linux call.] And a number of functions (from windows.h) that do the same thing

Linux solution:

#include <iostream>
#include <iomanip>
#include <time.h>

int main()
{
  int sum(0);
  timespec ts,te;
  clock_gettime(CLOCK_REALTIME,&ts);

 // Your stuff here (my example is about the minimum you can do)
  sum+=1;

  clock_gettime(CLOCK_REALTIME,&te);
  double TVal=1e9*(te.tv_sec-ts.tv_sec);
  TVal+=te.tv_nsec-ts.tv_nsec;
  std::cout<<"Time out (nanosec)== "<<TVal<<std::endl;
}

Some care is needed. You need to like to librt. i.e. g++ test.cpp -lrt .
Note also that you want to keep the optimization off since it actually can remove the sum+=1 part. (even if you add a use below!!). For your example, since it is doing real work that isn't a problem. However at the nano-sec resolution, calls to clock_gettime are …

StuXYZ 731 Practically a Master Poster

Your real problem is either (a) the resolution of your clock.
(b) that the insertion runs in a different thread.

You are likely to find that CLK_TCK is a very big number. i.e there are very very few CLK_TCK per second. On my computer there are only 200 per second.

So: There are two ways out. (a) Insert lots and lots and lots.
(b) Get a better clock.

Linux solution is easy: (this may work on windows but I have no way to test that.)

#include <sys/time.h>

struct timeval clockInit;
struct timeval clockNext;


gettimeofday(&clockInit,NULL);
 
// Your stuff here

I.insertion(A,200000);

// My stuff here
gettimeofday(&clockNext,NULL);
  
double tval=clockNext.tv_sec-clockInit.tv_sec+
  (clockNext.tv_usec-clockInit.tv_usec)/1e6;
 
std::cout<<"Time Taken == "<<tval<<std::endl;

hope that helps

p.s. If you still get zero, turn off the optimizer to see if you can get some resolution.

p.p.s. I think that your insertion command actually inserts the value 200000.

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

PLEASE READ THE POSTS ABOVE

THAT MEANS DO NOT POST CODE UNLESS IT IS IN code BLOCKS.

Your code works fine. BUT you have the wrong g++ line (since -O is
optimize) and you really wanted -o.

Otherwise you will have to post your output and you code in CODE blocks.

StuXYZ 731 Practically a Master Poster

I wish to (a) reinforce Chris's comment you have posted 18 and should have figured that out.


Use the advanced button and enclose you code. Use the # button.

Solution to the problem is that you missed out a : on the definition line
properties

General Note:

I believe that this forum needs a "how to debug problems" thread with the basics of how to split a problem down, how to get the compiler to work for you, rather than against you etc. The stuff that I seem to have to explain to the novices time and time again,
[particularly those that have come from interpreted languages -- because the mind set is different.]

StuXYZ 731 Practically a Master Poster

It seems you like adventures:

The rabbit hole can get deeper :)

template<typename T>
T 
convert(const std::string& SRef)
{
  T x;
  std::istringstream ostr(SRef);
  ostr>>x;
  return x;
}

template<typename T>
struct Type
{
    Type() {}  // THIS DOES not set types that don't have default constructor
    Type(T n):value(n){}
    operator T&() { return value; }
    operator const T&() const { return value; }
    Type& operator=(const char* p) 
      {
        value = convert<T>(std::string(p));
        return *this;
     }
    Type& operator=(const std::string& s) 
      {
        *this = convert<T>(s);
        return *this;
    }
    T value;
};

int main()
{
  Type<int> foo;
  Type<double> dfoo;
  foo = "123";
  dfoo="3.141";
  std::cout << foo <<" "<<dfoo<< std::endl;
  std::string s("2009");
  foo = s;
  std::cout << foo << std::endl;
  foo += 1;
  std::cout << foo << std::endl;
  int k;
  k = foo = 1000;
  std::cout << foo << '\t' << k << std::endl;
  return 0;
}

Note that I have used Ancient Dragon's convert function (For real code please add some checks!!!)

In short this post shows how templates can be your best friend (and your worst enemy).

StuXYZ 731 Practically a Master Poster

As cikara pointed out, you are incorrectly using trys!=b and that is going to get you into a mess.

I would (a) suggest that you use a count of the zeros to decide if you have succeeded. (b) Have a look at your algorithm. (c) check the rules of since you are not checking that the square (3x3) only contains 9 unique digits.

The algorithm is going to get stuck. THEN you have no way to back track ( ie suppose that you have put 1 in game[0][0] but that turns out to be incorrect then how do you replace that with a 2 if putting a 1 does not violate the problem.).

In your code, game is ok to be global, but solver should work with its own copy. Then the starting values can be set to allow iteration progression.

However, the algorithm is awful, especially as you scale to larger sudoku (4x4, 5x5 ..., 3x3x3 etc). Even for 3x3 you have on average about [TEX]10^{30}[/TEX] options (based on typically, 55 open positions)

However, if you try to keep a possible list for each square, then a series of simple rules will fill a large amount of the grid in (or reduce the search list. (and the determination of ring depends will allow you to prove that the problem has multiple solutions.)

StuXYZ 731 Practically a Master Poster

Hi,

If you are doing cards for any general card game, which makes use of suit, then you will benefit greatly from using a 64 bit card system. Then each bit refers to one card (with three left over).

That way in instances where suit doesn't matter it is easy to combine (e.g.

int rankedCards = (Cards.clubs | Cards.diamonds |
	      Cards.hearts | Cards.spades );

and you have set up the cards using a union.

struct SuitGrp
{
  unsigned int clubs : 13;
  unsigned int       : 3;
  unsigned int diamonds : 13;
  unsigned int       : 3;
  unsigned int hearts : 13;
  unsigned int       : 3;
  unsigned int spades : 13;
  unsigned int       : 3;
};

union BinCard
{
  uint64 Hand;    // uint64 is an unsigned 64 bit int (use a typedef)
  SuitGrp SG;
};

With this structure you can combine/sort/compare with much more ease than with a plan 52 count system.

Note the use of the : construct to define the length. This only works if the base type is longer than the number given. (in my case int is 2 bytes (16 bits) so that is ok.).

Hope this helps.

StuXYZ 731 Practically a Master Poster

Hi, operator++(int) and operator++() are the post and pre increment signatures respectively.

Note that the (int) in the post-increment does not get assigned or used
i.e. you might write

class A
{
  public:

   A& operator++(int) 
     { 
      // do stuff here; 
      return *this;
     }
};

Note: You do not need to return a reference to the class, you can return anything you want.

Can I strongly recommend getting a basic c++ book (see the FAQ on this section).

StuXYZ 731 Practically a Master Poster

A long long int (signed/unsigned) is 8 bytes. cout<<sizeof(long long)

Sorry I think I have made a mistake. I only have 64 machines so I get 8 byte. (by default). It you want 8 byte on a 32 bit x86 machine you will need the correct option on your configure line when you build gcc.

The quick way then is to use the gmp.

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

Hi k59,

Sorry, I understand that google can be used but these are the practice problems on daniweb's C++ forum. So I feel an answer should be forthcoming! -- i.e. they are not homework questions!

So this is what the questions ask and what I think you will learn from doing them. Please feel free to post your attempts for comment! I think MosaicFuneral has just got a little jaded of people asking "can you do my homework for me".

Factorial:

This is a simple mathematical problem to multiply all the number up to the value given e.g. factorial(4) == 24 because 1*2*3*4 = 24, It is normal to write 4! to mean 4 factorial. so the first few are

1! == 1
2! == 2
3! == 6
4! == 24
5! == 120

and so on.

Obviously this can be VERY big very fast. With C++, using an int, you are not going to get past about 35! (I can't remember -- you can find out!!)

So the problem is to write a program to calculate a factorial of a given number (e.g. typed from the keyboard).

The aim of the problem is to (a) teach loops (b) simple functions and for advanced students to teach recursion and for very very advanced students to teach when not to use recursion :) .

If you manage to do the problem (anyway), you will have progressed.
If you come back to the problem a year …

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

If it is to much to change in my code then that is all you had to say.

Well it works like this, you have posted two functions that DONT work.
I wrote a little bit about why they don't work and you don't want to try to fix them. Then you want the community to tell you how to change them to what you want!!

So it is either (a) a learning project (b) homework , (c) real production code. If it is (c) then you would be using std::list (or at least saying why you can't). If it is (a) then start by fixing what you have posted.

So don't just demand the answer you want. Enter a discussion.

StuXYZ 731 Practically a Master Poster

It is simple you fix deleteFront and insertBack, because neither work.

This looks like homework -- therefore show some effort.

If it not homework, show some pride in your work. Fix the first problems first.

StuXYZ 731 Practically a Master Poster

What you have clearly doesn't work:

Consider insertBack, you do not set first. It can be anything!

IF you had set first then conversion is easy.

newNode->link=first;

Now consider deleteFront, I do not understand what you are doing checking first->info (and what would happen if first was zero!)

So try testing these two functions with a range of input.

StuXYZ 731 Practically a Master Poster

So what is your question ??
What is a loop??

A loop is a group of statements that get called multiple times
e.g.

for(int i=0;i<10;i++)
   {
       // statements here
   }

which calls the statements 10 times
or

while(x>18)
{
   // Statements here
}

which calls the statements until x > 18. Note that if x is already
you don't get to run the statements in the loop.

There are other loop constructs, but for now: Write some code.

I would not try to do you assignment straight away, write a set of little test programs, e.g. print the number 1 to 10, then add them up.
then read a number from the keyboard etc. Post some code here, with a comment about what you can/can't understand and you will get a bit more useful feedback.

Note: We are not going to do you homework for you, but will help if you show effort.

StuXYZ 731 Practically a Master Poster

The function nCr should not be calculated using direct factorials. Very often nCr is within the MAXINT range BUT the factorials are not.
You should use the property of the factorials.

An initial optimization is to divide on the n/2 decision e.g.

long int nCr(const int n,const int r)
{
  long int result(1);
  long int dFactor(1);
  
  const int cnt((r<n/2) ? r : n-r);
  int s(n);
  for(int i=1;i<=cnt;i++)
    {
      result*=s--;
      dFactor*=i;
    }
  return result/dFactor;
}

There are a number of special cases, that should be programmed up (e.g. n/2==r). Additionally, 2,3, 5, and other prime factors can be removed from result and dFactor at intermediate points in the inner loop. With simple stuff like that you can keep nCr valid until n-r and n get very big, while int dies at 16, and long int at 20. Unsigned int gains you +1 on those numbers [Machine dependent!].

StuXYZ 731 Practically a Master Poster

Quick comment:

Top can show the total memory (although it actually sorts on CPU until you set the options )

pmap PID

Shows the total memory, including a breakdown of stack/heap memory and all the shared libraries used.

[PID :: process id (use ps to find it) It is a number ]

(Can this be moved to linux questions ??)

StuXYZ 731 Practically a Master Poster

Assuming all the other definitions are correct (e.g. defined MAX, friends etc)

The first/second problem is that tempZ is defined as an single int,
and therefore is not an array. you will need to create it as an array
e.g char tempZ[a]; to get that line to compile.

I am also guessing that you forgot that the if(t>=MAX) only refers to tempX statement and the code always reads into tempY. The in>>tempX etc. followed by reading into it.

You desperately need to write a lot less code. Say just reading in and the writing the input to the screen. Get that running and debugged then move on

StuXYZ 731 Practically a Master Poster

Try replacing the whole while loop stuff with this.

std::cout<<std::string((people+500)/1000,'*')<<std::endl;

If you don't want to use the string constructor then try...

for(int i=(people+500)/1000;i;i--)
   std::cout<<'*';
std::cout<<std::endl;
StuXYZ 731 Practically a Master Poster

Hi,

I am amazed at this code. The normal way to do a trapezium integral is simply to loop over the value like this

const int N(500);
const double startTime(0.0);
const double endTime(100.0);
double area(func(startTime)+func(endTime));
area/=2.0;
for(int i=1;i<N-1;i++) 
   {
      area+=func(i);
  }
area*=(endTime-startTime)/N;

What you are doing creating 100000 objects to do that is absolutely beyond me. However, I think you have the code mostly right ! So well done

BUT the problem is MATHEMATICALLY very ill-conditioned. I suspect that is why it was set. I guess that you will use Simpson next and then runge-kutta on the underlying differential equation. (I will comment just about ANY monotonically decreasing/increasing function is ill-conditioned under this integral method.

If you REALLY want to get the right answer with a trapiz. method then do the problem in log coordinates.

StuXYZ 731 Practically a Master Poster

Added to that ,my doubt is if we created a general template lets say for swap two value.In the main of that we created objects of in t type,float type.Will compiler treat both in compiler side implementation?

The answer to your question is yet unless you tell it to do something else!

This leads onto the other beautiful aspect of templates. You can specialize them.

Let me take an example:

Consider a polynomial class. You would have a template parameter the number of different variables (e.g. with x,y,z etc) and a template parameter for the type(double,complex,polynomial). So you define a solve method (say using Bezout matrix reduction) that works for any number of variables except one, BUT you specialize the solve for just one variable (e.g. polynomial of x, if numeric use GSL, if non-numeric expand and simplify). Then you can use the reduction in a simple recursion loop to solve your polynomial system without extra work. Effectively it doesn't matter how many polynomial variables you have.

It is easier to debug, since if it works for 1 and 2 variables it works for any. You write one class and find that it works for both double precision numbers AND algebraic constructs.

It is much easier to test a set of polynomials of double, than a set of polynomials of Legendre polynomials BUT you can rely on you code because it is templated.

Finally, when you solve something in a function language, the natural …

StuXYZ 731 Practically a Master Poster

Just commenting you can chain them together but you need: if (game[1]&game[2]&game[3])==play) BUT you get away with this because the possible values of game[] are 0,1,2. The above logic will fail if you are not using powers of 2 as the flag values.

Normally, the shorthand version I have written, gives better executions speed. Especially, since compilers are very bad at determining that game[] is binary bound. (and I also think it is almost impossible for a compiler to determine this)

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

Hi,

You have made several errors (a) mis-understanding of C++ [these are critical since they affect all further programming in the language]
(b) logic errors. They only effect this program.


I think that you have mis-understood the class encapsulation rules.
Private data is available to all members of the class as both the current and other versions of the class.

Let me give an example:

class A
{
    private:
        int x;
    public:
      void func();
      void f2(const A&);
}
       
void 
A::func()
{
    x++;   // acceptable
}

void 
A::f2(const A& Other)
{
    x+=Other.x;      // Also acceptable
}

Notice that func is able to just change x. Also f2 is able to access Other's version of x as well as its own. Note also by making Other const I have forbidden that Other's x is changed. If I make a mistake in the code logic and do change Other's x (or anything else in x) then the compiler will tell me. Important. compiler errors are many times easier to find than runtime errors. Almost anything that moves errors from runtime to compile time is worth doing.

That means that you don't need all the getTdollar etc with outputData() since it is a class member method.

If your class has a constructor / copy-constructor / assignment operators, you should nearly alway initialize everything. [Unless an expert (and even then most of the time) you should always define these three methods + the destructor explicitly

StuXYZ 731 Practically a Master Poster

Mynameisor is incorrect about point 1. But this is clean code that you have copied from the answer book. With your current pathetic knowledge HOW do you think you are going to get away with submitting it??

Where is you EFFORT? Not immediately obvious, so my effort is suddenly lacking.

StuXYZ 731 Practically a Master Poster

You have used an array structure. It sounds like you want to use a tree.
Obviously, everyone who has read Knuth [interestingly only in volume 4] :) , knows that an array can be used to represent a tree. Depending on what you want to do that might be the way forward. (Simple check down the array).

However, I think that you might need a tree. Since you look like you are going to want to use the properties of a tree more than just getting an output.

StuXYZ 731 Practically a Master Poster

First off, if you want some constructive feedback my immediate question is why, (a) you are learning C++/programming for fun and decided to write some code and want to have some feed back.
(b) you are taking a class and this is to be marked, and you are hoping to improve it. (c) other...

Actually both (a) and (b) and maybe (c) are good. But it causes a difference in what I say about the code.

First off:

Is there anything that is c++ in it other than the std::cout/cin ?
There are no classes / use of the stl, etc.
If you are starting with C and moving up not a problem, for a c++ class, not so good.

Layout.... Arrh!!!!! -- That is not good.

Beyond that shuffle stands out as awful. It will not result in particularly random cards.

There are a number of exit(1) lines. This is a bit ungraceful.

The conditional breaks are very very difficult to follow. I think that is were you need to code round your logic. [I mean the if (condition) break; that litter the code.]


For this kind of task, my next step would be to write a simple command parser, so that games could be played simultaniously.
(I don't mean across computers, but command could be simple letters to start a game eg.

play B       // play blackjack
B b 50       // bet 50 …
StuXYZ 731 Practically a Master Poster

Well you are pushing back an integer and j is zero and that is interesting :). It does work on my linux machine.

Additionally, if j gets bigger than 255 things can go badly wrong as well.

Both of these behaviour points are implementation specific. (I think)

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, please please look at boost::multi_array or similar structures.
This is were the vector formalism really doesn't do anyone any favors.
http://www.boost.org/doc/libs/1_37_0/libs/multi_array/doc/index.html

Next row can only have a vector<vector<string> > pushed back to it. col is a vector<std::string>. So that doesnt work.
You seem to be using it as a vector<vector<string> > so I would write

vector<vector<string> > vec;

  char Uletters[]="ABCDE";
  char Lletters[]="abcde";
  for (int i = 0; i < 3; i++) 
    {
      vec.push_back(vector<string>());
      for(int j = 0; j < 5; j++)
        {
	  vec[i].push_back("Item");
	  vec[i][j]+=Uletters[i];
	  vec[i][j]+=Lletters[j];
	}
    }
  for(unsigned int i=0;i<vec.size();i++)
    for(unsigned int j=0;j<vec[i].size();j++)
       cout<<"Vec "<<i<<" "<<j<<" == "<<vec[i][j]<<endl;

Note that you take the size of an indexed vector item in the loop vec[i] Finally, if you really want a 3D array (or tensor) then not a problem, the code extends to this.

vector<vector<vector<string> > > vec;

  char Uletters[]="ABCDE";
  char Lletters[]="abcde";
  for (int i = 0; i < 3; i++) 
    {
      vec.push_back(vector<vector<string> >());
      for(int j=0;j<2;j++)
        {
	  vec[i].push_back(vector<string>());
	  for(int k = 0; k < 5; k++)
	    {
	      vec[i][j].push_back("Item");
	      vec[i][j][k]+=Uletters[i];
	      vec[i][j][k]+=Lletters[j];
	      vec[i][j][k]+=Lletters[k];
	    }
	}
    }
  for(unsigned int i=0;i<vec.size();i++)
    for(unsigned int j=0;j<vec[i].size();j++)
      for(unsigned int k=0;k<vec[i][j].size();k++)
	std::cout<<"Vec "<<i<<" "<<j<<" "<<k<<" == "<<vec[i][j][k]<<std::endl;

Bit ugly but that is what you get for using such a construct.
See the boost or one of the many tensor classes available should you wish to change it. (The main advantage of this is that the tensor can be completely ragged e.g. the second row can have 6 items and the third …

StuXYZ 731 Practically a Master Poster

If that solves your problem, please mark the thread as solved.
(You can always start a new one with a different problem).

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

First off: and most important
Fatsbear please read the first announcement in this forum about code tags. Then use them.

Second: The problem is the association between calories and the food name.

You will find other posts, by your classmates I suspect, who have solved the problem by sorting on calories and then making the same moves on the foodname. This is an ugly solution. Especially, if you then have more information to associate, e.g. the price, the age .

Your best solution is to associate the food name with the calories in a class. Create an array/vector of you food class and sort the group as a whole.

The idea of a 2d array is simply not the way forward. It doesn't represent the underlying problem structure and in very difficult to extend.

Overload the operator< or use a comparison function and use the
standard sort algorithm, or write you own.

Finally, bubble sort is one of the worst sorts available and should never be used (except some very rare cases). It is simply too slow.
Despite JLopeman's careful minimization of the loop passes, on a long random list it is still horrifically slow.

Anyway, you should write some code and post that for comment/problem solving.

StuXYZ 731 Practically a Master Poster

Can I just suggest the boost filesystem code.
If you follow the link, you will see that the first thing in the tutorial
is how to find a file. The big advantage is it is operating system independent.

http://www.boost.org/doc/libs/1_31_0/libs/filesystem/doc/index.htm#tutorial

StuXYZ 731 Practically a Master Poster

Just in case you forgot. You can easily append to the end of the file.
Use

std::string input="Hello at the end";
std::ofstream File("file1.txt",std::ios::app);
File<<input<<<std::endl;        // This is written at the end of the file.

Obviously, if you don't want to change the original, you need to make a copy, but often a simple system command will do that for you, without having to worry about writing a loop/reading/writing etc.

StuXYZ 731 Practically a Master Poster

I am glad that solved the problem.

The best thing to do is mark this thread as solved.
Then ask the question again in a new thread.

(I am really not the person to answer your questions, at lunch at work, my group were trying to figure out how many hours we had used each OS, I got to 50 for all MS systems in total, compared to 15000 for Linux. I have had a cushy life :) )

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

All the above posters are completely correct. You really can't size arrays like that.

BUT -- Please before you go any further, write down on paper your algorithm. i.e. what is going to happen. The work it through on paper.
You then play the routine on paper with the short limits, ie a deck of cards with only four cards, say AKQJ and one suit. It will make your life a lot easier on the long run.

The you will see:

You have fundamental mistakes. e.g. If player 1 gets the Ace-spades, what stops players 2 getting the same card! (or player 1 getting it again).

Bubblesort -- apart from ultra-specialized instances should NEVER be used it is so slow.

If you took the trouble to write a class Card, with an bool operator<(const Card&) const , you could then use the std sort from #include <algorithm> . Or you could use a priority_queue object for each player.

[There is a single queue version of this game, which gets the same result (the score) -- but a little more care is needed with counters.
It is more efficient than multiple queues if nearly the whole deck is used.]

Finally, there are several threads on creating decks of random cards e.g. http://www.daniweb.com/forums/thread159174.html, were you can read ArkM's brutally short method of shuffling a deck. [Note, I gave him reputation and I am referencing his post !! He can't complain about …

StuXYZ 731 Practically a Master Poster

Well obviously I write stuff which is incomprehensible! :(

You need

x_coord[i]=xcoord[i-1]+...

(or the way you have the loop backwards, you need i+1.)

If you had used a point class, then you would have easily been able to take the dot product and seen that the angles between your points are incorrect.

Since Salmen's reference is to a stub page in wikipedia I am leaving the page from mathematica/wolfram. It is much more descriptive.

http://mathworld.wolfram.com/Polyhex.html

The best way to tackle the problem is to write a point class... (see earlier post) and remove duplicates and then inner points.

Further help when you show a bit more careful effort and some level of actually having read any of the references.