mrnutty 761 Senior Poster

Given we are at position (x,y) in a 2d Cell environment, its neighbors are

N[x][y+1]
N{x+1][y+1]
N[x+1][y]
N[x+1][y-1]
N[x][y-1]
N[x-1][y-1]
N[x-1][y]
N[x-1][y+1]

that assumes that the position (x,y) are not in the edge of the Array

mrnutty 761 Senior Poster

whats the error? post exactly

mrnutty 761 Senior Poster

@op you are just having syntax issues. For your case to make a proper switch statement, you need to add the braces. Here is an example:

#include <iostream>
using namespace std;

int main()
{

  int test = 1;

  switch(test)
 {  
   case 0 : cout << "Option 0\n"; break;
   case 1: cout << "Option 1\n"; break;
 }

 return 0;
}

Notice the keyword "break". That tells the compiler that if it reaches that case, then evaluate that case and then break out of the switch statement. If you do not break out of the switch statement, then the next subsequent case statement will be evaluated.

mrnutty 761 Senior Poster

Well just giving it a try shows that it becomes "X", with quotes.

When you write ""string"", it doesn't make sense syntax wise because the first double-quote gets matched with the next double quote, and so on. Hence ""string"", gets interpreted as a empty string, followed by the identifier with name string, followed by another empty string. In your second example, you tell the interpreted to use the double-quote as a literal character and not a special character, hence "\"string\"", gets interpreted as a string which contains a double-quote followed by the characters in string, then followed by a literal double-quote.

mrnutty 761 Senior Poster

Let me see. For example in this snippet you failed to show the includes

#ifndef SLOTMACHINECLASS_H
#define SLOTMACHINECLASS_H

class slotMachineClass{
    public:
        int switchToMoney(int x);
        void playSlots(moneySystem& a, energySystem& b, slotMachineClass& c, lotterySystem &d); //error: 'lotterySystem' has not been declared.
};

#endif // SLOTMACHINECLASS_H
mrnutty 761 Senior Poster

In your main, do you include the needed files? What is the exact error? Make sure, wherever you get an undeclared error, you include the proper files?

mrnutty 761 Senior Poster

1 is false. Try using the value x = 1.1
There is no restriction that the numbers must be integers for question 1.

I see a lot of people attacking you. But rather than saying you don't know what you are talking about,I will assume the question wasn't clearly stated to you and so I would like to explain why #1 is true. Its all in the wording. So this is question #1.

1) for all x E Z: if x^(squared) - 5x + 6 = 0, then x > 1 and x < 4.

In English words it is read as follows, for all values x in Z, if the value x^2 - 5x + 6 equals 0, then x has to be in between 1 and 4. Notice that it first needs to satisfy the equation x^2 - 5x + 6 first. And if it does, then it says that x has to be withing 1 and 4, exclusively. So lets see if this is true.

First we need to see what values of x satisfies the equation y(x) = x^2 - 5x + 6. We can reformulate the above equation as, y(x) = (x-3)(x-2) = 0. And we can instantly see that x = 3 and x = 2 is a solution. Hence if we plug-in x = 3 or x = 2, in y(x) we get the result y(x) = 0 for x = 3 or x = 2.

And now we check …

mrnutty 761 Senior Poster

Yes I think Visual studio 2010 has it

mrnutty 761 Senior Poster

No you can't compare imaginary and real numbers like that. #2 and #3 are both false. And #1 and #4 are true.

@OP, can you first show that 1 and 4 are true? Then show that 2 and 3 are false.

mrnutty 761 Senior Poster

If he's lucky. More likely is that his instructor will go through the gamut of lower level and error prone C-style solutions, and only mention the "STL" in passing.

Haha. When I took my first C++ class, we dealt with arrays extensively, 2-3 weeks. And towards, the end he introduces vectors for like 20 minutes of the last class. But I have to say, I learned a lot more this way.

mrnutty 761 Senior Poster

On one side, the more purist side, people argue that, by definition, the reference that is returned by the non-const indexing of any STL container is not required to be T& , it is only required to be of the type std::vector<T>::reference which may or may not be T& . Just like random-access iterator is not required to be T* (but it could), the only requirement is that it acts in a way that is similar to a T* . Technically speaking, they are right. Just like you cannot assume that std::vector<T>::iterator is a pointer T* , you are not supposed to assume that std::vector<T>::reference is a reference T& . The purist argument is also that you can easily deal with the various possible iterators (through templates) and that good C++ code should do the same with references. The problem is that iterator types are well defined in terms of valid expressions (Concepts) and iterator-traits, but references are not, and in the absence of specification about the expected behaviour of the std::vector<T>::reference type, the user is forced to assume that it is just a typedef for T& .

