mrnutty 761 Senior Poster

What exactly do you mean?

If you have an object moving, and you want gravity to account for its movement, then
you can just do this :

const float GRAVITY = -9.8;
ball.x += ball.velocity.x * dt;
ball.y += ball.velocity.y + GRAVITY * dt;

Those follow from basic Newtonian equation.

mrnutty 761 Senior Poster

Ignore all these scrub posters and use Horner's algorithm.

I take that as a compliment, thank you. And thanks for the info.

mrnutty 761 Senior Poster

I didn't compile your program bench, but in some compiler you may need to use the
keyword, typename in your to_string function, specifically here

typedef std::iterator_traits<FwdIt>::value_type value_type

because the value_type depends on the type that is passed. So the line would be :

typedef typename std::iterator_traits<FwdIt>::value_type value_type
mrnutty 761 Senior Poster

Why would you do this recursively? It will be better to do it iteratively.
For example :

//assume coefficient is written from highest degree to lowest 
float evaluate(std::vector<float>& coeff, const float x){
 int degree = coeff.size();
 float result = 0.0f;
 for(int i = 0; i != degree; ++i){
   float powResult = std::pow(x,degree - i);
   result += coeff[i] * powResult;
 }
 return result;
}
mrnutty 761 Senior Poster

First make use of const. Second in your NumberToString function, what happens
when the conversion fails? When the stringstream cannot convert the object passed in?
Handle those extreme cases as well. Also in your ContainerToString function, you
could just as well use a forward Iterator and it would work.

mrnutty 761 Senior Poster

Because the compiler see's it as :

int triangle(int);
mrnutty 761 Senior Poster

Or just this :

string str[5] = {"hello","ramble","people","kitty","rope"};
vector<string> vec(str,str+5);
mrnutty 761 Senior Poster

hi Everyone,

I'm working with a Text file. Somewhere in my code a function returns the current position of the file pointer. But i want it to go to the next line or 2 lines after to do a string search there. Anybody knows how i can do that?

Bests,

If you want the file pointer to goto the next line, then just use the getline(...) funtion
to read in the current line as a dummy. And the file pointer will proceed to the beginning
of the next line.

mrnutty 761 Senior Poster

>>I believe that using a new two-dimensional array is the way to go,
Why do you think so?

mrnutty 761 Senior Poster

You need to break things into functions so its more readable. Also try this :

while (arquivo && getline(arquivo, arquivo_linha))
mrnutty 761 Senior Poster

huh?

mrnutty 761 Senior Poster

Mind explaining, what exactly do you mean?

mrnutty 761 Senior Poster

Does mod mean the same as remainder?

Also, I have never taken a programming class before so please excuse my lapse's of knowlage.

Yes mod returns the remainder from the division of its operands. For example,
10 mod 2 equals 0 because 2*5 equals 10, with 0 remainder. Another example,
5 mod 2 equals 1 because 2 goes into 5, 2 times with 1 remainder. Work it out on paper first and you will learn it better.

mrnutty 761 Senior Poster

Why not just do it manually? It'l take less time than that way.

mrnutty 761 Senior Poster

Here are some hints to get you started :

1) Given a number n, n mod 10, always results in the last digit of n. For example :

//mod = %
12345 % 10 equals 5
101011 % 10 equals 1
9234 % 10 equals 4
1 % 10 equals 1
0 % 10 equals 0

Now you have that fact. Here is one more:

Given a number n > 9, n/10 removes the last digit of n. If n is a 1 digit number,
then the result is 0. For example :

123/10 equals 12 //removed 3
100/10 equals 10 //removed 0
5234/10 equals 523 //removed 4
1/10 equals 0 //removed 1

Now you can use those facts to get each digit of a number. For example :

define n equal to 104
n mod 10 equals 4 and save 4
let n = n / 10 //n now equals 10 , 4 was removed
n mod 10 equals 0 and save 0
let n = n / 10 //n now equals 1, 0 was removed
n mod 10 equals 1 and save 1
let n = n / 10 // n now equals 0
since n is 0 STOP;

