StuXYZ 731 Practically a Master Poster

Your errors are dominated by overflow. These kind of functions are normally computed in a logorithmic maniford, not the real number manifold.

Consider: pow(x,254) almost always in overflow for most of your x range.
pow(M_E,-x) at underflow for most of your x range

Those two can be combined: exp( log(x)*256-x), that reduces the over/under flow, and obviously doing the whole problem in the log space reduces it still further.

Your range from x to 100000 is going to do that unless you convert the integration to a log basis, if you calculated log_chi_cdf, you should be ok -- then just convert at the end

StuXYZ 731 Practically a Master Poster

There are several things I would like to add : ( stuff I would mark you down on (or more likely I would give extra credit for) ).

First off, there is not such thing as a guarenteed zero float. If you write this

float div(float A,float B)
   {
     if (B==0)
       {
          // do stuff
       }
     else
       {
          return A/B;
       }
   }

You have some problems, first off is that very often it is possible to get NEARLY zero, (depending on your system), you are going to get small rounding errors at the 1e-38 level, they are NOT zero. You also have the problem, what happens when (consider that float max is 1e38), you divide say 1e30/1e-20, you now have a number that has overflowed. (or the reverse 1e-20/1e30 goes to zero.) How you handle it is up to you, but something telling me what you expect to happen is good. [even a comment -- e.g. // over/underflows are user reponsibilty]

Then you do something very strange, you input int s but pass floats (by implicit conversion) to divide. Why not pass int s and then allow float to convert, that way you will have a robust zero test. E.g

 float div(int a,int b)
   {
      if (b==0)
        {
          std::cerr<<"Division by zero is forbidden in this program"<<std::endl;
          return 0;
        }
      return static_cast<float>(a)/static_cast<float>(b);
   }

Note the use of static_cast<float> to convert the ints to float. If you don't and you do just a/b you will find stuff like 6/7 …

StuXYZ 731 Practically a Master Poster

I think that you have a few problems with this, but please put all of the code into a single code block and we can all compile and check it -- given how difficult I am finding the new coding highlighting system, I can full understand you making the mistake you made formating your code.

I have noticed the following:

Your constructor Planet(string); has an infinite loop in it as some_planet is not converted into NewPlant except in the first pass.

However, somewhere along the way, you have missed sight of the object orientated part:

You don't have a planet class set up like this:

class Planet
  {
   private:
    const std::string Name;
    const float conv_mass;
   public:
     // other stuff
    float weight(const float EarthWeight) const { return conv_mass*EarthWeight; } 

  };

Note what has happened there: object knows about its own mass, you don't need to do a whole lot of looking up for each question each time, you would use it like this:

int main()
  {
     Planet UR("Uranus");

     std::cout<<"My weight on Uranus == "<<UR.weight(72.0)<<std::endl;
     std::cout<<"My dogs weight      == "<<UR.weight(8.0)<<std::endl;
  }

The trick/pattern here is to define/set conv_mass in the constructor.

StuXYZ 731 Practically a Master Poster

That has to be the worst error message I have ever seen !!! -- I mean I had no idea when I looked at it. Fortunately, I don't use visual C++ and got a this (from clang++)

test.cpp:7:12: error: default initialization of an object of const type
      'const int'
const int  numItems 8

Hopefully, that is enough to tell you the problem. But just in case it isn't: you have created a variable numItems but you have forgotten to initialize it in a c++ way. Try either this:

const int  numItems(8);      // this works [note the ; at the end] 
const int  numSalesP=10;     // this also works.

Beyond that it compiles. Obviously I don't have the file sales.dat and it core-dumps on the line while(!feof(salesFile)) because salesFile is zero and there was not test, but maybe that doesn't matter.

Hope that helps.

StuXYZ 731 Practically a Master Poster

This doesn't look too difficult, there are going to be several ways to do this:

SPOILER ALERT ---- the following works on SOME machines [not all I think].

You only have to change CAPACITY in an instance of Volkswagen and that simply means, reinterpreting the pointer to something that allow it to changed. e.g.

int main(int argc, char* argv[]) {
 
  Volkswagen vw;  
  int* A=reinterpret_cast<int*>(&vw);
  while( *A != 5) { A++; }
  *A=200;    // well more than 20 anyway.
  for (int i = 0; i < 20; i++) 
    vw.add(Clown());
  vw.done();
  return 0;
}

If you had set the capacity to zero, it would have proved slightly more difficult. Standard debugging would have found it (set it to 1234567 and see were it was), and then use the offset etc.

The problem is that you haven't effectively blocked this route, and forced me to use the route via the poor synchronization lock on the system. . But that is a slightly more interesting challenge.

StuXYZ 731 Practically a Master Poster

There a a few things that are a bit ugly about this code, and likely to be a source of error. [otherwise not a bad attempt]

The first is that you are using char board[70][20] then you are using
stuff like

void display(char board[][20], char newBoard[][20], int size, int z)
{
   if (z == 0)
     {
	for (int x = 0; x < 20; x++)
	  { 
	    for (int y = 0; y < 70; y++)
	      {
		cout << board[y][x];
     	      }
	    cout << endl;
	   }
	}
/....

Look you are passing size BUT not using it. If size was 100 or 20, what difference would it make. So either (a) defined two global constant variables e.g.

const unsigned int XSize(20);
const unsigned int YSize(70);
/// ....
char board[XSize][YSize];
///....
void display(char BB[XSize][YSize]) { //... }

or you can do something like this:
void display(const char** BB,const unsigned int XS,const unsigned YS)
{ /... }

I think that you should just pass a board to display either the newBoard or the Board. The flag is unnecessary .

Next, you then update newBoard and you do this

for (int y = 0; y < 70; y++)
   {	  
     newBoard[y][x] = board[y][x];
     //count neighbors
     if (newBoard[y-1][x-1] == 'X') nCount += 1;
     //.... 
     if (newBoard[y+1][x+1] == 'X') nCount += 1;
//...

three problems:

(i) if y == 0 and y-1 is.... -1 which is actually a very big number, therefore you get undeterminable result.

(ii) …

StuXYZ 731 Practically a Master Poster

Actually, I would much prefer that you wrote line 19/20 as:

std::vector<CBoard *> Board;
std::vector<CPlayers *> Players;

because what is the point of having namespaces and then just importing everything.

Also putting using namespace std; in at header file!!! Somewhere later, you are just going to import that into your code and make a complete mess because you will have then polluted the global namespace will all of std without knowing it. Errors like that take for ever to debug.

Secondly, you are using pointers in a vector, that is not a problem (assuming you are careful), but you do not have a constructor, copy constructor or an assignment operator. All three are auto generated by the compiler, and the last two are 99.9% likely to be very very wrong and will cause your code to crash in very unexpected ways.

thines01 commented: Solid advice +12
StuXYZ 731 Practically a Master Poster

This is hardly a C++ question, it is maths. Anyway, obviously you have made the transform (x,y>0)
[tex]lcm(x,y)=\frac{x y}{gcd(x,y)}[/tex]

That allows you to create a quadratic equation in gcd(x,y), that gives you what you the condition on gcd. That immediately excludes solutions for a large set of a,b,c. [fractional and imaginary solutions are disallowed]. For those that do have solution, then you have one of two conditions to forefill, and that gives you only one iteration variable as x conditions y.

Note, that for a,b,c < 1e6 brute force is an appropriate tool as well (well just, it order 1e12 calculations and that is a bit difficult).

StuXYZ 731 Practically a Master Poster

We are not mind readers: no code, no help because there is no way to help.

compsci91 commented: Manners -1
StuXYZ 731 Practically a Master Poster

Take my previous post, take the code and fill in the comments with real code.

Read the words of the error message OUT-LOUD. I am serious, then you will see that you have a reference to a method that is not defined.

consider this code:

void testFunc();

int main()
{
   testFunc();
}

Now make that work, i.e. compile AND RUN. That is your error in a nutshell..

StuXYZ 731 Practically a Master Poster

What does it say: it says that there is no poly::poly(). So were is your

poly::poly() : // maybe stuff here...
{
   // maybe stuff here 
}

While you are at it, fix the other errors and repost the working code.

StuXYZ 731 Practically a Master Poster

Come on lets us play guess the error message!!!! WHAT DOES YOUR ERROR MESSAGE SAY ?????

I get undefined reference to `poly::poly() so were is your constructor [for a start]

StuXYZ 731 Practically a Master Poster

Please post a whole working program. If I can't compile it and run it, it makes it difficult to help.

The operator+ part, it doesn't work and we can fix that after we fix the setCoefficient part, the constructors, assignment operator and the output method.

The set coeff might work as it is for some inputs, but is missing a test of size and the possibility to resize the vector.

Note that : SIZE()=exponent; will not work since SIZE() is a function that returns a value. It is the equivalent to writing 10=exponent; (which obviously wont work). You don't need it I think but I am guessing.

StuXYZ 731 Practically a Master Poster

Let us look at that untested code! -- Please get something to build and test otherwise you will get nowhere. -- The smallest possible successful program is were to start.

Anyway: Consider what your code does:

First you pass two values, the index (exponent) and the coefficient value. Good.

Second, you try to resize a vector to size exponent using the construct. That can only be done as a constructor (e.g. in the poly constructor) so doesn't work, you wanted coefficientVector.resize(exponent); .

Next having reserved exponent spaces you promptly set the exponent+1 space to something... remember vectors and arrays in c++ start from 0.

Then you set the size to exponent.

All of that logic is wrong as well, as shown by the example :

// set poly x^3-2x 
poly A;
A.setCoefficient(3,1.0);
A.setCoefficient(1,-2.0);
// Oh dear A has size 1
std::cout<<A.getSize()<<std::endl;

As you see you should only resize if the exponent is bigger than size.

So
(a) compile your code.
(b) write very small parts before compiling -- it makes it easier.
(c) check your logic on paper -- it really helps
(d) try to get something to work, the minimal program it doesn't need to do much
-- don't be afraid to use dummy functions e.g.

poly poly::opertaor+(const poly& rtSide) const
{ 
    // dummy return until I get round to writing this function:
   std::cerr<<"Warning : incomplete function"<<std::endl;
   return poly(*this);
}

(e) slowly add features keeping …

StuXYZ 731 Practically a Master Poster

Not sure that you know what you are doing here. The main part of the program will not work at all. Simply delete it from line 2 to line 14. It is utter junk.

First off: Provide a default constructor/copy constructor / assignment operator and deletion operator. I know that the deletion operator isn't going to have anything in it but but you will most likely want something in it later.

Next: Get that working in a real compilable/runable program. Create a polynomial and copy it to anther. I know it does nothing yet but it really really helps to do it in small steps.

Next: Think about what is meant by adding one polynomial coefficient e.g. 6x^8, do you want to expand your vector to size 9, and have 8 zero coefficients, or do you want to keep track of the powers. The write a test program that works with constants in the main program. At that point you will be beginning to get a feel for how it works.

Next do : output/operator+ and operator-. They are simpler than the rest.

Then tackle the more difficult * operator. That is difficult because if you multiply say (x^3+x^2) by (x^2+2) you get a polynomial with powers 5,4,3 and 2. The increase in the number of terms is a little tricky.

StuXYZ 731 Practically a Master Poster

There are many things that are wrong. I am not figuring all of them out for you but will give some help.

(a) Consider the test case: 15X2 Expected output 3 (because 30 goes to 3)/ Actual output 1.

So what went wrong. It is in your multiplication. You don't keep any account of multiple digit number e.g. you do 1x5x2 and get 10 which is wrong.

(b) The specification says that you will need to deal with numbers up to 1e19. That doesn't fit in an integer [on most computers].

Overall your algorithm needs a re-think. Sorry.

You have to figure out a way that you can truncate the multiplication number or ignore the parts that don't matter. That can be done (for example -- there are many ways), by noting that 10 has prime factors 2 and 5.

-- Parse a result with zero in it as special
-- Remove the factors of 10 (e.g. a 2 and a 5 prime factor). You are left with a key result:
if you have a remaining factor 5, your result is 5
if not multiply all the last digits together and keeping only the last digit at each stage

The above is definitely not optimal!! It is an example that can be shown to work with very very large input.

StuXYZ 731 Practically a Master Poster

The most scary thing about the above code is the pow(double(-1),j+1) ...
please think, an alternating pattern is required.

I initial thought that it was homework help, but it is actually nicely formatted obstifacted C++. So am not sure that the code deserves the -1 reputation. :)

WaltP commented: Try Obfuscated ;) +17
StuXYZ 731 Practically a Master Poster

If that is all that you want, e.g. a sorted list, then clearly a map is not what you want. A map is basically a quick way to look something up, for example if you need
to find a number that is indexed by name, a map is an excellent option.

However, if you have a sequence, say the letters A to Z, and a number associated with that which determines an order, then you want a sequential object. So in your case, it looks like std::list or std::vector are your first two choices -- this difference really being AFTER you have sorted them, do you need to just get the letters in order, or are you going to need to get say the 12th then the 22nd etc. If it is the former then use a std::list, if not use a std::vector.

Note in your case you have two pieces of linked information, so use a list/vector of pairs of items. More generally, if you have a lot of information, e.g someones name, address etc + a score on a test and you wish to sort on the score, then use a struct/class container that information and a comparitor function [That is code that allows you to compare the class objects and uses the correct number in the class for that comparison].

StuXYZ 731 Practically a Master Poster

The map is normally implemented as a set of std::pair<key,value>. The search is then specialised to be just on the key. [Note: there is nothing in the standard that says it must be like this, just this is the common way to do it].

Therefore you can iterate over the set and place it into anything, e.g. a vector or a list. The issues are what you need to do with it afterwards. The vector has the advantage that it is random access, but has cost associated with insertion, so depending on what you want a list might be better. However, if you want to sort something, you typically, need a sequential container which map isn't.

It is also important that the sequential container that you put the map into has both the key and the value, or normally, you have no way to figure out the key again.

StuXYZ 731 Practically a Master Poster

What you are really wanting to do is create a sortable storage form from your map.
The obvious way is to just put the map into a std::vector<std::pair<double,char> and sort on the first value in the pair. Obviously, you can reverse that and sort on the second value.

As for setting, not 100% sure what you want, you certainly can do this:

void setMapFromArray(std::map<char,double>& MObj,const double* DA,const int NSize)
{
  if (NSize<=26)   // assuming that you are not going to do interesting things beyond 26 (yet) 
    {
      char A='a';
      // The map might need to be checked here to determine if it is (a) empty (b) doesn't have
      // have existing entries etc.
      for(int i=0;i<NSize;i++,A++)
        MObj.insert(std::map<char,double>::value_type(A,DA[i]));
    }
   return;
}

Obviously, you can use a typedef, and some templates if you like, or a different input form etc.

Is that enough help?? [well with the first part really] -- and can you give a little more detail on the second part please.

StuXYZ 731 Practically a Master Poster

The error that you are having problems with is the fact that Timer::elaspsed_time is a function so you need to write double t = time.elapsed_time(); The reality is you really really need to re-write this. You are using #define's with sign letter values. (a) this is C++ so use a const. (b) s and r, you are going to type that somewhere else and get into a complete mess.

Use const int colSize(10); or some such thing.

Next you use 10 and % 10 in various places in the code hence forgetting that you parameterized it.

Then we have lines like:

short (*matrix_shifted) [row]= new short [column + 1][row];

It doesn't do what you want and it doesn't get deleted so is a memory leak.

If you want to handle your own memory for a matrix, then there are two basic patterns for memory allocation:

int  **M = new int[cols];
*M=new int[rows*cols];
for(int i=0;i<cols;i++)
  M[i]=M[0]+i*rows;
// or....
int **M=new int[cols]
for(int i=0;i<cols;i++)
   M[i]=new int[rows];

(There are others but you see them a lot less often).

Finally, you use the std::queue, well if you are going to use the STL please look at boost::multi_array and std::vector, both of which can be used in this manor.

StuXYZ 731 Practically a Master Poster

One of the first real fortran program every written was about the gamma function, and in typical mathematical notation it evaluated [tex]\sum_{i=1}^{6} \frac{\gamma_i}{1+\lambda_i \tau}[/tex] ina typical math function. Unfortunately I haven't seen the original code for it. But the use if i,j,... etc is extremely common for subscript in maths notation, so given that it was mathematicians that were the originators of computing, their notation become standard were it is applicable.

However, the first fortran compile manual [IBM 704] (published in 1956), uses i as a loop variable in the very first program (finding the largest number in a set).

StuXYZ 731 Practically a Master Poster

Minor comment to the above. You said

I know that constructors go into the .h file

Fortunately, that isn't true.

A lot of beginners (with C++/C) seem to think that there is some magic about .h and .cxx or .cpp files. There isn't. The compiler just (effectively) makes a single file out of all the #include "file" and the file that is being compiled. If you like you can declare all of your classes in .cpp files and your code in .junk files, it doesn't matter, it is just a convention.

Once you are aware of that, you only have to consider that the compiler tries to have the minimum information that can allow it to compile each file to make an object file, and that it is doing in top-to-bottom. The after object files have been made, the linker needs everything.

In practice that means that if you want to specify any function of a class, you need 100% of the class's declaration, and 100% of the declaration any other classed that you want to use, but 0% of any definition.

Example:

// this Is the DECLARATION 
class A
{
   private:
      // stuff..
   public: 
      void method();
};
// THIS CODE MUST BE BELOW the declaration either in the same file or by an include:
void A::method()
{
   // do stuff
}

The example is just what you need when you compile, the includes are a quick way to help you not have to copy …

StuXYZ 731 Practically a Master Poster

Without question focus on your other interests and skills... be it sports/hobby etc.

If it is in a field outside of the typical domain of these kind of projects it automatically gets a better mark because there is an implicit effect of the marker over estimating the complexity because he/she is not so familiar with the domain.

There is also one special category, if you have good maths skills your project will automatically seem better than the coding effort put into it because of the additional complexity. E.g. it is not much effort to code up a simple electric circuit modeler , if you are comfortable with complex numbers and differential operators. The key element here is that you already have paid the cost of learning the maths skill and you are getting double payback, first of the original maths class and second for the coding project.

StuXYZ 731 Practically a Master Poster

What I find strange is the switch/case statement when you have a choice base on a simple number.

if (choice<1 || choice>maxCandidates)
  votes[choice-1]++;
else
  { 
     std::cout<<"Incorect number... Exiting"<<std::endl;
     /etc...
  }

Then the next thing that look strange is calling votes1() from votes1(). Surely
write a function getVotes() and then do the decision and processing outside that
function in another loop/control structure.

Finally, if you define optimization you have to specify what you mean, IO, CPU, size, or what I think you really mean, making the code clear.

StuXYZ 731 Practically a Master Poster

-- Can I suggest that you test your code with 10-6 which should give 4 but doesn't.

When you have fixed that problem in the obvious way, you can test

-- Then test your code with 5 2 /

This will highlight another error.

StuXYZ 731 Practically a Master Poster

Not sure how much of the answer I should give. [if it is too much help then I am sorry]. If this insufficient, please reply and let us know.

The first thing to note is that any integer number x, can be expressed as:
[tex]x=a m + r[/tex] were a and r are integer and m is your modulo number.

Then note that [tex]x^2 = (am+r)*(am+r)=a^2m^2 + 2ar m + r^2[/tex] which clearly modulo
m is just r^2.

That should be enough for you to see how to proceed.

StuXYZ 731 Practically a Master Poster

First off, the reason for your error might be better understood if we consider this piece of code:

bool function(int a,int b)
{
   bool retValue;              // Value not set!!!
   if (a==b) retValue=true;
   return retValue;
}

That is in-essence what you have done. You actually hide it a little by not putting a
return statement at the end of your code, but it is the same code. If you need to see that, take your original and ADD a line after the last statement before the } in isanagram std::cout<<"HERE"<<std::endl; and you will see that you are then going to exit the function without an explicit return statement.

As to debugger, yes you will need to learn to use one but not now. Understanding, how to put print statement (std::cout) and fundamentally looking at your code will help more.

StuXYZ 731 Practically a Master Poster

The art of programming starts when you carefully crafted code doesn't work. That is when you start trying to make your code do something, (anything), to help you understand it. Yours is a classic case.

The first thing to do is add a print statement std::cout<<"I am here"<<std::endl; . The first place to try is straight after int main() { .

Second turn on the compiler warnings, and fix 100% of them. For example it is int main() not void.

Thirdly, start printing out every variable, and figure out if you believe the value you are seeing.


Finally, on most systems you are going to get away with it, but std::cout is buffered and the buffer is flushed with the command std::cout.flush(); However, that is a lot of hassle to write after every output, so we have the stream modifier std::endl which does two things: (a) adds a line-feed (return) which is appropriate for the system, and second flushed the output. That means that it doesn't wait till the end of the program or the buffer becoming overly full to output the text to the screen or file. In this case, were the program is hanging that might be something to think about.

StuXYZ 731 Practically a Master Poster

The error is in the function isanagrams. If you turn on the warnings on the compiler.
[No I don't know how to do it on Visual studio.] You will see that you are told that
fro that funciton: warning: control reaches end of non-void function.

The problem is that the value is the undefined, so you many get a true even if the strcmp(a,b) is not equal to 0.

Try changing the conditional to this: return (strcmp(a,b)==0); Additionally, you read the dictionary words into a VERY short character array (20 characters). I made the mistake of testing the program with a typical English dictionary file, and core dumped the program, because the longest words in the english dictionary are over 20 letters long. It is often important to be very careful about reading strings directly in to character arrays without checks on the maximum number of character that are allowed to be read.

StuXYZ 731 Practically a Master Poster

Lower triangular normally means that all the element above the diagonal are zero. I would clarify that first.

You are also going to have to be very careful about near zero errors if m is any of the floating point types. e.g. is 3.12e-312 not zero.

StuXYZ 731 Practically a Master Poster

There are several errors. The biggest one is to write (X2 - mean)^2 since the ^2 does not mean power, but actually means xor.

If you want power, you have to write either pow(value,2.0) or you could of course do value*value.

Note that you don't initialize mean, and mean is declared as an integer, this is not a good idea, since the average is unlikely to be an integer. E.g. 1,1,2,2 the average is 1.5

Sol1 is actually your average (as you calculated it)

StuXYZ 731 Practically a Master Poster

A word of caution because from the question, I think that you don't fully grasp what is going to happen [if I am wrong then apologies].

Your code says this:

class fileSys{
public:
  Filesys(Pdisk& disk);
private:
   Pdisk disk;
};

And that implies that you are going to write the constructor something like this:

Filesys::Filesys(Pdisk& P) : 
  disk(P) 
{}

OR

Filesys::Filesys(Pdisk& P) 
{
   disk=P;
}

I suspect from the error that you have, you wrote the second. That way TWO thinks are going to happen that you don't want.

First, you are using the compiler generated copy constructor and compiler generated assignment operator, HOWEVER you are using a class Pdisk that is not a POD [Plain old data] class (because it contains std::string which has memory management within it). Thus you are going to get strange, difficult to repeat runtime errors.

Second, you are constructing Pdisk by using a default constructor (which you have now to give) and then coping the data in. Very inefficient.

The rule of thumb is: unless you are certain that the compilers default constructor, assigment operator, copy constructor and destructor are exactly what you want write them explicitly. i.e. your class declaration should look like this:

class Pdisk
{
  // stuff...
  public:
    Pdisk(const std::string&,int,int);
    Pdisk(const Pdisk&);
    Pdisk& operator=(const Pdisk&);
    ~Pdisk();
  // more stuff....
};

If you have 1% doubt, write them. If something strange happens when using the class and you haven't written them, write them and then …

StuXYZ 731 Practically a Master Poster

Several problems exist.

First if you reference an array out of bounds you are going to get a mess.

Consider your code:

for (int i=0;i<V;i++)
    {
      for (int j=0;j<H;j++)
	{
	  ne=0;
	  if ( A[i][j-1]=='*' ) { ne+= 1; }
// .....

What happens as j is zero?? Similarly what happens when i is V-1 or j is H-1. You are then accessing unknown memory locations.


The solution to your problem is the define char A to be char A[V+2][H+2]; . Then set the boundary to be dead and then work from 1 to V and 1 to H.


Next Error:

You update the map on a cell by cell basis. The game is normally set out in a form by which the state of the game at a point in time is used to calculated the change, and then the whole change is implemented at once across the whole map. This can be easily carried out by having two arrays and switching between them each move.

StuXYZ 731 Practically a Master Poster

Caut baia correctly points out the error (I believe) but I would like to point out that
you seem to have missed the use of PI.

You declare a const double PI to be 3.1419 and then don't use it. In the line x=4.0 * 3.1419 * pow (r, 2); why not write x=4*PI*pow(r,2); . That way if you have to change PI to something else e.g. a more accurate representation then it is only changed in one place in the code.

Additionally, I guess you know that r*r is the same as pow(r,2) [and sometimes depending on compiler options, quicker and more accurate]

StuXYZ 731 Practically a Master Poster

First off given your question statement,

To Code: rand7() which generates randomly distributed no. from 1-5

you can do this: ;)

int rand7() {  return rand5(); }

Ok I guess that isn't your question, you actually want to return rand7 where the result is 1-7.

First thing to establish is if rand5() returns an integer value or a floating point number in the rand 1-5. If it is integer you can try this:

Quicker in the long run is to use a reduction algorithm. E.g create the number

//
while(a>20) {
  a=(rand5()-1)*5+(rand5()-1);
}
return 1+a/7;

The issue is is it quicker than adding 7 numbers (and seven calls to rand5()). It can be slower, but most of the time it is quicker.

If on the other hand you have 1.0->5.0 you can actually use the same algorithms, but in that case there is the much quicker approach of just dividing the result, however, this approach looses low bit accuracy.

StuXYZ 731 Practically a Master Poster

Your problem is (simplified) this:

for (int i = 0; i < numStudents; i++)
{
  Student student;
  student.fName="fred";
  sNames.push_back(student);    // Copy the current version to sNames
 
  // Do stuff with student ... doesn't matter what.   
   
  // student goes out of scope
}

The problem is the push_back uses a copy constructor to copy the state of the object to the vector. It does not mean that it is tied to the object. If you did this

Student A;
A.fName="fred";
sNames.push_back(A);
A.fName="john";
sNames.push_back(A);

// sNames would be of size 2, and have two Student objects, one called fred and the other called john.

In direct answer to the question:

There are many ways to write out a vector. Here are two examples which do not use a functional method. [You have used both loops and iterators in you code, hence my choice]:

for(size_t i=0;i<sNames.size();i++)
  {
    std::cout<<"Item "<<i<<"=="<<sNames[i].fName<<endl;
  }
// or
std::vector<Student>::const_iterator iter;
for(iter=sNames.begin();iter!=sNames.end();iter++)
  {
    std::cout<<"Item =="<<iter->fName<<endl;
  }

Hope this helps.

StuXYZ 731 Practically a Master Poster

I have a nice little bit of OLD code that I use to count the number of bits, and I have adapted the idea. [Note I didn't write the original idea of using 0333 and 0111, but I do not know who did].

unsigned int uCount = MyInt
    - ((MyInt >> 1) & 033333333333)
    - ((MyInt >> 2) & 011111111111);
  
   result=(uCount & 1);

It is about 3 times quicker on my computer. As with all of these things please benchmark it yourself, with your compiler and your optimizations flags etc.

The principle of the code is that it is clustering each number into little triplets of bits and the & 0333 and & 0111 part just keep the triplets isolated.

The double subtraction effectively sum the number of bits in a triple, by binary residual.

The & 1 at the end carries out the xor part of your code.

StuXYZ 731 Practically a Master Poster

The problem is that you are passing the string in the wrong order. Consider just
the string "10-5". What you are doing is finding the first non-digit and setting that
to operator so you loop through doing running_sum-=10 Then you ignore the last number:

What you need is a quick read of the first number and put it into the running_number,
and then find the operator etc

StuXYZ 731 Practically a Master Poster

There is nothing intrinsically wrong with your code. i.e. in a stand alone test env. it works.

The error you are getting comes from your library matrixOptLibrary.h. There are any number of reasons that this code is going to break it. (a) the using namespace std; ,
and more likely (b) that your typedef is in a include file and it is not in a namespace, and it is above an #include "matrixOptLibrary.h".

If you can post a small complete test code that produces the error, we will have another look. Otherwise pay particular attention to your .h files, particularly if you also have #include lines in them.

StuXYZ 731 Practically a Master Poster

Unfortunately, there is still lots wrong with this. It would also have helped if you had just posted your code, nobody does (or should) run executables from unknown sources.

Now to the code itself..... I am going to list a number of types of errors, but only one of each type (as I classify it, so it is very arbitrary ;)

void genDigs(int base,char *digs)
{							
  if(base<10)
    {
      digs=NULL;
      return;
  }
//....

The error here is that setting digs to null has zero effect. If you had done this *digs ='c'; , then it would have had an effect.
Reason that you still have this error: You did not turn on warnings in your compiler.
(or pay attention to them).

std::string 
toNorm(int *num,int digNum,int base)
{ 
  std::string Num;      //String variable for keeping final form of number
  char *digs=new(std::nothrow) char;      //An array for keeping digits in given base
  genDigs(base,digs);
  if (digs)
//....

you allocate ONE character, but then use digs as a multiple character array.
Either (a) allocate sufficient characters, (b) use an expandable storage, e.g. std::string. (c) make getDigs allocate the space.

You specifically use the nothrow new, and test digs AFTER using it!!!!

You use variables called num and Num, that is one small mistype away from a difficult error, and it is close to impossible to read easily. Think about your variable naming!

for(int i=0;i<digNum;++i)
   {
     if(num[i]<10)	
       Num+=num[i]+'0';
      else
        Num+=digs[num[i]-10];     
   }

The code above is what you wrote, consider …

StuXYZ 731 Practically a Master Poster

Sorry, but regardless of the errors in your code you have the wrong algorithm.

You seem to have assumed that you can translate directly from base 10 decimal numbers, you cant. Eg. Consider 49. That would be written IL. however, your code
would produce XL1X.

So I would suggest that you have a go at creating another algorithm. Try it out on paper first, that will greatly help when you come to coding it up.

StuXYZ 731 Practically a Master Poster

I will comment, that your programming AND your math need to be strong to do a masters. I believe that you can effectively trade between ability in them. Extremely good math, and ok programming will work as well. If I have to select between two candidates I have a tendency to go for stronger math. [Note there is a minimum in both areas that you are going to need].

Finally, (a) never do a masters in an area that you feel is uninteresting. Unknown is ok, spend a few days going over papers in the field before accepting. (b) the interaction with your supervisor and to some extent his/her group is important, you don't have to like your supervisor [doesn't harm] but you have to be able to respect him/her, and he/she has to have enough time to do those things that help you, be that dealing with the bureaucratic stuff, getting money, helping you write up papers, or actually helping you avoid dead ends, and particularly structuring scope.

I can't really comment on what industry needs, basically, in a couple of years time, I don't think I can predict with any certainty what is required in my field, so the whole scope of industry seems impossible. Personally, I recruit primarily on ability, not specialization in the field.

StuXYZ 731 Practically a Master Poster

Not a bad effort, however, your comments suggest that you would like some feedback...
So here are a few things that I have noticed.

First off, I don't like seeing using namespace std; anywhere, but NEVER in a header.

In function BToDec, you do this:

int *num=new int;         // This only allocatts ONE integer

fromNorm(baseNum,base,num);         // This uses num as if it is an array of size dependent
                                    // on the string baseNum. 

// ... other stuff.
delete [] num;   // definately wrong

This error is repeated throughout

Additionally, in that function you do this:

int Num; 
for(int i=n;i>0;--i)
  Num+=num[n-i]*(unsigned long int)pow(base,i-1);

Several problems with just those three lines. First you take the trouble to convert the result of pow() to an unsigned long int only to add it to a value that is only an int.
Obviously not really a good idea.
Surely the power etc could be avoided with code like this:

int Num(0); 
for(int i=0;i<n;i++)
  {
     Num*=base;
     Num+=num[i];
  }

Also you know how to use references, so get into the habit of using them, time and time again you just pass large objects by value (e.g. strings etc).

Also fromNorm just needs a re-write. What happens if base is less than 10?? e.g in line char *digs=new char[base-10]; Anyway it is good that you are trying to write an extended piece. Writing numerical code, both efficiently and robustly, is extremely taxing and will significantly improve you coding …

StuXYZ 731 Practically a Master Poster

The main problem is that you have no idea what is going on because you have not put print statements std::cout<<"I am here"<<std::endl; in your code.

Next you have a character string that you call string. You actually pass the pointer to the first character. In a typical c-style character string the last character is zero.

Now how do you access those characters, that you have to do by addressing it by one of several methods: Let us do a quick summary:

You can use array addressing, e.g.

char* Str="this is some string";
std::cout<<"The  fourth letter is : "<<Str[3]<<std::endl;

Note that arrays are offset from zero, so Str[3] refers to the forth character.

you might decide to access them by doing a pointer offset. See that Str [in the example above] points to the first character in the string. To see that you can do this:

char* Str="this is some string";
std::cout<<"The  first letter is : "<<*Str<<std::endl;
std::cout<<"The memory location of that letter is : "<<Str<<std::endl;

Not that the * operator is used [it is not multiply here... another confusing issue sorry], to indicate that the contents of the memory location are required.

Therefore you can do this:

char* Str="this is some string";
std::cout<<"The  forth letter is : "<<*(Str+3)<<std::endl;
std::cout<<"The memory location of that letter is : "<<Str+3<<std::endl;

So you have, effectively moved 4 characters further on, which is effectively the forth character.

Now, in your loop you take the address …

StuXYZ 731 Practically a Master Poster

First off I agree with Mike, but I will also add that after a while, the C++ aspect of the programming language becomes almost second nature. I will be struggling with the maths, [ that somehow never becomes second nature :( ] and with the main design, or the likely runtime or memory problems, but the language takes a second place -- often I am not even aware which language I am programming in. [Yes I have put bits of C++ into a the middle of f90 method -- the compiler reminded me to get more coffee before coding.]

StuXYZ 731 Practically a Master Poster

I am surprised reading this, I would have thought most of you knew the +2,+4 rule --
but it hasn't come up, just the old +2 rule.

Assuming that you are not going to use the memory that the typical sieve methods use, or the complexity of the more you can extend the idea that you increment the test by +2 to +2,+4 as below.

bool isPrime2(unsigned int& number)
{
  if (number > 3) 
    {
      if (number % 2 == 0) return false;
      if (number % 3 == 0) return false;
      const int MAX = (int)sqrt(number) + 1;
      int i=5;
      while(i<MAX)
	{
	  if ( (number % i) == 0) return false;
	  i+=2;
	  if ( (number % i) == 0) return false;
	  i+=4;
	}
    }
  else if (number<2) 
    {
      return false;
    }
  return true;    
}

The code as given is about 45% quicker than the simple +2 system. However, there are many other ways of doing things.

The next obvious extension is sometimes called the wheel factorization , e.g. http://primes.utm.edu/ That reference has lots of other algorithms as well.

StuXYZ 731 Practically a Master Poster

If you are just after the centre and the shape is convex then, what about just taking the average if you do

Point C(0,0)

// sum over points:
for(int i=0;i<Number_of_Points;i++)
  C+= shapePoint[i];

// divide by the number added up:
C/=Nubmer_of_Points;

(Point is just a simple x,y class. You can equally do it with a struct Point { double x,y; }; , and just add to x and y. )

That gives you a centre of mass, that will be in the shape if the shape is convex.

[note you might have to deal with floating point coordinates after the division. Then you will have to either accept them or if you need integer, then test the four possible roundings (e.g 3.3,4.3) test (3,4), (4,4), (4,5) and (3,5). Even then that might fail. [But in that case there will be no solution]].

StuXYZ 731 Practically a Master Poster

This kind of question is designed to show you that a loop for all the numbers N=1 to N=LOTS [because the answer is big!], is not the way! Even if you got your div function you work, you could easily be spending a long time waiting for it to work.

[Note to teachers: don't set that as 1-20 since that is far too quick on todays hardware but 1-25 would be a better set, just doable in typical long int sizes [64bit] but not in int, and takes sufficient long but not stupidly long time that someone doing a brute force approach will not be able to do it]

To give you a large hint, a very similar question on a 1970's maths paper I saw as a kid. [Sorry I am old!!!]. Note that was before electronic calculators!! You need to think about primes and prime factors. For example, since the solution must divide by 7, and as 7 is prime, you only need to consider multiples of 7.

From that you should be able to figure out how to do it.

p.s. I have no idea what ull means, just delete it. You seem to have grabbed a C function from somewhere and dropped it into your C++ program.

StuXYZ 731 Practically a Master Poster

I am going to ask about firstPerson's code here. So first some initial thoughts, first I always like to separate output from function, i.e. don't do logic/maths in the same place as you are telling the user what happens or what is wanted. Especially, as often initially you develop going onto the terminal, and later into a GUI or some logging system.

That tells me that int getLevel(const char); look like the correct prototype and use -ve or 0 as a error code. Alternatively, int getDefLevel(const char,const int); , and the second integer is the default level if nothing/junk is entered.


Second I have two comments + a question about firstPerson's code:

int getDifficultyLevel(const char *msg)
{
  const std::string difMap = "EAH";

  // Doesn't this just set ans to zero ???? 
  char ans = 0;        

  // This should have been done outside of the call
  cout << msg;              

  // this returns std::string::npos+1 :
  return difMap.find( toupper(ans) ) + 1; 
}

The first is I don't really think that msg should be a char* but much rather a std::string& since we are using them already.

Second doesn't ans have to come from the calling function?

Finally, [the real reason for posting].

So I cannot decide if I am certain that std::string::npos+1 is ALWAYS equal to zero. Obviously, the method find, returns std::string::npos if there is not match to the find. I found that std::string::npos is beyond the maximum number of characters in a …