That, I guess is technically correct. I haven't thought about it that way. Thanks for the realization.

mrnutty 761 Senior Poster

Consider using enums or contants for direction. For example:

#include <iostream>

enum Direction{WEST,NORTH,EAST,SOUTH};

//assumes proper ordering, WEST = 0, NORTH = 1, EAST = 2, SOUTH = 3
string showDirection(const Direction& d){
 const string encoding[] = {"WEST","NORTH","EAST","SOUTH"};
 return encoding[d];
}
int main(){
 Direction currentDirection = WEST;
 cout << showDirection(currentDirection);
 return 0;
}
mrnutty 761 Senior Poster

Why is that firstPerson?

I draw my reasons from experience and not necessarily from its design. For example, when I was working under my professor, I had to read in a DNA matrix, which consisted on 0's and 1's. So naturally, I thought to use vector of bools since it was natural thinking for me. But as I start implementing the program, I realize that using vector of bools instead of just vector of unsigned chars was a bad idea. I had difficulty using the vector-of-boolean interface. For example, you would expect operator[] to return a l-value reference where you could assign a r-value to it. But it turns out that std::vector<bool> uses some proxy where it doesn't work as you think it does. At the end I seen really no gain by using vector-of-bool. Sure memory was optimized, but for my that wasn't really a problem. I can tell you that I got more than about 50% performance increase by using vector of unsigned char than vector of bools. Anyways, from now on, I would rather not use vector of booleans, unless someone can show a good reason in a reasonable situation where it would be better than using a regular vector or even std::bitset.

mrnutty 761 Senior Poster

He did, in the first post.

Oh i see, your right. Anyways, as suggested, inserting the median would produce the most optimal tree for that case. I don't see why OP cannot do that.

mrnutty 761 Senior Poster

What happens when you insert a sorted sequence of items into a binary search tree?

Thats the thing though, who says his items are being inserted in sorted order? Wouldn't insertion for him be just be 'as random'?

mrnutty 761 Senior Poster

>> for example, as part of a bitfield or specializations of STL containers such as std::vector which will result in requiring only 1 bit per bool variable

In my opinion, I think this was a bad idea implementing a specialized version for vector of bools.

mrnutty 761 Senior Poster

If you can suffer the extra storage cost while building the tree, place all of the pointers into an array initially, shuffle the array randomly, then do the insertion:

{
    std::vector<mesh_t> v(62500);

    std::fill_n(v.begin(), v.size(), next_mesh());
    std::random_shuffle(v.begin(), v.end());

    for (auto mesh : v)
        tree.add(mesh);
}

Given a basic binary search tree, your best bet is simply to ensure that the items are inserted in a reasonably random order. This produces the average case of a well (if not ideally) balanced tree.

I really don't know if thats a better solution than just inserting it into a tree, unless I missed something.
If OP really wants to do operations before insert, then sort the mesh by some comparison, then start adding the median into the tree one by one.

Another thought is how about using std::map? Its usually created via red-black trees, which has good balancing.

mrnutty 761 Senior Poster

A converse of a statement P->Q is Q->P, although it does not necessarily make it true. So all you have to do is change the P and Q position. Your answer looks correct

mrnutty 761 Senior Poster

A bool can be thought of as an int with a range 0f 0 to 255. As such a 0 means false and anything else is true.

This is wrong. You shouldn't think of boolean data types as a integer with a range of 0-255. A boolean datatype usually consist of 1-bit. The bit can be 0 or 1. Zero equals false, and One equals true. So think of boolean as only true or false value. By design, the value 0 represents false, and anything else represents true.

mrnutty 761 Senior Poster

Idk if this works but maybe try out using this algebra:

1/9 = 0.1111....
9 * 1/9 = 9 * 0.1111
1 = 0.999....

See if you get similar result on a computer.

mrnutty 761 Senior Poster

Initially, I'd go with the C language. Because of its lacking of type-safety, there are many ways to hack a C program, or shall I say more opportunities. Also note that, C is meant to be a subset of C++, so you do you Security Analysis using C++ as well.

mrnutty 761 Senior Poster

Its up to you, you can scan through a instance of '+' and assert that there are numbers in the left and right of it, and the same for '*'. Try looking into 'postfix' as well.

mrnutty 761 Senior Poster

I am using std::stack. I ended up copying the stack content. It is for an assignment. I think the point is to make us aware that this is a problem.

Thanks for confirming I would need to copy!

ok, cool beans then

mrnutty 761 Senior Poster

If you are using std::stack, then there isn't any concept of iterators for std::stack, which makes sense.