//now the digits we saved, do stuff with them

All of that is assuming integer arithmetic.

mrnutty 761 Senior Poster

Here is an example of your problem :

//Player .h
#include "Monsters.h"
//...
//Monster.h
#include "Player.h"
//...

Your problem is called Circular Dependency
See if you can solve it on your own.

mrnutty 761 Senior Poster

First some design problem. This function is pretty bad :

void attackplayer(Player& hero, bool checkup, bool checkdown, bool checkleft, bool checkright){
 if (checkup == true || checkdown == true || checkleft == true || checkright == true){
	hero.damage(damage);
 }
}

First an obvious way to make this better is to use the boolean as boolean, no need
for conversions, thus you should just do this

void attackplayer(Player& hero, bool checkup, bool checkdown, bool checkleft, bool checkright)
{
	if (checkup || checkdown  || checkleft || checkright ){
		hero.damage(damage);
	}
}

But its still bad. Specifically, you have a variable for each direction. What you
should do is abstract the direction. So the param is just 1 Direction and in that
Direction it has left,right,up,and down states. So do Something like this :

struct Directions{
public:
	enum Dir{EAST,WEST,NORTH,SOUTH,SIZE};
private:
	bool dir[SIZE];
	Directions(){
		std::fill(dir,dir+SIZE,false);
	}
public:
	void east(bool r){ dir[EAST] = r; }
	void west(bool l){ dir[WEST] = l; }	
	void south(bool s){ dir[SOUTH] = s; }
	void north(bool n){ dir[NORTH] = n; }

	bool get(const Dir direction)const{
		return dir[direction];
	}
};

class Player{
private:
	Directions playerDirection;
public:
	void attackplayer(Player& hero,const Directions& dir){
		if(dir.get(dir.EAST) || dir.get(dir.WEST) || dir.get(dir.NORTH) || dir.get(dir.SOUTH)){
			/* Do stuff */
		}
	}
};

No that might look like a little more work, but end the end it will save you more trouble.

mrnutty 761 Senior Poster

Its pointless doing this since, you are using string, unless you are doing this as an
exercise.

string text = "This is the text I want to search in";
string wordToFind = "want";
bool isFound = text.find(wordToFind) != string::npos;
mrnutty 761 Senior Poster

Here is an example :

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main(){
 vector< string > names;
 const string END = "!";
 cout << "Enter many names... <enter '" << END << "' to quit >\n";
 while(true){
  string temp;
  cin >> temp;
  if(temp != END)
    names.push_back(temp); //add names
  else break;
 }

  for(int i = 0; i < names.size(); ++i){
   cout << names[i] << "\n";
  }

  return 0;
}
mrnutty 761 Senior Poster

I hope there is no naming conflict here , since there is a std::list. But this code:

listArray = new list[hashTableSize];

will THROW and exception, instead of setting listArray to null. So there is no
reason to check if listArray is null, because you won't get a chance to check it, unless you use nothrow.


EDIT, from your previous post, you need a good constructor :

struct hashType{
	listType *head;
	listType *tail;
	int numValue;
 //use a initializer list, to initialize head,tail,numValue using its default constructor.
 hashType() : head(), tail(), numValue(){} 
};
mrnutty 761 Senior Poster

why yes there is.

mrnutty 761 Senior Poster

When you change the array size, change the bounds on the for loop as well. Thats why
you should use integer constants :

const int MAX_SIZE = 10;
int inputArray[MAX_SIZE] = {0}; //initialize all elements to 0

 for(int i = 0; i < MAX_SIZE; ++i){
  cin >> inputArray[i];
 }

 //sort array using bubble sort
 for(int i = 0; i < MAX_SIZE; ++i){
   for(int j = 0; j < MAX_SIZE; ++j){
       if(inputArray[i] > inputArray[j]) std:::swap(Array[i],Array[j]);
    }
  }

  //print Array
 for(int i = 0; i < MAX_SIZE; ++i){
   cout << inputArray[i] << " ";
 }

