mrnutty 761 Senior Poster

Well this is essentially a transversal problem. You need to verify that
the left child of the parent is less than, and the right child of the parent
has to be greater than the parent. So essentially you will have to
transverse the whole binary tree. Whats the usual transversal, algorithm
that you are use to ? Whats its complexity ?

mrnutty 761 Senior Poster

No you use what someone geniuses already have written for you. It will
be pretty hard to create your own graphics command, that does not
encapsulates other's functions. I would suggest to start with SDL.
This link will be
a good start.

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

Not sure what technique you used, but in comp Sci its usually done
by making the matrix in echelon form and multiplying the diagonal numbers
Nice job though.

mrnutty 761 Senior Poster

>> So it seems i basically just need to reverse the direction it's rotating.

Try reversing the angle its rotating about. Also make it an else if statement.

mrnutty 761 Senior Poster

Hello everyone,

I am trying to understand composition versus inheritance in C++. I have looked at many web pages, but I haven't found anything that makes sense to me. Can someone please tell me where I can find some examples of programs that might make sense to me? I am a beginner and I am looking for an example that is very "beginner friendly".

Thanks!

Remember, prefer composition over inheritance. And usually, when
you inherit something, it can usually be composed in the class instead.

mrnutty 761 Senior Poster

>>i have this rectangle and i want to be able to rotate this shape around another when i press a key.

By default the rectangle rotates around the origin. So if you wan't the
rectangle to rotate around an object, then translate the world x units until the object to be rotated around is at the origin. Then rotate the rectangle. So the rectangle rotates around the origin, which is where the object now resides. After the rotation is done. Translates the world back -x units. This causes the appearance of rotation around shape.

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

Virutal inheritance comes into play when you inherit from two classes
and both of those class inherit from the same base class. Its called
the diamond shape inheritance.

Here is an example :

struct Base{
};
struct A : Base{
};
struct B : Base{
}
struct C : A , B{
}

The struct C has a problem. Namely that struct A and B inherit from
the same base class. This is not good since it will have 1 more base
class than it needs. So to solve this problem, we need to use virtual inheritance.

So :

struct Base{
};
struct A : Base{
};
struct B : Base{
}
struct C : virtual A , virtual B{
}

Now C contains, A, B and Base. Instead of A,B,Base,Base.
Thats the overview of why one would use virtual inheritance. Google
it up for more info.

mrnutty 761 Senior Poster

I don't think thats possible. Obviously, you will have to iterate over all
the elements to reverse the order.

I think the best you can do is : O(log(n))

mrnutty 761 Senior Poster

That's why people shouldn't jump too early into graphics without good
knowledge of the basics. Ball is a function. It is not a class nor a struct.
Thus you cannot use the dot operator on ball.

A easy way to get the ball to move is by doing something like this :

float ballX = 0.0f;
float ballY = 0.0f;
float ballZ = -1.0f;

void drawBall(void) {
        glColor3f(0.0, 1.0, 0.0); //set ball colour
        glTranslatef(ballX,ballY,ballZ; //moving it toward the screen a bit on creation
        glutSolidSphere (0.6, 7, 7); //create ball.
}
void display(){ 
 glClear(...);
 //more stuff
 drawBall();
 //...
 glutSwapBuffer();
}
void keyboard_s (int key, int x, int y)
{
   switch (key)
   {
      case 'a' : ballX -= 0.05f;
      case 'd' : ballX  += 0.05f;
      case 'w' : ballY += 0.05f;
      case 's' : ballY -= 0.05f;
      case 'r' : ballZ += 0.05f;
      case 'f' : ballZ -= 0.05f;
   }

All you its doing there is updating the position of the ball. The ball
gets redrawn every frame, but ballX, ballY , and ballZ might does not
have to be the same at each frame. Thus changing ballX, ballY, ballZ
would change the position of the ball.

And P.S : I would advice you to learn more about classes before you
go to far with this graphics. Trust me, its gonna pay off later.

mrnutty 761 Senior Poster

This link shows the function prototype that pow function takes. Make
sure you match one of the function prototype.

So for example this code :

pow(2,2);

will not work since pow does not overload pow(int,int) . But this any of these will work :

pow(2.0,2.0); 
pow(2.0,2);
pow(2.0f,2.0f);
pow(2.0f,2);
mrnutty 761 Senior Poster

put the "cout << endl; " at the end of the first for loop. So do this :

for(i=1;i<5;i++)
    {
         for( j=1;j<6; j++)
         {
              infile>>random[i][j];
              cout<<random[i][j]<<endl;
         }
              cout<<endl;
    }
mrnutty 761 Senior Poster

i would guess yes.

mrnutty 761 Senior Poster

First correct me in this if I'm wrong.

For sum = 0 , return 0;
For sum = 1 , return 1;
For sum = 2 , return 2;
For sum = 3 , return 3;
For sum = 4 , return 5;
For sum = 5 , return 8;
For sum = 6 , return 13;


It looks like its defined by :

F(n) =
{ 0 if n = 0 }
{ 1 if n = 1 }
{ 2 if n = 2 }
{ F(n-1) + F(n-2) for n > 2 }
{ else not defined }

Thats just a guess.

mrnutty 761 Senior Poster

Do something like this :

int nearSqrt(int num){
 int n = sqrt(num);
 return n*n;
}

That returns the nearest square number. For it to be greater than num,you need to return (n+1)*(n+1);

mrnutty 761 Senior Poster

Get the size of the file first and dynamically allocate an array of that size.
Example :

void read(const std::ifstream file){
 size_t fileSize = 0;
 file.seekg(0,std::ios_base::end); //set the point to the end of the file
 fileSize = file.tellg(); //get the position
 file.seekg(0,std::ios_base::beg); //reset the file to starting point

 float *input = new float[fileSize+1]; //just to be safe we add +1
 //read file and do stuff
 
 delete [] input;
}
mrnutty 761 Senior Poster

Please forgive me, but I don't seem to follow... Could you care to explain more?

1) start a loop
2) ask for input
3) use the switch
4) continue with loop until exit command entered

