StuXYZ 731 Practically a Master Poster

You have made mistakes in the code to do the largest AND smallest.
First off, consider the test case of a user inputting ONE number only.
Let us say that number is 10.

Then your code will report that correctly for the largest BUT report 0 for the smallest. The problem here is that you have assumed that the largest and smallest number cannot occur together. Same problem exists if you enter 3,5,10.

Second issue is that you start with the smallest number equal to zero. That is obviously a mistake. There are (easy) two ways round that (a) set smallest to be the biggest possible integer, (b) use a flag.

Let me show your how to to the latter.

// Note that i is acting both as the loop variable and the flag
for(int i=0;i<UserInput;i++)
  {
     if (!i || smallest>number)
       smallest=number;
  }

Yes it adds an extra test. That is sometimes a problem.

StuXYZ 731 Practically a Master Poster

Not surprising because of a tiny bug in your loop: You wrote: for( int inte = 1; inte = 1; ) { } Now a for loop has four parts, first an initializer, that goes from the first open bracket to the semi-colon. Second a conditional, that goes between the first and second semi colon, Next is post iteration statement, that goes after the second semi-colon. Finally there is the loop block that goes between the two braces { }.

The loop is done this way.
(a) Carry out whatever is in the initialization statement
(b) Test the conditional.
-- If the conditional is FALSE : leave the loop block -- Do nothing more.
-- if the conditional is TRUE : continue to (c)
(c) Execute the loop block.
(d) Execute the loop iteration statement
(e) goto (b).

So in your case:
(a) you create an integer inte. Then it is set to 1.
(b) Determine that inte=1 is TRUE. That is because ALL integer assignments of any value other than 0 are true.
(c) execute loop block
(d) Nothing to do
(e) Go to (b)

Thus you can never get out of your loop. That is why 34/35 dont get run.

Also please please call your variables something slightly more descriptive, using inte, integ intege is asking to make a typo and cause piles of difficulty finding the bug.

StuXYZ 731 Practically a Master Poster

There are several very worring things to think about.

The first is the delete [] pixels_index that happens on line 58 of your original code and line 261 of the update. That line gets called a lot of times if I am not mistaken, but you only create pixels_index once. To test it, put a std::cout<<"this is called only once "<<std::endl; and make sure I am wrong.

Second, the goto refresh command, that is going to produces a huge stack, at each time, you are getting an extra loop. You should loop over the flush ONLY while there are events on the queue, then you should stop.

Other than that I can't see anything, hopefully, that is the problem or someone else can see what is wrong...

StuXYZ 731 Practically a Master Poster

Just coming back to the assignment of a value. I think this is a little verbose and confusing:

if(rand() % 2 == 0) {value = -1;}
else {value = 1;}

Can we use the mathematical property that you can linearly map any number set to any other smaller/equally sized number set, and in this case : value= 2*(rand() % 2)-1; The advantage is to avoid the conditional, and that avoids a lot of cpu time.
[Actually : with full optimization, g++ converts this to equivalent code, however, that is not what happens in a two conditional case.]

This kind of construction comes up a lot, it is important to know it because you will see it in other peoples code, and when you decide that you want to modify it to give your values between -6 and 8, it is easy to change, were as the if construction is not. E.g. value=(rand()%15)-6; Sorry for the interjection but with three layers of loop, you have saved yourself a layer of confusion. [at the cost of a slightly more complex construction]
So in short, fix your nearest neighbour sum first.

StuXYZ 731 Practically a Master Poster

Sorry, you haven't given us enough code here...

We need to know what w, w_temp, h_temp get assigned to and how. If you can, post the
fragment of code that they are set in as well please.

I guess the you almost certainly have made a memory error with the indexes e.g. by overwriting global_index when it comes to the last value because of the +2 etc.

The other thing I am thinking of is that you have not initialized one of those variables?

StuXYZ 731 Practically a Master Poster

Ok, sorry, I got 4,5,6 etc from being lazy and not wanting to type.

If you want to save yourself the typing ...
From line 29 to 36 of your second version of the code, you could replace it with this:

const double arrayData[]={24,21,43,24,43,31,41,42,34,41,45};

for(int i=0;i<SIZE;i++)
  calc.Data[i]=arrayData[i];

Note, that line 25 of your code has no purpose and should be deleted.

Otherwize a good effort.

StuXYZ 731 Practically a Master Poster

Well done!! I don't think I have seen this error before!!

What you have done is this: calc.Data[SIZE]=(24,21,43,24,43,31,41,42,34,41,45); That is your error... You have use round bracket e.g. ( ). That is not what you wanted. So let us see what happens.

You first evaluate the contents of the bracket. e.g. 24,etc. using the comma operator, that simple means that it evaluates to 45. Then you set calc.Data to 45. But since that is over the limit of the array boundary, [recall, arrays are indexed from 0 to SIZE-1] you in effect have a completely uninitialized array, and because of your structure, you set mean to be 45.

However, if it was a simple array you, could write this double arrayData[]={4,5,6,7,8}; But this is not allowed for the struct. Therefore, the quickest thing to do is to change the first loop to this:

const double arrayData[]={4,6,7,8,9,91};
for(int i=0;i<SIZE;i++)
{ 
   calc.Data[i]=arrayData[i];
   sum+=calc.Data[i];
}
StuXYZ 731 Practically a Master Poster