Now if you want to change the array size, all you have to do is change only MAX_SIZE
to a different number.

mrnutty 761 Senior Poster

>>but still, I wont be able to code a working and satisfying OOP design

Don't worry not many people do. It takes time and practice and more time and practice.
Until, then start reading and coding. Eventually, you will start to recognize some
type of pattern you can do to solve a problem.

mrnutty 761 Senior Poster

1) Write code.
2) Write more code.
3) Read up on design patterns, whether it be wiki or whatever
4) goto 1 until comfortable
5) Now every time you write code, you can either :
5a) Finish the code, and the project ( depending on its size) then take a step back
and see how you can better the system, decouple it, give each class its minimal
job.
5b) Or take a step back first, and think about how each class interacts with the
other and then how all class interacts to make the program. This is where UML
comes in. It provides a visual
6) Repeat all of this procedure for like your whole life, and eventually you'll get
to be a better programmer.

mrnutty 761 Senior Poster

Also add std namespace :

#include<iostream.h>
void hi(void);
void name(void);
using namespace std;
int main()
{
...
}

Otherwise you get errors like "cin" not found, and so on.

mrnutty 761 Senior Poster

I found the solution just in case anyone is staring at this thread wondering the same thing about there template. The template is supposed to be a .h(header) rather than a .cpp.

Yes thats, a known fact. The up coming C++0x is going to fix this.

mrnutty 761 Senior Poster

Which version of MS Wrod do you have. In version 2007, it saves the formatting
and the colors. Perhaps, try copy/pasting it on a text file. And then export it on
M.S word.

mrnutty 761 Senior Poster

Can you explain a little more on what the problem is, and how you determine its a problem?

mrnutty 761 Senior Poster

I need to see the definition of elem and sentinel before we jump to conclusion.

mrnutty 761 Senior Poster
string fileName = "File";
	string extension = ".txt";
	for(char fileNum = '0'; fileNum <= '9'; ++fileNum){
	 string currentFile = fileName + string(1,fileNum) + extension;
	 cout << currentFile << endl;
	}
mrnutty 761 Senior Poster

What its asking you is to make a walk through table -- a step by step table
where each row corresponds to each iteration of the loop. Here, I'll get you started

Given this code :

int c = 0, sum = 0;
while (sum < 8) {
  c++;
  sum += c;
}
 cout << sum;

a walk through table might look like this to start :

iteration # , value of c , value of sum
---------------------------------------
   0             0               0
   1             1               1
   2             2               3
   3             3               6
   .             .               .
   .             .               .
   .             .               .

I think that is what its asking for.

mrnutty 761 Senior Poster

Actually, I never seen that before. Usually I just call the function w/o the return
statement. I think you should omit the "return" statement on line 8 and 17, because
that might confuse a reader thinking that it actually returns something.

mrnutty 761 Senior Poster

Here are some although googling would help you get more problems :

1) Create a program that checks if the input is odd or eve
2) Create a program that checks is a power of 2
3) Create a program that asks the user for a positive even number, if thats not supplied, then throw an error
4) Create a program that compares 2 strings and outputs its max
5) Create a program that has the user enter 2 numbers and outputs its max, min, and everage
6) Do #5 for 3 numbers then 4 numbers then 5

mrnutty 761 Senior Poster

Your average.h is Good, nice job.

Now your average.cpp, has a logic error. Think of average.h like it declares
a function prototype. And average.cpp actually defines these functions.

The logic error in your average.cpp :

#include "average.h" //good

using namespace std; //does not need this since average.h already has this, but is a good practice

float calculateAverage(int numberInputs[], const int size) //function definition  //good now you define the function you declared in average.h
{
	int sumOfTotalInputs = 0; 
	int i = 0;
	int avg;
       /*--------Below is your logic error--------------------*/
	sumOfTotalInputs += numberInputs[i]; //calculation to get the total sum of numbers from user
       /*----------------------------------------------------------*/
	avg = sumOfTotalInputs / size;  //to find average 

    return average;
}