>>start a loop

while( true ){...}

>>ask for input
ask for input inside while loop
>>use a switch

switch(input) { ... }

4) continue with loop until exit command entered
ask user to continue or not :

cin >> loopAgain; if(loopAgain == 'n') break; else continue;
mrnutty 761 Senior Poster

This code :

cout << "Enter 1 to create an account : ";
 int nEntered;
 cin >> nEntered;
 for(;;)
 {
 if( nEntered == 1)
 {
  BankAccount s;
  cout << " Bank account created\n If you would like to make a deposit press 1";
  break;
 }
 else
 {
  cout << "You didn't enter a vaild number";
 }
 }

is bad already. Try something like this :

bool shouldCreateAccount = true;
cout << "Would you like to create an account<1 = yes, 0 = no >";
cin >> shouldCreateAccount;
if(!shouldCreateAccount) return 0;
else { createAccount(); }
//...

The same with the rest. Why are you using infinite for loops?

mrnutty 761 Senior Poster

use vectors. Here is an example :

#include <iostream>
#include <fstream>
using namespace std;
int main(){
 vector<float> inputValues;
 ifstream file("num.txt");
 while(!file.eof() || !file.fail()){
  float num = 0.0f;
  file >> num;
  inputValues.push_back(num);
 }
}
mrnutty 761 Senior Poster

You access each individual numbers and multiply them :

int Array[2] = {1,1};
int Array2[2] = {5,5};
int result[2] = {};
result[0] = Array[0]*Array2[0];
result[1] = Array[1]*Array2[1];

Of course there is a lot more to this, but you get the basic idea.

mrnutty 761 Senior Poster

Oh read your last post. What you need to use is string.find_first_not_of().
Here is another example :

string romanCharacters = "IVXLCDM";
string str1= "XXIID";
string str2= "21341";
if( str1.find_first_not_of(romanCharacters) == string::npos){
  cout <<str1 << " is roman numerials\n";
}
 else cout << str1 << " is not roman numerials\n";

if(str2.find_first_not_of("0123456789") == string::npos){
 cout << st2 << " is not a number\n";
}
else cout << str2 << " is a number\n";
mrnutty 761 Senior Poster

This :

char array2[arraySize2] ={'A','B','E','F','G','H','J','K','N','O','P','Q','R','S','T','U','W','Y','Z'};
   for (int i = 0 ; i < str.length() ; i ++)
     int b = str.find(array2[i]);

can be replaced with this :

if( str.find_first_of("ABCDEFGHIJKLMNOPQRSTUVWXYZ") == string::npos){
 letter not found.
}

but it seems that you are trying to find the number of occurrence of a
letter right ? If so then what you should is just loop over the string
and count how many letters occur there of certain type.

mrnutty 761 Senior Poster

There are more difference. For instance, when an object gets destroyed,
its destructor is called. Whereas when an object gets destroyed, its
member function might not be called. Also a destructor has no return
type where as an member function could.

Looks like what your confused about is polymorphism. Take a look
at this code :