As for your question, you can copy the stack content if needed. But it looks like you shouldn't be using stack in the first place?

mrnutty 761 Senior Poster

Easy way is to use std::string

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main(){
 std::string input;
 cin >> input;
 for(int i = 0; i < input.size(); ++i) {
    cout << input[i] << endl;
 }

  //sort it 
  std::sort( input.begin(), input.end());
  cout << input << endl;

}
WaltP commented: You've got to be kidding!! -4
mrnutty 761 Senior Poster

Something you can try,

1) Create tokens from data, are garu suggested.
2) Insert those tokens into a vector
3) Call std::partition on the vector giving it your own comparison
3.a) You own comparison, could return true if the token is digit, thus separating digits from strings
4) From there you can proceed to go on further

mrnutty 761 Senior Poster

>> cin >> a >> b >> read_hw(cin, homework);

that essentially turns into cin >> cin which doesn't make sense. I agree, for your function, read_hw you should make it void. Enabling syntax such as read_hw(cin,homework) >> a >> b is obfuscated.

Just think read_hw as a regular function and call it as a regular function in its own statement. Don't try to use the returned value as there is no need. A better approach would be this :

#include <iostream>
#include <cstdlib>
#include <iostream>
#include <vector>

using namespace std;

istream& operator >>(istream& in, vector<double>& hw)
{
    if (in)
    {
        // get rid of previous contents
        hw.clear();
        // read homework grade
        double x;
        while (in >> x)
            hw.push_back(x);
        // clear the stream so that input will work for the next student
        in.clear();
    }
    return in;
}

int main()
{
    double a, b;
    vector<double> homework;
    cin >> a >> b >> homework;

    cin.get();
    return 0;
}
mrnutty 761 Senior Poster

What ^she^ said... with an emphasis on " All this implies is that you've ignored the more useful parts of the standard library for far too long."

mrnutty 761 Senior Poster

Yes If you are allowed to use STL's list, then list<account> listOfAccounts will do

mrnutty 761 Senior Poster

Oh right, you need to seed first.

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

using namespace std;

int main(int argc, char *argv[])
{
    srand( time(0) ); //seed

    cout<<"Current Car Pool Riders/Drivers\n";
    cout<<endl;
    cout<<"Monday - Nathan\n";
    cout<<"Tuesday - Jimmy\n";
    cout<<"Wednesday - Cochran\n";
    cout<<"Thursday - Harris\n";
    cout<<endl;
    vector< string > drivers;
    drivers.push_back("Jimmy");
    drivers.push_back("Nathan");
    drivers.push_back("Cochran");
    drivers.push_back("Harris");
 
    std::random_shuffle( drivers.begin(), drivers.end() );
 
    string pick = drivers[0];
    cout<<"The Person Driving this Friday is - " << pick << endl;
    cout<<endl;
 
    system("PAUSE");
    return EXIT_SUCCESS;
}
NetJunkie commented: Worked like a charm :) +3
mrnutty 761 Senior Poster

If its to learn C++, then I suggest you to do this.

1) In a file list all of the participants name
2) From your program, read/store the participants name
3) Pick a random name and output

It will be easier if your program just shows the random person's name instead of having the user enter 'Go'

Alternatively, if you don't have a lot of names, then it might be easier to hard-code the names in a vector. And then shuffle it and pick a random name. Judging from your post it looks like you only have a few names. In that case, it might be easier to do hardcode it.

Here is a sample code that you can work with.

#include <iostream>
#include <algorithm> //to randomly shuffle
#include <vector> //our container
#include <string>
using namespace std;

int main(){
  vector< string > fruits;
  fruits.push_back("apple"); //add a fruit to our container
  fruits.push_back("orange");
  fruits.push_back("pear");

  //randomly shuffle the vector
  std::random_shuffle( fruits.begin(), fruits.end() ); //reorders the container in random order
  
  string pick = fruits[0]; //pick the first element, could be any since the container was 'shuffled'
 cout << "Today, you should eat " << pick << " for breakfast " << endl;

 return 0;
}
mrnutty 761 Senior Poster

The "<T>" just means its not a specialized for any types, hence applies to all instance. The "os" and "s"
are just object parameter.

mrnutty 761 Senior Poster

what compiler are you using? I think the original might be a valid syntax. Either way report it to your instructor

mrnutty 761 Senior Poster

Does this mean the h file must be in the same project?

Thanks for the help with the syntax.

No doesn't have to be in the same project, its just that usually people separate the class interface from its implementation in different files. If the class is templatized then as of right now you cannot seperate the interface from the implementation into multiple files. The header file( .h ) can be any where as long as you link it properly.