the place where I marked logic error is your first problem. You need to go through the loop and add up all the values like so :

for(int i = 0; i < size; ++i){
 sumOfTotalInputs += numberInputs[i];
}

Now your other problem is inside your main.
This code

int [NUM_OF_INPUTS] = [0];

is not how to declare an array, this is how you declare an array :

int Array[NUM_OF_INPUTS] = {0};

Then you do not need this part in your main, just delete it :

cout <<"This program will average a group of 5 numbers of your choice." <<endl;
cout <<"\n\nPlease enter 5 numbers: " <<" "<<endl;
//cin >> numberInputs[i]; //<--- do not need this , you have it inside you for loop

Fix those and …

mrnutty 761 Senior Poster

Ok, here is the deal. Do you know how to do this with 1 file ?
For example in 1 file, you would do this :

//main.cpp
#include <iostream>
using namespace std;
float calcAverage(int inputs[], const int size); // [1] function prototype
int main(){
 const int NUM_OF_INPUTS = 5;
 int inputs[NUM_OF_INPUTS] = {0};
 for(int i = 0; i < NUM_OF_INPUTS; ++i){
     cin >> inputs[i]; //get the 5 numbers from user
  }
 cout << "Average = " << calcAverage(inputs, NUM_OF_INPUTS) << endl;
}
float calcAverage(int inputs[], const int size) // [2] function definition{
 int sumOfTotalInputs = 0;
 for(int i = 0; i < size; ++i){
   sumOfTotalInputs += inputs[i]; //get the total sum
 }
 //calculate the average, notice average is of type float
 float average= float(sumOfTotalInputs) / size; 
}

Now all you need to do is split the code up, so for example you could do this :

//average.h
void calculateAverage(int inputs[], const int Size); //[1]function prototype
//
//average.cpp
void calculateAverage(int inputs[], const int Size){ //[2] function defintion
  //... code to calculate averge given the array of numbers and its size
}
//main.cpp
int main(){
 const int NUM_OF_INPUTS = 5;
 int Array[NUM_OF_INPUTS] = {0};
 //get inputs from array
 cout << "Average = " << calculateAverage(inputs,NUM_OF_INPUTS)  << endl;
}
mrnutty 761 Senior Poster

I think its hear :