#include<iostream>
using namespace std;

struct A{ virtual void f(){ cout << "A\n"; } };
struct B : A{  void f(){ cout << "B\n"; } };

void print(A& a){ a.f(); }

int main(){
 A a = A();
 B b = B();
 a.f(); // prints "A";
 b.f(); //prints "B";
 print(a); //prints "A";
 print(b); //prints "B" but prototype expects A
}

a.f() calls its f() function.
b.f() calls its f() function.
print(a) calls a.f().
print(b) calls b.f() even though the prototype expects an object of A.
Thats called polymorphism.

mrnutty 761 Senior Poster

Also don't use magic numbers. Use constants.
For example :

enum FuncReturn{ ALL_DIGITS , INVALID_INPUT };
int myCheck(const string& str){
 if(str.find_first_of("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz") != string::npos) return INVALID_INPUT;
 else if(str.find_first_of("!@#$%^&*()-_+=';[]{}:<>?/.,`~") != string::npos) return INVALID_INPUT;
 else return ALL_DIGITS;
}
int main(){
 FuncReturn f;
 f = myCheck("123123143431a");
 //....
}
mrnutty 761 Senior Poster

>>well, the compiler fortunately didnt complain :-)

No, in fact thats unfortunate.

>>anyway, the advantage of this implementation over the next_permutation in STL is, that you can instantly get the permutation at any index.

The disadvantages is that this is not a safe code. Its a homemade code,
and is likely to fail at some point with some wrong input. Its not as
efficient as the stl...and much more to list.

Generally, one does this for practice, NOT to replace stl's algorithm.

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

Its pretty close. You had the right idea to use a for loop and use isdigit
function. You just didn't do it correctly.

Here are basic steps you can try :

1) Get input into a string
2) Create a for loop from i = 0 to string.length
3) use isdigit inside an if condition inside the for loop
4) if "3" fails then exit the loop and show and error message
5) If the loop does not fail then you have an string with all digits.

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.

mrnutty 761 Senior Poster

what do you think ? Don't you have a compiler ? Whats confusing you ?
So many questions( including yours ) but no answers?

mrnutty 761 Senior Poster

Nope. What you did makes no sense. A char can only contain 1 char.
Use std::string instead.

mrnutty 761 Senior Poster

If your function is write, and it writes to the screen, then just templatized it.

mrnutty 761 Senior Poster

You didn't define a operator+, that takes an int. You only defined
a operator+ that takes another Polynomial.

mrnutty 761 Senior Poster

Just for emphasis, an automatic variable is deleted with it reaches
the end of its block. So for example :

int main(){
  {
      int x = 0;
   } //x is deleted when it reaches this bracket
  
    int x = 3, y = 3
} //x and y is deleted when it reaches this bracket

so as you see, you can use "{ ... }" the bracket to destroy the variable.
But you should try to give each variable unique name and not have to
do that.

mrnutty 761 Senior Poster

>>I don't believe you can call class functions without an object.
It can be done.

#include <iostream>
#include <string>

using namespace std;

struct Print
{
	static void print(string str)
	{
		cout << str << endl;
	}
};

int main(){	
	Print::print("string");
}

But from the looks of it, using a namespace would be a better idea.

mrnutty 761 Senior Poster

>> out<<m.info[i*m.cols+j];

Change to :

out<<m.info[m.rows * i + j];
mrnutty 761 Senior Poster

You need exactly what you said here "std::cout << "Haha, this is a loop";"

You need a loop. Here is an example of for loop.

#include <iostream>
using namespace std;
int main(){
 const int MAXLOOP = 100;
 for(int i = 0; i < MAXLOOP; ++i){ //loop 100 times
  cout << "loop number : " << i << endl;
 }
}
mrnutty 761 Senior Poster

>>info[cols_*row + col];
I don't think this conversion is right. Assuming you are using a 1D array.
Then our 1D array indices is like so :

0 1 2
3 4 5
6 7 8
9 10 11

Your conversion equation is " row*col+col ". Say we call matrix(1,1);
That should return the value stored at 4 right? But your equation says
that row*col + col == 1*1+1 = 2. which is not 4, as you need it to be.

A correct conversion function would be :

int& Matrix::operator() (unsigned row, unsigned col)
 {
   if (row < rows_ && col < cols_)
      return info[rows_ * row + col];
  else return -1;
 }

In the above code rows_ should be a const number of rows that the
matrix has. Also notice how the if statement changed. If the rows and columns index are less that the max number of rows and columns then
we return some value.