mrnutty 761 Senior Poster

Check this out

mrnutty 761 Senior Poster

This right here

friend ostream& operator<< <T>(ostream& os, const List<T>& s);

is invalid syntax. It should be

friend ostream& operator<< (ostream& os, const List<T>& s);

Also make sure your implementation of the List is in the same file as the definition, since its templatized.

mrnutty 761 Senior Poster

If your trying to implement copying files then you can do something like this.

int main(){
 ifstream inputFIle('input.txt');
 ofstream outputFile('out.txt');
 char ch;
 while( inputFile.get(ch)) outputFile.put(ch)
}
mrnutty 761 Senior Poster

I don't know what you are asking for but you need to cin >> v.a >> v.b [\i]. Make sure you define var v before using it in cin

mrnutty 761 Senior Poster

No you can't cin a enum unless you define it yourself.

mrnutty 761 Senior Poster

I guess that depends on what is meant by permutation. I take a permutation of size n to contain all values from 0 to n - 1 and to contain each value only once. So, for n = 5, say, a valid permutation would be:
$p = 0,4,3,1,2$
but something like:
$p = 0,4,3,1,16$
would be invalid.

For this definition, I guess you could put a bunch of checks in front of the actual inverting loop:

void inverse ( const std::vector< unsigned >& p, std::vector< unsigned >& ip )
{
   if ( p.empty() )
       return;

   /* Check validity of range */
   if ( *std::max_element( p.begin(), p.end() ) == p.size() - 1 ){
      /* Handle this error */
      return;
   }
   /* Check for repeated values */
   std::vector< bool > used( p.size(), false );
   for( unsigned i = 0; i < p.size(); ++i ){
      if ( used[ p[i] ){
           /* handle repeated number error */
           return;
      }
      used[ p[i] ] = true;
   }

   /* No need to check for unrepresented numbers, since this condition is */
   /* implied true if we get to this point, so by now the permutation is  */
   /* good for inversion.                                                 */
   
   ip.resize( p.size() );
   for ( unsigned i = 0; i < p.size(); ++i )
      ip[ p[i] ] = i;
}

Does that sound reasonable?

There is no specification that says permutation cannot contain any value from 0 to UNSIGNED_INT_MAX. Permutation is a concept hence it doesn't make sense to say permutation of …

mrnutty 761 Senior Poster

>> ip.resize( p.size() );
>> ip[ p ] = i;

the problem as I mentioned is that the value of p can be much greater than p.size() therefore making the statement ip[ p ] a bug

mrnutty 761 Senior Poster

I never heard of 'inverted premutation' but it looks like your reversing the key to value mapping into value to key mapping. The fastest way you can do this is in linear time, since you have to go through the whole array, which your function does. But there are some redundancies in your code and a possible bug.

The redudent code is your tempIndex, there is no need for it since you can simply use 'i' as it does not change in the body, until next iteration. And a possible bug is that you have no way of knowing whether 'ip' array is big enough, especially since the range p is huge. As a result of this, your program now suffers from buffer overflow and hackers can use this as a means to hack your program.

So to make your program more efficient in space,although you have to sacrifice time, you can do something like this,

//assume result size is same as mapping size
void inverse(const unsigned mapping, const unsigned size, unsigned result){
 for(unsigned i = 0; i < size; ++i){
   unsigned newKey = mapping[i];
   unsigned newKeyIndex = _getKeyIndex( result , newKey, size); //returns a unique index, via hashing
   result [ newKeyIndex ] = i;
}

The _getKeyIndex returns a index from [0,size) and it handles any collision. Google hashing for implementation. In theory the worst time for the above function is quadratic, because of the hashing, but the average case for hashing is constant.

So …

mrnutty 761 Senior Poster

Why? Reading the original post, I gather that the OP is trying to do something like this:

#include <iostream>
using namespace std;

struct AbstractEvent
{
    static int counter;

    static int get_next_id();

    static void init_event_ids();

    virtual int get_type() = 0;

    virtual ~AbstractEvent() {}
};

struct ConcreteEventA : AbstractEvent { static int type; int get_type() { return type; } };
struct ConcreteEventB : AbstractEvent { static int type; int get_type() { return type; } };
struct ConcreteEventC : AbstractEvent { static int type; int get_type() { return type; } };

// more concrete events ...

int AbstractEvent::counter = 0;
int AbstractEvent::get_next_id() { return counter++; }

int ConcreteEventA::type = AbstractEvent::get_next_id();
int ConcreteEventB::type = AbstractEvent::get_next_id();
int ConcreteEventC::type = AbstractEvent::get_next_id();

// more concrete event type initializations  ...

int main()
{
    ConcreteEventA a1, a2;
    ConcreteEventB b1, b2;
    ConcreteEventC c1, c2;

    AbstractEvent & ea1 = a1, & ea2 = a2;
    AbstractEvent & eb1 = b1, & eb2 = b2;
    AbstractEvent & ec1 = c1, & ec2 = c2;

    cout << ea1.get_type() << endl;
    cout << eb1.get_type() << endl;
    cout << ec1.get_type() << endl;

    cout << boolalpha << endl;

    cout << (ea1.get_type() == ea2.get_type()) << endl;
    cout << (ea1.get_type() == eb2.get_type()) << endl;
}

You can achieve the same functionality simply doing this:

#include <iostream>
using namespace std;

struct AbstractEvent
{
    virtual const void * get_type() = 0;

    virtual ~AbstractEvent() {}
};

struct ConcreteEventA : AbstractEvent { const void * get_type() { static const int type = 0; return &type; } };
struct ConcreteEventB : AbstractEvent { const void …
mrnutty 761 Senior Poster

Another option is to create a hash given the class information.

#include <iostream>
#include <typeinfo>
#include <string>
using namespace std;

size_t hash(const std::string &data) {
  size_t h = 0;
  for (unsigned i=0; i < data.size(); i++){
    h = (h << 6) ^ (h >> 26) ^ data[i];
  }
  return h;
}

template<class Class>
size_t getEventID(const Class& c){ return hash( typeid(c).name()); }

class Foo{};
class Bar{};

int main(){
  Foo f1,f2;
  Bar b1,b2;
  std::string str1,str2;
   std::cout << "f1 : " << getEventID(f1) << std::endl;
   std::cout << "f2 : " << getEventID(f2) << std::endl;
   std::cout << "b1 : " << getEventID(b1) << std::endl;
   std::cout << "b2 : " << getEventID(b2) << std::endl;
   std::cout << "str : " << getEventID(str1) << std::endl;
   std::cout << "str : " << getEventID(str2) << std::endl;
}

although you might want to automate this process

mrnutty 761 Senior Poster

make sure you aren't creating 'out' over and over again, therefore overwriting data. And post your new code.

mrnutty 761 Senior Poster

umm something like so:

struct ConstantRandom{
  int randNum;
  bool isFirstTime;
 ConstantRandom(): isFirstTime(true), randNum(0){};
 int operator()(){
   if(isFirstTime){ randNum = rand();  isFirstTime = false;}
   return randNum;
};
int main(){
 srand( time(0) );
 ConstantRandom cr;
 int i = cr(); //i equals some random number
 int j = cr(); // j should equal to i

Basically your just saving a state

mrnutty 761 Senior Poster

Yes I figured from your post that Publication was a base class. If you want to, you can cast the publication to the derived class and take appropriate measure like so:

Book * bk = dynamic_cast(*it);
if(bk != null){
  //publication was a book so do book stuff with 'bk'
}
mrnutty 761 Senior Poster

First you loop solution is very inefficient, with regards to opening and closing files. Just open it once and close it once.

Next a solution to your problem is to have the classes have its own extraction operator. Check this link for more details.

mrnutty 761 Senior Poster

Okay, 'd' instead of 'the' I can understand (I don't agree with it, but I can understand), but WTF is up with omitting 'ee' from "between"? There's a point where being lazy and being a retard come together, and it's generally best to stay away from it when trying to communicate with highly technical people.

Its the way people communicate these days, specifically, when writing electronically. I'm not going to lie, I talk like that with my friends. And the main reason being not laziness, but to get the same point across faster. But yea, I agree, there is a time and place for everything.

mrnutty 761 Senior Poster

>>By the way, i have this feeling that if lets say i get the hang with one Lib and then move to another that the previous Lib ive learned would go to waste, is it something i should worry about?

That's kind of an awkward question. I mean, throughout the years you will learn how to use different libraries for different things. Everything is a tool and tools will and can be replaced.


>>P.S i was using Dark GDK lib but i did not like it as much because it did all the job for me while i didnt understood how the libs code-work is done, isnt SDL something similar?

Listen, I was like you at one point. For example not wanting to use an image loading library because I didn't want to use someone else's code. But when you get more mature, you come to realize that its not always about knowledge, its about productivity. In your free time its ok to learn new skills. But in real world you will be using some tool that you didn't write. So get over it ;).

And as for SDL, I would strongly suggest you to go for it, else you can learn OpenGL. What you should concentrate at this stage is not how to load a image or do a certain task, but you should concentrate on learning to program effectively. This can only be done by practicing to program. So grab something …