mrnutty 761 Senior Poster

>> if((s3=="Y" || "y"))]

You want if(s3 == "Y" || s3 == "y") or if(s3.find("yY") != string::npos) or if(tolower(s3[0]) == 'y')

mrnutty 761 Senior Poster

Problem question: Given the sequence A and B, where A is the inorder traversal value and B is the pre-order traversal value, reconstruct the binary tree that produces such results when performing inorder and pre-order traversal on that binary tree. To reconstruct the binary tree you can simply print the breadth-first traversal of the reconstructed tree. You can assume that the size of A and B is 2n+1, that is, its a complete and full binary tree.


Example :

input:
A = 1 2 3 4 5 6 7 #in order traversal
B = 4 2 1 3 6 5 7 #pre order traversal

output:

Bredth-first tree: 4 2 6 1 3 5 7.


Note the tree looked like :

4
   / \
  2   6
 /\  /\
1 3  5 7

Bonus: For fast implementation in terms of speed and memory!

mrnutty 761 Senior Poster

You need to take into account the margin and padding as well.

mrnutty 761 Senior Poster

You should need to pace yourself. First learn concepts of programming. Get a good grasp of it. Learn's the ins and outs of one programming language. Learn about data structure. Learn about algorithms. Practice more and more. Then once you feel you have gotten a good grasp, then do some simple 2D graphical program. Use SDL. Its easy to learn and comprehend. Learning directX right of the back is hard because there is so much stuff you need to do before you get your first triangle application up. So start slow and steady. Don't just jump into something complicated, gradually take it step by step and before you know it, it will all make sense to you. Good Luck. Come here for help if you need to.

mrnutty 761 Senior Poster

Yes possible. You will constantly have to monitor the keypress of your computer and on a certain combination key pressed, you can positioned the mouse to some absolute coordinate.

mrnutty 761 Senior Poster

how about just "abcdefghijklmnopqrstuvwxyz"? Its minimal as possible. And it could be considered as a sentence if you add a period at the end.

mrnutty 761 Senior Poster

1) typeid(type) does not return a unique object in all cases. You might want to combine (typeid(type).name(),instanceNumber) as a key.

2) typeid(type) is not unique

3) HashTable

mrnutty 761 Senior Poster

What will knowing that data structure FB used will help you in anyway? If you have a problem of picking which data structure to use, then either post it here or compare the pro's and con's of each data structure and pick the one that best suites the problem. They don't use some magical data structure that no one knows. Most data structures are based on the basic ones like trees,arrays,list.... so get to know the fundamentals first.

mrnutty 761 Senior Poster

Please clarify more.

mrnutty 761 Senior Poster

First figure out how to reverse one word, ex [hello] --> [olleh]. Then go on from there. There are many ways you can achieve this. Why don't you give it a try and come back if you have problem.

mrnutty 761 Senior Poster

The compiler will compile only relavant portion of the code. If you change Y and X depends on Y, then Y and X will get compiled and all files that depends on X will get compiled. If you want to reduce your compile time, you may want to take a look at http://c2.com/cgi/wiki?PimplIdiom and other search results.

mrnutty 761 Senior Poster

What problem are you having? Maybe a simple example will get you started. A simple multiplication table.

#include <iostream>
using namespace std;

int main(){
 const int MAX = 5;
 //show row metadata
 cout << "\t";
 for(int n = 0; n < MAX; ++n){
   cout << n << "\t";
 }
 cout << endl;
 for(int i = 0; i < MAX; ++i) cout << "\t--";

 for(int i = 0; i < MAX; ++i)
 {
  cout << endl;
  cout << i << "|\t";
  for(int j = 0; j < MAX; ++j){
      cout << i * j << "\t";
  }
  cout << endl;
 }
}
mrnutty 761 Senior Poster

Note that although a greedy approach to this problem is optimal, its not a general solution to an optimal solution for all coins. For a general optimal solution, one can use dynamic programming.

mrnutty 761 Senior Poster

opps its late, I need some sleep, it will run as much as it needs to. My mistake

mrnutty 761 Senior Poster

>>actually the loop is infinite but the return makes it leave the function thus ending the program

Actually that loop will never run in the first place because "1 is never equal to 2".

mrnutty 761 Senior Poster

despite the infinite loop at the end of main().

Actually, its finite, the condition is infinite, but this doesn't necessarily mean the loop is infinite.

The same code but more OOP style:

#include <iostream>
#include <string>

class Application{
private:
 std::string title;
public:
 Application(){}
 Application(const std::string& titleName) : title(titleName){}
 virtual void run() = 0;
 virtual void stop() = 0;
 virtual int exit() = 0;
 const std::string& name()const{ return title; }
 virtual ~Application(){}
};