mrnutty 761 Senior Poster

In my c++ book it shows how to do it differently. I'll just post that up to so the person who asked can have more options in choosing what he wants to do.

I'll use an example to explain it.
Suppose you want to display num which stands for 4.91877 .
To display the number normally, you would just do:

cout << num;

To display it with only four decimals, you would do this:

cout << setprecision(4) << num;

To display it with only 3 decimals, you would do this:

cout << setprecision(3) << num;

Like this, you would display the number with 2 decimals and 1 decimal.

To use the setprecsion(4), you have to include<iomanip>.
Another option is to use cout.precision. For example :

const float PI = 3.14159265;
cout << PI << endl; //show with default precision
cout.precision(4);
cout << PI << endl; //shows with 4 digit precision
mrnutty 761 Senior Poster

Nope. That's the limitation of the linked list. You need to transverse the
list to get to a node. Whereas with arrays, you can access the data by
indexing. But using linked list, you can delete and insert element very fast,
O(1) to be exact.

mrnutty 761 Senior Poster

>>Won't work. Try it with an input of 321.

Actually, I was under the impression that he wanted to get 3 numbers
from the user. I guess I misread his post.

mrnutty 761 Senior Poster

Close but you still did not need to program for this problem.

We have this wonderful formula :

Fib(n) = round( Phi^n/√5)


We can manipulate the above equation to get the number of digit we are looking for by using logarithm.


Fib(n) = log( phi^n / phi(√5) )

Lets denote Fib(n) to be X, the number of digit we are looking for,
then we have :

x = log( phi^n / phi(√5) )

x = log(phi^n) - log(√5)

x = n*log(phi) - 0.5*log(5)

( x + 0.5*log(5) ) / log(phi) = n

Thus we have a formula for n :

n = ( x + 0.5*log(5) ) / log(phi)

Now we want to digit to be 1000. But in the original equation
we have the round function. So to cancel that out, we subtract
1 from the input x and ceil our final equation.
Thus our final equation is :

n = ceil ( ( (x - 1) + 0.5*log(5) ) / log(phi) )

Now plugging x = 1000 and phi = 1.618, we get :

n = 4782.

mrnutty 761 Senior Poster

>>can someone show me an example of how you would initiate a variable.

int variable = 0; //declare and initialize the variables

>>how you would fix a undeclaired identifiers.

an undeclaried identifier means that you used a variables that has not
been declared. For example :

int n = 1;
int m = 2;
sum = n + m; //error indeclared identifier

The way to solve this problem is to declare the variable. In the above
code, you need to declare the variable sum. So the correct code should be :

int n = 1;
int m = 2;
int sum = n + m; //notice the "int sum" part. Thats the declaring the variable part.
mrnutty 761 Senior Poster

>>I want to my program to prompt user to input a number with three or more integers

You know how to get the user input into a variable right ?

int var1 = 0 , var2 = 0, var3 = 0;
cin >> var1 >> var2 >> var3; //get 3 inputs from the user

>>I need the program to output a space between each numebr

You know how to output numbers to the screen dont you?

cout << 1; //output the number 1
cout << " "; //output the string space
cout << 2 << " "; //output the number and put a space after the number

>>then i also need to output the sum of these number so 3+3+3+4?

You know how to add the variables dont you ?

int var1 = 0, int var2 = 0, int var3 = 0; //create variables
cin >> var1 >> var2 >> var3; //get inputs

int sum = var1 + var2 + var3; //add the results

//print the sum
cout << var1 << " + " << var2 << " + " << var3 << " = " << result;

Next time just take it part by part and try the problem.

mrnutty 761 Senior Poster

Yep, I think you need to include sstream as well. stringstream is
defined in the sstream header file.

caffeine commented: Thank you for being patient with my dumb question! +1
mrnutty 761 Senior Poster

Are you using opengl and glut ?

mrnutty 761 Senior Poster

whats your definition of symbol?

mrnutty 761 Senior Poster

Most likely, you did not initialize your variables. Also you probably might be
writing into memory that you are not supposed to. Because, in debug, the
compiler pads the memory more than in release.

mrnutty 761 Senior Poster
void turn_it_is(int play1, int play2)
{
    cout << (((turn_it_is%2)==1)?(play1:play2));
    cout <<  " it's your turn ";
    cin >> turn_it_is;
}

What are you doing? "turn_it_is" is a function. Not a variable!. Why
are you trying to use cin >> turn_it_is ? and also why are you trying to
use the modulus operator with the function name ? Did you make a
global variable called turn_it_is or something ?