cin >> userGuess;
	while (!cin >> userGuess) {

In there you are asking the user to input a guess first. Then say it failed.
Then in the while loop it goes to ask the user to input a number
again. But the stream is in a failed state so that produces an error.
And since I don't know the operator precedience by head, I am not
sure if the ! gets evaluated before >>.

TO solve your problem change this part :

cin >> userGuess;
	while (!cin >> userGuess)

to this :

//cin >> userGuess;
while (!(cin >> userGuess) ){ ... }

Notice I commented out the cin >> userGuess part, which means you
don't need that.
mrnutty 761 Senior Poster

>>matrix<T> operator+(const matrix<T> & other) const {

You're still not getting it. You have const corrected function header. That
means you cannot change your member variables state. Which means
this->data.push_back (this->data + s_row); is illegal!!!!!

mrnutty 761 Senior Poster

Your function prototype is constant corrected, so that means you
cannot change the member variables, which you should not have to.

First you need to check if both the matrix are of equal size( equal row AND equal column ). Then next, you should create a new matrix object, that has a size equal to the matrix passed in. Then in a for loop, like you
were doing, just set the value at the index to the addition of the matrices at the same index.

mrnutty 761 Senior Poster

You should not worry about how fast a fundamental loop is. If you
care about speed, then your bottleneck is probably elsewhere.

mrnutty 761 Senior Poster

First thing that you need to do is write a driver program that has a main function in order to test it. Test the constructors and printRational. If you haven't written printRational, write it because you'll need it a lot when testing.

// driver program 
// includes

int main ()
{
    RationalNumber a();
    RationalNumber b (3, 4);
    a.printRational ();
    b.printRational ();
    return 0;
}

See if it compiles/runs/gives good results. If not, debug. If yes, you're on your way and you can write some of the operators.

Minor error on the red highlighted part. The compiler will see that
as a function. So to fix that we remove the parenthesis. Making it look like this :

RationalNumber a;
VernonDozier commented: Good catch. +11
mrnutty 761 Senior Poster

We can but not the way you showed it.

if ( (choice == 'e' || choice ==  'E') && (cur == 'd' || cur == 'D' ) ){
 //...
}
mrnutty 761 Senior Poster

Yes its permitted. 1st of all why do you need to use it? Second, the syntax gets pretty tricky. Here is an example :

#include <iostream>
using namespace std;

struct Foo{
	int x;
	int y;
	void print(){ cout << "(" << x << "," << y << ")" << endl; }
	Foo() : x(0), y(0){}
};

//typedef to make syntax simpler
typedef int Foo::*FooMemberPointer;
typedef void (Foo::*FooFunctionPointer)(void);

int main(){
	FooMemberPointer posX = &Foo::x;
	FooFunctionPointer display = &Foo::print;

	Foo littleFoo = Foo();

	(littleFoo.*display)();
	littleFoo.*posX = 100;
	(littleFoo.*display)();
	

	return 0;
}
mrnutty 761 Senior Poster

If you are on windows, then you can use PlaySound . If not then there might be something similar to your
OS. If all fails, you will have to use a 3rd party library.

mrnutty 761 Senior Poster

When you say it crashes, when does it crash? Do you know at
what line?

Also the cipher you are doing is called ceaser shift cipher.

If you would like to wrap a encoded char to be within 32-126,
then use the modulus operator, although your method looks
like it works but not completely sure.

And also there is no need to convert the char to int and the int back
to char just to add a key to int. You can add the key to char
just like you would to an int. The compiler will implicitly convert
the char to an int during operations that you are performing.

mrnutty 761 Senior Poster

Another thing to add, I feel like you have a lot of redundant coding.
For example, you can implement the operator -() in terms of the
operator +(), instead of providing a definition for each one. Did you feel
like you have copied and pasted a lot of code?

mrnutty 761 Senior Poster

You will have to work with the graphical window, because once you exit
the sdl window, it automatically closes the console window as well. You
might be able to get around this by using win32 but thats another
language you will have to learn.

mrnutty 761 Senior Poster

Whats the general form?

From that example, you can do something like this :

unsigned int var1 = 11;
	long var2 = 5;
	long var3 = 3;
	unsigned int final_var = var1 &0x3;
	final_var <<= 2;
	final_var |= (var2 & 0x01);
	final_var <<= 1;
	final_var |= (var3&0x1);
mrnutty 761 Senior Poster

Can you gives us a picture or something that shows how the output
should be?

mrnutty 761 Senior Poster

So far so good. But you still underuse the second chance. Say, you work your way up with an increment of K. The worst case will give you (N/K) + K comparisons. Which value of K will minimize it?

It is not the best algorithm, but is very close to the best (at least, it gives the right asymptotic behaviour). What's left is (a) to make the increment vary according to the amount of yet untested values, and (b) to prove that it is actually the best.
Good luck.

PS to those who answered before me. The wording of the original problem statement is very confusing. Please reread it carefully. It is a very well-known interview problem, usually formulated as follows:
You are given 2 marbles and a skyscraper. Determine a lowest story, such that marble breaks when dropped from it.
A binary search does not work here.

I wasn't implying full binary search, just a partial binary search.

mrnutty 761 Senior Poster

Just an idea, since the array is ordered. Consider comparing the
mid of the array. If the number X is greater than the mid, then
compare the mid of the top half. Keep this pattern. As soon as you
have failed 2 greater than comparison, then start with the subList thats
being considered and brute force it. That way, the the search
could be in log(n) at worst.