class MainApplication : public Application{
public:
 MainApplication(): Application(){}
 MainApplication(const std::string& title): Application(title){}
 void run(){ std::cout << Application::name() << endl; }
 void stop(){ }
 int exit(){ return 0; }
};

int main(){
 MainApplication app("hello world");
 app.run();
 return app.exit();
}
mrnutty 761 Senior Poster

See the difference between the two:

//in .h
void inorder(nodeType *p) const;
void preorder(nodeType *p) const;
void postorder(nodeType *p) const;
//in main
b.inorder();
b.preorder();
b.postorder();
mrnutty 761 Senior Poster

remove the 'struct' word in line 4

mrnutty 761 Senior Poster

For P2 its easy to come up with a O(n*m) \in O(n^2) solution, but can you come up with a linear time algorithm, possibly in O(n+m), where n is the length of the p and m is the length of q?

mrnutty 761 Senior Poster

You can use a counter to count how many characters has been printed already and see if the counter is the split number. For example

int counter = 0;
int splitPoint  = 2; 

string str = "hello";
string rev = "olleh";

for each character in rev
   if startPoint == splitPoint print space and set startPoint to 0
   print current character rev[i]
   startPoint = startPoint + 1; 
endFor
mrnutty 761 Senior Poster

Reverse the whole string( ex [hello] -> [olleh] ) then split the result into pairs( ex split pair of 2 [olleh] -> [ol le h]). If you are just outputting it, then output a space at every split position.

mrnutty 761 Senior Poster

>>Why are programming languages dissimilar even if they go after the similar compilation procedure?

Maybe a simple answer is that, people weren't satisfied with the current programming language, hence tried to build a "stronger" and more expressive language; this caused the variation of tools to be created.

mrnutty 761 Senior Poster

Put training1 definition above training2 definition. Also put a "return 0;" in the last line in main. Also use "#include<iostream>" not #include <iostream.h>"

mrnutty 761 Senior Poster

This is completely not true.

For the most part it should be, especially judging from @OP's post, I wouldn't expect him to be doing any problem that hasn't been solved or has a variant of the solution he needs.

mrnutty 761 Senior Poster

All algorithm you need to know are usually already implemented efficiently by the libraries or some other well known vendors. Your job should be to efficiently use them to complete your project and increase your productivity. Of course this doesn't mean you shouldn't know that basic concepts, like sorting, trees, hashing, dynamic programming, greedy programming and possibly linear programming.

mrnutty 761 Senior Poster

Sure. First realize that Menu's can be recursive, that is you can have menues inside menus. For example, you can have a top level menu called, Clothes which contains sub-menus like sports clothes or winter clothes. Noticing this recursive structure, might hint that a tree implementation might be a natural choice. Noting the above, here is some idea to go by.

struct Menu{
 std::string name; //could be menu name or a item name
 std::vector<Menu> subMenus;
Menu(const std::string& name, const std::vector<Menu> subMenus): name(name), subMenus(subMenus){}
 void add(const Menu& m){ subMenus.push_back(m); }
};

class SportsClothingMenu{
private:
 Menu sportsClothingMenu;
public:
 SportsClothingMenu(){}
private:
 void _populate(){
        Menu soccerClothesMenu("soccer");
        //...add soccor clothes to soccerClothesMenu
        sportsClothingMenu.add( soccerClothesMenu );
  }
}

Note that we know a menu is a leaf if it has no children, so in the above case if subMenu.empty() is true. You should be able to take it from there. There is no real need to use pointers here. Using std::vector will suffice.

Interista commented: Ur a Champion +0
mrnutty 761 Senior Poster
div = num1 / num2;    
            remainder = num1 % num2;

1)Let num1 = 6 and num2 = 3. Then div = 6/3 = 2. and the remainder 6%3 = 0.
2)

if (num1 < num2)
            {
               div = num1;
               num1 = num2;
               num2 = div;
            }

This is irrelevant in the above case since num1 > num2. So its skipped.

3)

while(remainder != 0)
            {
               div = num1 / num2;
               remainder = num1 % num2;
               num1 = num2;
               num2 = remainder;
            }
            num2 = GCD;

Since remainder is 0, this won't get executed and num2 is set to GCD which you haven't defined, so it will be 0. You see your problem?

mrnutty 761 Senior Poster

This int zero(float); has to match this int zero(float a[9][13]) . Same goes for the rest.

mrnutty 761 Senior Poster

The idea is simple once you know it. You need to store the diff values into hash, in order to get it in linear time*.

Here is the idea:

1) Combine S1 and S2, call it S
2) For each element in S, check if the difference is in the hash table
3) If it is, then output the match else keep processing.

Example:

A = {1,2,4}
X = 5;
HashTable = {}

//step 2