The strangest thing that you have done here is recode your reduce function with a different algorithm. So let us consider the first algorithm: You implemented (with errors on the variables, the GCD algorithm using the Euclidian method. That can simple be put as this: The gcd(a,0) == a and gcd(a,b) == gcd(b, a % b)
So given two numbers a, b, you find the biggest and

FrAction reduce()
{
a=num;
b=det;
while (i = (a % b))
{

// Check on size needed here:
a = b;
b = i;

}
std::cout"Greatest common divisor is "<<b<<std::endl;

So you should be able to test this and finish the reduce method.

StuXYZ 731 Practically a Master Poster

Well first off, this is good. Insert functions correctly, i.e. does indeed double the memory. It also copies (as far as I have tested) and sorts everything out.

However, there is a subtle bug in erase that may hurt. You can get a memory violation.
In your shift of moving elements down from the higher part of the array:

for(int i=pos;i<mySize;i++)
  myArray[i]=myArray[i+1];

However, you are going to access memory that is outside of the allocated memory, e.g. i+1 == mySize. That is very unlikely to cause problems with a simple type like int, but for something like a real class that is going to cause problems.

So change the code to

for(int i=pos+1;i<mySize;i++)
  myArray[i-1]=myArray[i];

Why does operator= return a const List& surely you don't want a const return type ?

insert should be void insert(const elementType&,const int); , consider if elementType is an expensive to copy object.

You have no check for maxSize==0 or maxSize<0 (since you are using an int not a unsigned int.)

Give that you are dealing with List etc, that is part of the std namespace, would it be better not to use "using namespace std;" and instead use the using std;:cout; etc or just put std::cout in your code ?

Finally, you understand that there are several improvements that are possible. (a) it is insert and copy in the loop, so to improve the situation when you resize. (b) allow the memory block that is active …

StuXYZ 731 Practically a Master Poster

Well I don't think this is going to be that welcome, so I sorry.

First off I am not 100% you understand why you want to encapsulate something in a class. In this case, you want a fraction type, that behaves as if it is a standard type, e.g. a double etc.

So first consider those variables that are common to all methods of the class and represent the state of the class object. In this case there are only really two, the numerator and denominator. Therefore these are the only two variables that should be in your class definition. e.g.

class Fraction
{
  private:
    int num;
    int den;
  public:
};

Now those variables are global to the class, and specific for each instance of the class you make. e.g. Fraction A(3,4), B(7,8); , if you call a method, e.g. B.add_display(), then in the method there are two variable num, den with values 7 and 8, but if you call A.add_display() the variables are 3 and 4. In particular you do not need to either explicitly redefine then or get them.

ALL other variables required for methods of the class, can be declared locally to the method. We have a code review saying at work, "constness, locality, type generality". Ignoring the last for this post, locality is where a variable is defined in the deepest scope possible to do its work, i.e. if you are swapping two variables, define the temp copy variable within the loop.

StuXYZ 731 Practically a Master Poster

Ok first off, welcome to daniweb, and thank you for writing a clear post with code blocks and not-too much and not too little code!

Ok to your problem, you have unfortunately made a couple of logic errors. First, consider your loop, for(int c=2;c<= num;c++) . This will test each possible factor up and including the number itself. If this was the only error, ALL of your test numbers [except 2] would be reported as not-prime.

Now, let us consider the inner part of the loop, numPrime is set true each and every time round the loop. Then it is set if a factor is found. BUT then it is tested, and regardless if it is either true/false you execute a break statement. Therefore,you only test if the number divides by 2. No other numbers. You can see this if you add a line cout<<"Test number c == "<<c<<endl; as the first instruction of the loop.

So to remedy you could do something like this

numPrime=true;
for(int c=2;c<num;c++)
   {
     if (num % c == 0) 
       {
          numPrime=false;
          break;
       }
   }

  if (numPrime == true) 
    std::cout<<"Number prime"<<std::endl;
  else
    std::cout<<"Number not prime"<<std::endl;

Some simple improvements that will help, you only need to test up to the square root
of the number, since if a*b=N^2 and a=N+x and b=N+y where x, y and >=0 then
a*b== N^2 + N(x+y) +xy. Which can only hold if x,y==0.

StuXYZ 731 Practically a Master Poster

The error is because this is a definition of a class. You have then put initialization code in it which is not going to work.

You could do something like this:

class box
    {
    public:
        int x;
        int y;
        XMMATRIX  world;
        ConstantBuffer cb;
 
        // constructor
        box(int a, int b)  : x(a),y(b) 
         { cb.mWorld=XMMatrixTranspose(world); }

    };

Here I have added the cb.mWorld to your constructor. You might have to think about if this makes sense in your context, and what to do about the assigment operator, and the copy constructor.

StuXYZ 731 Practically a Master Poster

First off please use code tags.

Second, actually, this is quite a common and slightly difficult problem, and is 100% down to how numbers are represented on a computer.

First off float is an inaccurate number, it cannot represent even simple number, like 0.2 without some rounding error, that is because it is a set of binary values, e.g. to represent say 0.25 , we say that the number (in binary) is 001 and there are two shifts of the decimal point, e.g. the number read from RIGHT to LEFT: units, 1/2, 1/4, 1/8 etc... However there is no non-infinite sequence that represents many simple decimals, e.g. 0.2. [This is a gross simplification, see e.g. http://en.wikipedia.org/wiki/IEEE_754-2008 ]

The code you gave does this: total = (A-B)*100; where A and B are floating point numbers. Then you multiply but 100. What you have done in increase the error by a factor 100. [Note in binary that is a shift of over 6 bits.]

Then you have the other problem, you convert your floating point number to an integer like this : int I=A; . Now what is important is now that this simple cuts off all the decimal part, e.g. 2.999999 is converted to 2.

Then you say you got it working with the new code, actually, you just reduced the error and got luckier. The code you have is STILL in error, just that there are LESS cases. You will get errors for …

StuXYZ 731 Practically a Master Poster

Your problem is the equals sign (=) in your sort function.
You cannot e.g. this allows

Edge1 A(0,0,1);
Edge1 B(0,0,1); 

// This should not be true to use the algorithm sort.
sortFunction(&A,&B) == sortFunction(&B,&A)

Also please use a managed point with vectors, e.g. boost::shared_ptr.

tommyz4 commented: Good help. +0
StuXYZ 731 Practically a Master Poster

In which case you cannot do this. Let us break this problem down some more, if you do this :

class A { 
  protected: 
    int var;
};

class B{
  public:
    void func(A& obj) { obj.var=10.0; } // THIS IS not possible 
};

So in class B, you cannot change the private/protected variables of object A. The only way is if class A (or a derived class) gives you access to the variables.
If you have derived classes D1, and D2 (from A) and you CANNOT change A, then you can make classes D1 and D2 inherit from another class BD, which has the virtual public function that allows you to change the protected variable in A. E.g

Original code:
class A { protected: int X; };
class D1 : public A { };
class D2 : public A { };

New code:

class A { protected: int X; };  // We can't touch this
class BA : public A { public : void changeX() { x=20; } };
class D1 : public BA { };
class D2 : public BA  { };

class something { public: void modify(BA* optr) { optr->changeX(); } };

int main()
{
  D1 obj1;
  somthing Sobj;
  Sobj.modify(&obj1);
}

Sorry for simplify your example but it was getting too long winded. Hope this is clear.

StuXYZ 731 Practically a Master Poster

So you can't add a virtual function to the base class??
Then your only decision is to make BaseClass completely abstract, i.e a standalone instance is disallowed, or not. If you don't then think about adding the functionality to say class absFunc, which is inherited by BaseClass, then you get compile time check that you are not setting a parameter that cant be set.

Example of virtual function

#include <iostream>
class BaseClass
{
public:
  // IF BaseClass is abstract do this:
  // virtual void setParameter(const double) =0; 
  // BUT it is not [in your example] , so do this:
  virtual void setParameter(const double) {}   // You could put an exception/error etc here.
};

class DerivedClass : public BaseClass
{
  double P1;
public:
  virtual void setParameter(const double D) 
    {
      std::cout<<"P1 Set:"<<D<<std::endl; 
      P1=D;
    }
};

class SecondDerivedClass : public BaseClass
{
double PX;
public:
  virtual void setParameter(const double D) 
  { PX=4.0*D; std::cout<<"PX Set"<<PX<<std::endl;}
};

class AnotherClass {
public:
void setParameterOfDerivedClass( BaseClass * baseClass, double parameterValue )
  {
    std::cout<<"called ptr"<<std::endl;
    if (baseClass)
      baseClass->setParameter(parameterValue);
  }
  
void setParameterOfDerivedClass(BaseClass& baseClass,
                 const double parameterValue) const
{
  std::cout<<"called refer"<<std::endl;
  baseClass.setParameter(parameterValue);
}
  
};

int
main()
{
  AnotherClass A;
  DerivedClass B;
  
  A.setParameterOfDerivedClass(B,10.0);
  A.setParameterOfDerivedClass(*B,30.0);
}

Is this what you are after?? [Sorry if it is not...]

p.s. Note Please make the destructor virtual if you go this route.

StuXYZ 731 Practically a Master Poster

First off C++ has evolved in the last 10 years, hence some changes. These changes were because of unforeseen problems that occurred.

Let us start with why using namespace std; and why you might not want to do that anyway.

What happens in that there are a large number of standard library types, classes and functions that are available via a large number include files. Many of these names are relatively simple, e.g. max, min etc. In the same way that you don't declare everything global, you don't want the who symbol table polluted with names. Therefore, they are put in a namespace (std). That way you can select the symbols you are going to use and not accidentally introduce a "difficult to find" bug by using a global symbol. e.g.

using std::cout;
using std::endl;

Or you can explicitly type the namespace at the point of use, e.g.

std::cout<<"this is a test"<<std::endl;

However, you have the option to go back to the old way, and type using namespace std; . Obviously, you can do the same for all the other namespaces that you import. However, if you get into difficulties by name pollution...sorry you only have yourself to blame. :) [Note for small projects, you will be fine, but bigger projects don't work]. Also note that all the using commands are scoped, so you can have it globally, or just for one section etc. That is why you should not put them in an include file.

StuXYZ 731 Practically a Master Poster

Having looked at Rebellions test case, which is clearly has complex roots, I think that you are going to have to use complex numbers or use two doubles. Since two doubles is a bit ugly let me talk about std::complex<double>.

First of there is an amazing amount of stuff in that type, especially for the beginner. There is a namespace (std) and there is a template class. Both of which deserver a whole chapter in Stroustrup's C++ book!

However, the beauty of C++ is that once you OR someone else, has actually defined a class, complete with all the operators (e.g. +,-,* etc), you can use it almost as if it is a normal type, without worrying about exactly what it is.

So if you did this

// Note: have to convert b*b-4ac to a complex or sqrt(double) will be called.
std::complex<double> sPart=sqrt(std::complex<double>(b*b-4*a*c));
and 
std::complex<double> root1= (-b - sPart)/(2*a); 
std::complex<double> root2= (-b + sPart)/(2*a);

You could then just output your result. e.g. std::cout<<"Root 1 == "<<root1<<std::endl; , or you can check that the solution is a complement
by doing root1*root2, etc.

This may not be what you want, however, you can also solve your problem by noticing that if b*b-4*a*c is less than 0, then that part is the imaginary value, and you can
output it as std::cout<<"Number = "<<-b/(2*a)<<" "<<sqrt(4*a*c-b*b)/(2*a)<<"j"<<std::endl; ;

Finally, If a is zero there is still a solution, since you have b*x+c=0 , i.e x = -c/b.

StuXYZ 731 Practically a Master Poster

Two quick comments, AD is correct that you should have deleted line 4 in Fraction.h, [and that you have misspelled fractions in main()] (what it does is define the symbol hbg_cmpsc122 as and empty value. Therefore when you write namespace hbg_cmpsc122 { you have effectively writen namespace { .

This is why you have all the error messages to the unnamed namespace.

The normal include file guard, is to write this

#ifndef FRACTION_H
#define FRACTION_H

 // your stuff here...

#endif

So perhaps it would be better to change line 4 of Fraction.h to #define FRACTION_H .

Finally, if you want to turn warnings on for g++ then use g++ -W -Wall.

Ancient Dragon commented: Yes, that's what I meant :) +33
StuXYZ 731 Practically a Master Poster

I am answering this simple because I can't believe that anyone teaches a class without giving some feel for why.

Your code introduces that basic concept of a 2D array, ie. having two coordinates.
[The idea can be extended up to many dimensions e.g. 3 or 4 etc.]

So when would you use a 2D array, well for anything with 2D coordinates, e.g. locations on a map, you want to write the next route finding code for your GPS, well, you will have a 2D array of points of interest. Your particular example looks like you are about do a chess program (8x8 board). You might need to do some photo editing, each pixel is often on a 2D array, when you camera say 4 megapixels, it means that the CCD is actually a 2D array of pixels 2000 by 2000.

There is another type of example that is when you have information that is correlated, e.g. If you want the test scores for a set of students over each week, you might declare a 2d array like int scores[NStudent][NWeeks]; .

I am surprised with this way of teaching coding in the abstract, I like to do it with a problem that is common to the group, e.g. young students, get them to write a game, older I tend to aim it at the course, e.g. for engineers I might get them to write a simple circuit simulator.

So think of something that you …

StuXYZ 731 Practically a Master Poster

Your problems include two things that come to mine:

(a) the answer that you require is complex, but you are trying to put that into a double. Not going to work. Instead add a #include <complex> to your headers and use std::complex<double> root; . You are also going to have to be careful with your sqrt. Since the incorrect sqrt function (that taking a double) will be called if you don't. [i.e. you want to cast the b*b-4*a*c to a complex before taking the sqrt. ]

(b) Your test for zero is strange, what is wrong with this quadratic x^2-9=0 ??
[Small reminder, testing doubles as a==0 is often not going to go well, as you are likely to have a very small number not zero]. Anyway, you only have to check is a is not too small to cause an overflow. That is a better test done after the calculation.

StuXYZ 731 Practically a Master Poster

Well first of if you need random numbers to actually compute something else, don't use rand() for anything, it simple isn't random enough. [Basically, rand() has very poor lower bits.] e.g. see http://www.eternallyconfuzzled.com/arts/jsw_art_rand.aspx

So that leads us to looking for a good [enough] random number generator. The current defacto standard for most scientific simulations is currently MesenneTwister [e.g. GEANT, gsl, octave]. Mersene-Twister can be found at http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html. Note, this site links to the original Mersenne Twister, and some of the faster (but same randomness) implementations that exist. All of the links go to open source code. It also links to the scientific papers about the random number generator, be warned heavy maths.

Finally, what you are after is to create a random number between to numbers (considered a range). Using your favorite random number generator, you are typically going to get a random number between 0 and 1. If you are using Mersenne Twister you have a choice of getting the number fully inclusive, partly inclusive and totally exclusive [i.e. you can/cannot get the extreme values one and zero].
You have to be careful about that choice and its effect on your applications, then you want to convert it into your range. This is done like this:

double rV= lowerNumber+ (higherNumber-lowerNumber)*random();

Note that you might have to cast the number to an integer, again be careful to ensure that you can/can't get the lowest/highest numbers in the range.

StuXYZ 731 Practically a Master Poster

Nearly working but you have a small tiny problem with your code.

In C (and C++) your simple char strings need to be terminated with the value 0.
[That is 0x0 and not the character '0'].

You didn't do that, and you don't need it for the second loop that sets q. You
do need it for the comparison, because you might have extra characters at the
end of the comparison. You could check that with something like, printf("Length of p and q : %d %d",strlen(p),strlen(q)); .
[Note that is the C way of doing it.]

Therefore you need something like this: for lines 16/17

if (*p=='\n') 
  {
    *p=0
    break;
  }

The we come to the loops that set q, Interestingly what you have written [except for the zero terminator] actually works!!! However, you are doing this:
(a) get a letter in the word(s) in p from the back,
(b) set ALL of the array msg2, to that value
(c) leave q pointing to the first character AFTER the end of msg2.
(d) repeat from (a).

Therefore you need to fix this double loop.

Note: If you want to, you do not actually need to use a second array to copy the words into. Recall, that you can compare individual letters, e.g. if (msg[4]==msg[5]) printf("There is a double letter in this word\n");

StuXYZ 731 Practically a Master Poster

Sorry, as I was reviewing my post, I then had a big edit of it... then I spotted the error....

Line 78 is fine, it was me miss reading the variable name. [Sorry for the confusion]

StuXYZ 731 Practically a Master Poster

Introductory Note: You have not written std::vector<double*> S; . Which is a completely different discussion. This is often frowned on because it is SO easy to mess up, the memory [de]allocations.


Ok: In the general sense it is perfectly fine to have a point to a vector, or any other stl class. There are several "obvious" reasons for having a pointer, e.g.
(a) you could have extended a standard class and have a polymorphic system.
(b) you have a selection of classes and were avoiding a bit of memory/resource etc.
(c) You want to transfer ownership of the pointer between objects.

Of those I think (a) and (b) are not good reasons:
(a) isn't good, since the lack of virtual functions in the STL implementations don't make them easy classes to extend.
(b) The size of the class is minimal relative to a filled class. Normally has zero bearing on memory footprint etc.
(c) I am kind of ok with, but I would normally wrap it in another class, with better control and semantics.

Now let us look at what you are actually doing and see if I agree.

Well every student has a vector<double> assignment, so you are only interesting in option (c). Indeed this does make your sort quicker. However, the cost is the potential bugs that you will introduce.
However you can effectively have what you want (and slightly more optimization), by moving the …

gerard4143 commented: Great pointers +4
StuXYZ 731 Practically a Master Poster

The A and the B are the two different RectStruct that you are comparing. If you don't pass that then there is no point to the function?

The function takes any two rectangles and returns (in variables min/max) the areas such that the largest area is in max and the smallest area is in min.

StuXYZ 731 Practically a Master Poster

Well if your professor said use a struct, not a problem you just do this:

struct Rect
{
  private:
     float x;
     float y;
     // etc
  public:
    Rect(const float,const float,const float,const float);
};

Yes I know that is not what was intended ;)

The only difference between a struct and a class is that a class is by default private and a struct is by default public. If you add private: and public: statements they are the same.

Three minor points, the typedef serves no purpose but to give you two names for the struct, e.g. Rect and RectStruct, surely just call the struct RectStruct.

You might want to consider using a reference to RectStruct in printRectValue/assignRectValue/calcRectArea etc, e.g. float calcRectArea(const RectStruct&);

NEVER put using namespace std; at the end of an include file like that!!

StuXYZ 731 Practically a Master Poster

The first thing that is wrong is that you have written this: p[i]=str[strlen(str)-i]; Now apart from re-using strlen(str), which it would have been better to put it in a varaible (although my compiler nicely optimized it out). What happens when you put i==0 into that statement you get: p[0]=str[strlen(str)]; and that is the same as p[0]=0; .

Line p[strlen(p)+1]=0; is also not good, if you had done your loop
correctly, this code would have been horrible, since you don't know the length of p.
[The code adds a 0 after the final zero]

If you get into char string problems, it often pays to do this
for(int

StuXYZ 731 Practically a Master Poster

First off you haven't give us Rect.h, and that is important.

However, guessing that Rect.h looks something like this

struct RectStruct
{
  float x;
  float y;
  float height;
  float width;
};

First off, I really like what you are trying to do with this code, you have almost all the main aspects of basic functions in this code. Sure, it is not correct, but once you are finished, you effectively have a single example, which covers are large number of techniques. Additionally, you have a lot of output, that is a really good debugging/understanding tool.

However, we have a few problems to discuss:

Firstly, you have decided to make RectStruct a simple structure, but then added a whole host of assignment and calculation functions. That is ok, but think about if a class with public methods and private data would have been better.

Second, calcMinMaxValue, is a truely horrible function. The reason is that you
allocate new memory to rect01, then don't delete it. You seem to be using rect01
and rect03 without any initialization. [or did you ad a special default constructor
to RectStruct in Rect.h??]

So calcMinMaxValue function should be like this:

void calcMinMaxValue(RectStruct& A,RectStruct& B,float& min,float& max)
{
   // your stuff here
}

Thirdly, int main(), you allocate two rectangles rect01 and rect02. That is fine,but for every new there should be a delete e.g. put a delete rect01; etc at the end of the code.

StuXYZ 731 Practically a Master Poster

Well assuming that you have a string and you want to change it, you can
used this

std::string test="abcde";
test[4]="X";
std::cout<<"Test == "<<test<<std::endl;

The string class provides the operator[] which allows you to examine and change each letter in the string. That along with a loop will allow you to change the vowels in a string to anything you please.

If you get a little more sophisticated you can start using functions like find() etc. But start with a loop first.

If you get stuck, post the code you have ... hope this helps.

StuXYZ 731 Practically a Master Poster

The normal approach is to use an integer. If you are working with decimal currency then you would use the number of pennies for examples, or even 1/1000 of a penny. Whatever accuracy you require. [Please replace "penny" by the correct currency unit].
To display the value, normally you would then divide by the correct amount, and then display. I might give you rounding errors in a display, but remains accurate so when you subtract two big numbers you still have an accurate small number left.

You may well need to use a long int, rather than int

StuXYZ 731 Practically a Master Poster

I can guess that isn't going to work well!! You really don't need to include any cxx files in your .h files. [With the possible exceptions of some template classes but even then you should avoid it].

First: Small point , don't use #include <file.h> for your files, the < > searchs the whole include path e.g. /usr/include etc, and your files are going to be local to the project directory, so you have two problems, it takes longer and you have the possibility of getting the wrong file, if you are unlucky with your naming.

So what you really want is to compile the .o files (the object files) for LinkedList and then main etc. Let us do it manually and then see how to construct a simple Makefile.

g++ -o LinkedList.o LinkedList.cxx
g++ -o main.o main.cxx
// Linking bit (putting the object files together)
g++ -o Program2 main.o LinkedList.o 

So what you have done here is compiled two object files, and then after the fact, linked them together. Now if you were to change LinkedList.cxx, then you would only do the first and third step, since main has not changed. If you change linkedlist.h, since both main.cxx and LinkedList.cxx have that file included you will do all three steps.
Now the purpose of make, is to automate those decisions.

The Makefile is to do that as well, but only compile those bits that need compiling if something has changed OR the dependencies of the file …

StuXYZ 731 Practically a Master Poster

The quickest way is to put a setprecision into the stream:

InputOutputStream>>std::setprecision(12)>>TotalOutputString;

(You may need to add an #include <iomanip> to your file as that is the place for the definition. You don't need the std:: if you have the horrible, using namespace std; line).

That still means that you will get 1e13 if you enter a number over 100 billion.
However at those number you start seeing floating point rounding errors. e.g
you will start to see 999999995 (as floating point is roughly only accurate to 8 places.) If this is for financial calculations, do not use float or double.

StuXYZ 731 Practically a Master Poster

Your problem is a combination of reverse and the way you call reverse.

You have reverse (char*), as taking a char pointer. That is an area of memory that can be modified. However, when you call it, you pass a constant string. C++ represent that memory as non-mutable, i.e. It does not allow you to modify it. Hence you get a runtime error.

So to fix your problem call reverse this way

int main()
{
   char word[]="university";
   reverse(word);
   // NOTE: word has changed.
   std::cout<<"Word is now ::"<<word<<std::endl;
   return 0;
}

Additionally, main() is actually returns an int, most compilers that were written in this century, will not allow you to compile it as a void. [Which tell us that you really should get a new compiler. There are many good free compilers and IDE (Integrated development environments), available.]

StuXYZ 731 Practically a Master Poster

First off I assume that this is a course work/self-learning problem, otherwise, just use a pre-existing library routine. [GSL/ACM/G4 and others]

The usual place to look for maths stuff is the wolfram site and you get: http://mathworld.wolfram.com/QuarticEquation.html

Ok, that takes you through the solution of both the real and complex cases (constants a to e can be real/complex). [The real case is just a quick optimization of the complex case].

HOWEVER:

If you have coded up quadratic and cubic equations before and understand how the solvers work then you will have no problems. If you haven't done them before, ensure:
(i) You understand how they work [remember that your solver will have to do that in the case that constant a is zero.]
(ii) you have written and tested each of them
(iiI) You understand the special cases of the simpler equations

Your quadratic solver will use the lower level solvers for many of the special cases, e.g.
for the case that the depressed function has a zero x term. You cannot bluntly ignore the zero coefficient terms and just pretend that you want to solve it with the general form. It will give you divide by zero errors, or horrific numerical errors if you try to set zero to a very small number.

The quartic equation has a lot of alternate cases, it becomes an ugly mess of "if statements", in C++, no matter how it is …

StuXYZ 731 Practically a Master Poster

Sometimes the best way to look at a problem is to reiterate it. So here goes. Feel free to ask questions about this comment.

The objective of the code is to write "Hello, NAME" were NAME is replaces with whatever you say your name is. However, it is to have in in a block of stars. (*).

e.g.

******************************
*                            *
* Hello, VeryLongNamedPerson *
*                            *
******************************

The issue with rows are the number of "*<blanks>*" lines to add. e.g You might like 6 above and below. HOWEVER, the code as written does NOT do that. The line rows = pad*2 does not need the pad*2. Then later in the code the placement of the greetings text is not centred.

cols on the other hand is a calculated variable, ie it depends on the length of your name, However, it also depends on a const variable pad, i.e how many spaces from the edges of the *s to your greeting.

This examples to my mind is poorly set out . I would have much prefered to see code start as this

int main()
{
   const int pad(3);           // spaces to the side of your greeting
   const int rows(5);          // Total rows displaced including greeting and 
                               // ***** at the top / bottom.

   // Calculated values here:
   //.....

i.e this is a very clear definition of what is a parameter and what is calculated -- it comes back to the principle code should convey …

StuXYZ 731 Practically a Master Poster

My guess is that you have just landed on the chapter about arrays. I could tell you about the standard library, stuff like vector etc BUT I hope that is a later chapter.
In fact, I hope that you do this exercise, three times or something like that, using different storage systems each time.

Anyway Arrays:

You seem to have understood variables, and they are just names that are going to have a type and a value. You could write this:

std::string name1,name2,name3,name4;
std::cout<<"Enter 4 names"<<std::endl;

std::cin>>name1>>name2>>name3>>name4;

Now that is ok, but what if you wanted more than 4 names, say 100. That would be VERY laborious. So to get round that you can do this:

std::string arrayOfNames[25];
std::cout<<"Enter 25 names"<<std::endl;
for(int i=0;i<25;i++)
  std::cin>>arrayOfNames[i]<<std::endl;

Now as long as the part in the square bracket correspond to a number from 0 to 24, you have effectively found a way to write arrayOfNames23 or whatever the number is.

There are two points : (a) the index runs from 0 to 24 (b) if you get it wrong and put arrayOfNames[25] what happens is undefined. i.e you can get a completely random name or your program can core dump etc.

In addition, since c++ is a relatively low level language, you can see how the code arranged the memory in reality (and hence why the strange 0 to 24 pattern above).
Consider this:

int xArray[25];
std::cout<<"Memory location for xArray[0]="
          <<reinterpret_cast<long int>(xArray)<<std::endl; 

for(int i=0;i<25;i++)
  std::cout<<"Mem …
StuXYZ 731 Practically a Master Poster

Not 100% sure what you are after, so I am going to re-iterate your problem as I see it then you can correct me and (hopefully) we can all get closer to the exact problem you are after:

You seem to have several problems that need to be separated out.

(a) You have an array of detectors that are silicon based. The array is a close packed structure on a rectangular/square array (?) [This is important -- is it square/rectangular -- since that effects the probability that charge can move to the next cell]

(b) the readout electronics is obviously not reading in the same pattern, [thus allowing electronic cross talk to be seen -- this is different from pixel cross talk, and to improve deadtime issues]. Thus the array of data that you get needs to be re-mapped to find out which pixel is next to which other pixel.

(c) The data you get for a given pixel is simple binary detection of an event/ no detection. There is no time information, no charge information etc. (?)

(d) As I understand it you you have a grid of pixels in space, that have a finer grid of position sensitive points within each grid point. You seem to have 2048 pixels each made up of 16x16 fine grid of points.

(e) There is charge spillage from a fine point to its nearest neighbours but there is no charge spillage to the next pixel grid …

StuXYZ 731 Practically a Master Poster

Your problem is really in replaceString.

replaceSubstring(string1,string2, string3);
}

void replaceSubstring(string string1, string string2, string string3) 
{
  int spot1; 
  int spot2; 

  spot1 = string1.find(string2, 0); 
  spot2=  string1.find(string2, 3);    // From original string 
  string1.replace(spot1, (spot1 + 3), string3);
  // Now original string is NOT orignal length:
  // NOTE: Replace(position, length_to_change , substitute_string)  
  string1.replace(spot2, (spot2 + 3), string3);
  cout << string1;
}

what is happening is that you find the position in the string for the first and the second word. BUT you replace the first word, first. That shortens the string, THEN, when you replace the string. So you are one character off.

Then you make your next mistake. The replace takes three variables (a) the position,
(b) the length to replace (c) the substituted string. You have incorrectly thought that it takes two positions, easy mistake to make, but it is just the length. therefore in your code you accidentally chop off all of the string. [In the first instance the position is 0, so 0+3 is still the length.]

you might want to look at something like this:

void replaceSubstring(string&,const string&,const string&);
int main() {
  string string1 = "the ball is under the car         ";
  string string2 = "the";
  string string3 = "that";
  cout << "The orginal strings consist of: "<<string1 << endl; 
  replaceSubstring(string1,string2, string3);
  cout << "The new string consist of: "<<string1 << endl; 
}

void replaceSubstring(string& SMain, 
		      const string& searchString,
		      const string& replaceString) 
{
  // This is because string defines the type …
StuXYZ 731 Practically a Master Poster

Well I am going to try to give you part of the answer, others (more knowledgeable) will hopefully fill the details in. I am going to assume you are talking about class initializers.

So let us do this via examples, so consider:

class A 
{
  const int vInt;          // Must be initialized in constructors
  double V;                // Can be initialized in constructors
  const complexClass cX;   // Will be initialized in constructors
  otherClass* Lptr;          // Can be initialized in constructors

  public:

    A();

    static double calcValue(const int);
    double getLen() const;
};

In this example there are four variables and two are constant. There are a set of rules about what happens in each case. First of all, all the variables can be initialized in the constructor. e.g.

A::A() : vInt(5),V(3.4),cX(1,2,3),Lptr(new otherClass(4.5,"filename")
{}

As you can see all variables are initialized. Now please not that the order matters.
You can only access them in order. This will not provide the correct results:

A::A() : vInt(40),Lptr(new otherClass(4.5,"filename"),V(Lptr->getLen())
{}

Note that despite the order on the constructor definition, the order is as given in the class definition, i.e. the value of Lptr is set after V has been set. In this code the likely effect is a memory violation/core dump of some sort. (You do get compiler warnings on all modern compilers)

Also note that I have not initialized cX. That is ok if and only if, cX has a default contructor, that takes no values. If cX's …

StuXYZ 731 Practically a Master Poster

Sorry but can you post your current code [using code tags] please, I have no idea what line 24 is for example, and I don't exactly know what changes you made.

StuXYZ 731 Practically a Master Poster

Ok you seem to have made a number of mistakes that stem from a simple mis-understanding of how arrays and pointers interact.

So I am going to go through the basics of this :

First off an array as defined by int array1[5]; reserves a block of memory that is 5 integers long. They are sequential in memory, i.e. there isn't another object/item/value in between.

Now a pointer can point to any memory location, or it could point to no memory location (it value will be zero).

Multiple pointers can point to the same memory locations, if required. Pointer are like book marks they point to pages in a book. Change there location does nothing to change the book. Only if you write to the memory location pointed to by the pointer does the array change, [similar to writing in a book at the page indicated by a book mark.]

So looking at your code:
You want to reverse an array into a new array.
You need to pass three things to a function. Original array LOCATION , size, NEW ARRAY LOCATION.

However, you correctly get the first and second but no the third.

In C++/C we have a helper pointer which is the name of the array. It points to the first element of the array. You don't have to use it. These two pointers are the same array1 == &array1[0] .

So you should call reverseArray as this: …

StuXYZ 731 Practically a Master Poster

You hopefully have read the rules, no homework help unless you show some effort. This is an easy algorithm, you just implement. You are going to need some simple variables, the count, the previous letter, the current letter and the output string/stream.

Loop over the input string/stream and compare the next letter with the last letter, if it is not the same write out the last letter + the count (if not 1), reset the count and update the last_letter variable. Some care is needed for when you read in a number.

Improvements can be made in the compression ratio with a wide number of things, e.g. a symbol to mean to stop compression until the next copy of the symbol etc. Discussion of what happens when you double compress.

When I have set stuff like this I normally give about 50% extra marks for the unasked for extras. [Which allows a mark out out 140 and a carry over to other parts of the course. :) ]. So think about how to improve the algorithm, for your input data, when the compression works, what sort of break even data exists, and what happens with pure-random data.

So when you have some code , post it here in code tags, and give a brief outline of the problems, e.g. expected output and actual output, and we will comment and provide some help [if we are able to].

StuXYZ 731 Practically a Master Poster

Just to ask, you say that it is for a paper in ACM and IEEE. Any of those journals have a fairly high entry level, they are refereed and some of them have a very high rejection rate. That seems a much bigger problem the how your program was written. If I take a finished project that has got a paper accepted to IEEE, I can claim all of the other factors really easily regardless of actually how I wrote the project.

So my guess is that this is a project for a masters thesis by research. So basically, you are going to have to give us some more hints on what subject area you are looking for.

The place I would look is in a lot of the semi-neglected areas, [less popular at the moment] that were looked at in the 1970-1990s which often can be relooked at with the massive increase in computing power to give insights into their underlying problem. Other areas of projects are often newish algorithms applied to data sets, e.g. a similar route caching algorithm applied to say web searches etc.

The problem you face is that "getting an idea" is not something that just happens. Once you start on a research project, two things happen, you read something completely unrelated and think that maybe some part of what you are doing can be applied to it , and that your read something unrelated that can apply to your stuff.

StuXYZ 731 Practically a Master Poster

There are many problems with this code: But the bit that should be stopping you compile and debug it is in the call: output_result ('largst', a, b, c); You see two problems first that single quotes are used for a single character e.g. 'x' etc. You need a string. So change it to "largest". [Another minor issue: you have spelt largest incorrectly in your code].

Next you have not declared you function correctly. The prototype is void output_result(int,int,int); I think you need this void output_result(std::string,int,int,int); [Note: a reference e.g. const std::string& would be better which you obviously have covered since you are using them in get_input.]

Finally, you have a couple of "" in your output_result part. They are wrong obviously. [If you actually want a quote in the output, then you need to "escape" it e.g. "this is a \" quote in a string" .]

After that you will need to debug it, get the functions for smaller/greater called etc.


When you post again, can you please use code tags and give a little bit of the compiler error messages.

StuXYZ 731 Practically a Master Poster

I first off this is an excellent exercise. If you are doing this yourself, well done, if you have a teacher/class, your prof. certainly has found an excellent problem.

So why do I think this is so good, what happened here is that you have designed two classes that can be related. However, when you do try to do that you have a number of issues that could have been avoided if some of the more subtle OO design "rules" had been applied.

First off Rational should be an effective replacement for double. So anywhere in your code that you could write double x; , you could have put, Rational x; . It is not there, yet. Second, polynomial is written to take an integer coefficient. What about the other normal options, e.g. double, matrix, polynomial. [A polynomial of polynomials is mathematically sound and useful.] It should take these options without any significant change to the code.

So what work needs to be done to get to this state:

Make Polynomial more general so that it takes a template type e.g.

template<typename T>
class Polynomial
{  
  public:

  static const int maxTerms = 10; // maximum number of terms

  Polynomial(); // constructor
  // WHERE IS MY COPY CONSTRUCTOR ?????
  Polynomial& operator=(const Polynomial &); 
  ~Polynomial(); 

  Polynomial<T> operator+(const Polynomial<T> &) const; 
  Polynomial<T> operator-(const Polynomial<T> &) const; 
  Polynomial<T> operator*(const Polynomial<T> &) const;

  Polynomial<T>& operator+=(const Polynomial<T>&);
  Polynomial<T>& operator-=(const Polynomial<T>&);
  Polynomial<T>& operator*=(const Polynomial<T>&);
  
  void enterTerms();           // Spelling error corrected
  void printPolynomial()
StuXYZ 731 Practically a Master Poster

Couple of small points, since FirstPerson is correct. You should not be using pointers in your quaternion class, but I believe that FP has made a tiny tiny mistype:

Conjugate of a quaternion is normally

#
void CQuaternion::conjugate()const
{
return CQuaternion(w,-x,-y,-z);    // w is not multiplied by -1 here.
}

Depending on your code, I prefer to have operator*= called from operator* and make
operator*= a member of the class, and think about putting operator* either in / out of the class as is suitable.

However, It think conjugate would normally be a member of the class, because you normally would write this,

Quaternion Q(3,-4,5,-6);
double Weight=(Q * Q.conj()).real();
// or more typically:
result = Q.conj() * func() * Q;

and that leaves one less place to go and update, if you say refactor the class to use a double + a 3d vector.

StuXYZ 731 Practically a Master Poster

t:
Why not convert the file into a ordered vector/list of time:count, using a structure
to represent the time. e.g.

struct Item
{
int day;
int timeSec; // Number of seconds from midnight
int count;
};

Then you can use a std::vector of Item, which you can defined a less than operator to
allow you to sort it, binary search works well to find stuff like the first of day 3. [You might want to keep an index file or days, or max counts per day etc, or whatever is very often accessed.]

If you have a 2D array even for each minute of every day over 20 days, think of the SIZE of the array! 20*60*24, that is already 28800 entries. If you ever need second resolution life gets very unpleasent.

I do not see the logic in using a 3D array, surely count is the data, so it should not be an index of an array in most normal circumstances [There are exceptions].
If you add counts to your array, even if all counts are below 100 you at 2.8million. It will be fine but it is getting very non-extensible.

StuXYZ 731 Practically a Master Poster

Sorry but I REALLY don't understand what you are trying to do. I would appreciate an example or two. However, that leaves the code, which is simply horrible. It cannot possible be necessary to write so much code to do this, and it cannot be necessary to using strings to manipulate the data form [They are very very expensive (CPU/memory etc) for the purpose of bit operations].

So I am posting a simple reverse bit code that reverses the bits in an integer. If you then want to apply xor or and etc to it. Then just do a reverseBit(45) ^ 1202; or whatever you wish to do.

If you can post a short description of what the code is trying to achieve, I/others may be able to help you further.

#include <string>   
#include <iostream>

std::string
convertToBinStr(unsigned long int V)
  /*!
    Simple function to convert an integer
    to a binary string
  */
{
  std::string Out;
  int sIndex(sizeof(V));
  Out.resize(sIndex);

  while(V)
    {
      sIndex--;
      Out[sIndex]=(V & 1) ? '1' : '0';
      V>>=1;
    }
  return Out.substr(sIndex);
}

unsigned long int
reverseBits(unsigned long int V)
{
  unsigned long int  result(0);

  for(int i=0;i<sizeof(V);i++)
    {
      result <<= 1;
      result += (V & 1);
      V>>=1;
    }
  return result;
}

int main()   
{   
  std::cout << std::endl;
  std::cout << ((12+20) & 1456) << std::endl;
  std::cout << "Convert == "<<convertToBinStr((12+20) & 1456)<<std::endl;
  std::cout << "Convert == "<<convertToBinStr(reverseBits(32))<<std::endl;
  return 0;
}

p.s. I simplified your includes, main() returns an integer, and I disposed of the system calls.

StuXYZ 731 Practically a Master Poster

Sorry firstPerson, I think I miss-read what you were saying and then failed to explain my comment.
The code as presented can allow gcd [the variable] to be zero. [hence the test in the code, etc].

I fully accept that nobody should start with zero (or one) but most likely from 2 and go up.
And you are correct that gcd cannot be zero.

I also think that this reduction method should be deleted and re-written using a better algorithm.

Anyway, sorry to all those I confused. I think my original post is mostly sane after that statement... (hopefully) .