i = 1
key = 1, diffValue = 5 - 1 = 4
is diffValue a key in HashTable?
false so insert: HashTable = { (1,4) }
i = 2
key = 2, diffValue = 5 - 2 = 3
isdiffValue a key in HashTable?
false so insert: HashTable = { (1,4), (2,3) }
i = 3
key = 3, diffValue = 5 - 3 = 2
isdiffValue a key in HashTable?
true so output: {(2,3)}

no more iteration.


However there is a catch to the above algorithm.
1) It does not handle the case where target value is 2 times the diff value. You need to fix that
2) Hashing is at worst linear time in theory. So that still makes it O(n^2) in theory
But its possible to make the hashing O(1) because its a sequence of number and we can achieve perfect hashing. So you will have to assume that to assume linear time solution.

mrnutty 761 Senior Poster

firstPerson, that code you wrote is mind blowing to me.
I would never have thought of using a second for loop to check the input before assigning the input into the array.

maybe because this is my first programming class, but now you've given me a brand new outlook on how to write future code.

THANK YOU

I'm glad it helped. Good Luck.

mrnutty 761 Senior Poster

I am looking for a simple example that uses link list to implement hash table so that I can better understand hash table.

Is this homework? Or just a learning project?

mrnutty 761 Senior Poster

Your code is hard to read but your problem is in line 15, your using the array and it hasn't event been initialized it. Usually when you use an array, you you use hardcoded index when you want to access all values. What you are looking for is something like so:

int main(){
 const int size = 4;
 int values[size] = {0}; //set all values to 0;
 for(int i = 0; i < size; ++i){
     int input = 0;
     cin >> input; //get user input
     //check if it matches any previously inputted values
      bool isUnique = true;
     for(int j = i - 1; j >= 0; --j){
           if(input == values[j]){ //if current value is equal to the newly inputted value
               isUnique = false; //set state to false
               break;     //exit out of this for loop;
           }
     }
    if(isUnique){ //if is unique, save it
         values[i] = input; 
     } else{
            cout << "\nError value is not unique\n";
            //reset counter
             --i;
     }
 }
}
babyhuyx commented: Amazing, Very Helpful, totally opened my mind to new way of coding +1
mrnutty 761 Senior Poster

wiki is always a good starting point. What exactly is troubling you?

mrnutty 761 Senior Poster

Windows OS. Its a project actually. So its going to be portable, im using visual studio 2010

If thats the case, then you will need a way to create a new process and run a needed application. You can use boost libraries to create new process( I think its portable ), and when creating the new process , you will need to make sure the correct application gets opened.

On a easier note, maybe something tedious like this:

#ifdef _WIN32
 #include <cstdlib>
 #define SystemCmd System
 #define TextFileEditor "notepad"
#elseif defined ___linux
 #define SystemCmd system
 #define TextFileEditor "gedit"
#endif

#include <string>
using namespace std;

int main(int argv, char *argv[]){
   if(argv > 1){
       const char *filePath = argv[1];
       if(isTextFile( filePath) ){
          string textFileCmd = "./" + TextFileEditor + " " + filePath;
          SystemCmd( textFileCmd );
       }
       //else if...
   }

  return 0;
}

But note that SystemCmd is not a good way to go about it, because of security issues and its blocking nature. See system for windows for an example.

mrnutty 761 Senior Poster

What OS are you running for? Does it need to be portable or just a simple home application?

mrnutty 761 Senior Poster

I think what you want to see is if the combination of (r,s,d) results in some winning combination? Is that correct. For example if R = $ and S = $ and D = $, then you would win some large amount? If so then you can simply do something like this:

for (char i = 0; i < 3; ++i) 
{ 
        char r  = rand() % 3;
        char s  = rand() % 3;
        char d  = rand() % 3;
 
        cout << "___ ___ ___\n";
        cout << " "<<sign[r]<< " | " << sign[s] << " | " << sign[d] << " | " << "\n"; 
        cout << "___|___|___|\n";

         if(r == s && s == d && d == '$') { //if r = $ and s = $ and d = $
              cout << "JACKPOT!!!!\n";
         }else if(r == s && s == d && d == 'X'){ // if r == X and s == X and d == X
              cout << "You won $500 \n";
        }else if(r == s && s == d && d == 'O') //  if r == O and s == O and d == O
              cout << "You won $100 \n";
        } else{
              cout << "You won nothing :(\n";
        }
}

You can create a function to automate and remove the redundancy if you need to.

mrnutty 761 Senior Poster

Not sure if its clear what you want to do. Do you want to write a C++ program where it takes a file path to a image or music and opens the file using appropriate application like ms-paint for images or windows media player for music? Or do you want the C++ program to take in a filePath like a music and play it using your own functions and code?

mrnutty 761 Senior Poster

>>Polish a turd and it's still a turd.

But its a cleaner turd? Anyways, who wants to touch a turd anyways, grosss lol.


As per the application of bubble-sort, the only place I seen it was in my introductory course. But even then I don't know if that is really a good idea. The one time I would show bubble sort is to demonstrate how not to write algorithms, or use it as a leeway to implement a better one.

mrnutty 761 Senior Poster

>>Weird and redundant, isn't it?

For now yes, but if you guys decide to not use "_T" then you can simply change the macro definition instead of changing the code a whole lot for accommodate the new type.

mrnutty 761 Senior Poster
class Pdisk
{
public :
	Pdisk(string diskname, int numberofblocks, int blocksize);
        Pdisk(): numberofblocks(0), blocksize(0){} //default ctor
private :
	string diskname;
	int numberofblocks; 
	int blocksize;  
};
mrnutty 761 Senior Poster

An example:

#include <ctime>
#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

int getRandom(){ return rand() % 500; } 

int main(){
 srand(time(0)); //seed random number function
 int size = 0;
 cout << "Enter size: ";
 cin >> size;
 
 std::vector<int> data(size,0); // contains size number of 0's
  
 std::generate(data.begin(), data.end(), getRandom ); //fill vector with random numbers from [0,500)
}
mrnutty 761 Senior Poster

>>How are you supposed to deal with teachers that are no longer hired?

You would presumably have a function to fire teacher:

class Department
{
private:
    Teacher *m_pcTeacher; // This dept holds only one teacher
public:
    Department(Teacher *pcTeacher=NULL)
        : m_pcTeacher(pcTeacher)
    {
    }
  void fireTeacher(const Teacher* t){ 
     if( t == pcTeacher){  //if you know teacher has a unique value, say SocialSecurityId, then you can delete it based on that or other criteria. 
         pcTeacher = 0; 
    } 
  }
};

>>You will have tons of dynamically allocated teachers. How do you manage all of them

You manage them with a container that represents a list of teachers

>>if i had done regular class composition this wouldn't have been a problem correct and only 1 class would be needed?

Think of composition as representing a list of object as a whole. For example, you can think of a class called Car as a whole, even though it has different objects in it like, tires, body...etc. But you still treat the Car as a whole, removing the car, repairing the car, selling the car and so on.

Conceptually, in that example, it makes more sense to remove teachers one by one. Certain teachers stays, others gets fired, although it may be possible, if the Department declared bankruptcy then all teachers would be removed.

mrnutty 761 Senior Poster

How is the graph constructed? Presuamably you should have an edge going from Node_i to Node_j, if permitted. Where is your edges?


EDIT:

Or is your 2D Array the graph it self, for example:

e1 e2 e3
e1 1   0   1
e2 0   1   0
e3 1   1   1

what that graph, we can say that e1 can goto e1 and e3, e2 can got to e2, and e3 can go to e1,e2,and e3. Is that how you are interpreting the grap?

mrnutty 761 Senior Poster

once you do it manually, you'll learn to use the standard algorithm for this std::count(test.begin(),test.end(),'t')

mrnutty 761 Senior Poster

when your dead you'll know. tell us about it

mrnutty 761 Senior Poster

Having a scoring function on words, means having heuristic. Need to know what the problem is? Do you want more occurring words to having higher weight? Do you want longer length words to have higher weights? Do you want words that have vowels to have higher weights? You see you objective function depends on your objective. So what is your objective?

mrnutty 761 Senior Poster

I'm not sure what exactly you want. Do you want to extract each NodeArray into its own array?

mrnutty 761 Senior Poster

You need to make sure that it maintains a heap structure, that is the highest priority( or the lowest) is constantly at the top. So whenever a user inserts or deletes a node, you still need to maintain that property. There are several ways of doing this, check here for details.

mrnutty 761 Senior Poster

If you have something like a factory pattern then you can enforce it, for example:

class CandyFactory{
 private:
  struct ChoclateBar(){ 
        int calories; 
        ChoclateBar(): calories(){}
   };
 public:
  shared_ptr<ChoclateBar> makeChoclateBar(){
       return shared_ptr( new ChoclateBar() )
  }
};

I don't know if thats what you were asking?

mrnutty 761 Senior Poster

>>getline(cin, first_sphere[3]);
You want: cin >> first_sphere[0] >> first_sphere[1] >> first_sphere[2] Also as suggested, move this code

float RadiusofTwoSpheres(float *sphere1, float *sphere2);
	{
		cout << "The Radius for Sphere's 1 and 2 is... " << endl;
		cout << endl;
		cout << "R = " << (float)sqrt(pow(sphere2[0] - sphere1[0], 2) + pow(sphere2[1] - sphere1[1], 2) + pow(sphere2[2] - sphere1[2], 2)) << endl;
	};

before int main(){}

Zvjezdan23 commented: Thank You so much for helping me. =) +0