m4ster_r0shi 142 Posting Whiz in Training

@ nitin1:

i have calculates the time complexity as O(nlogn). Am i right ? please verify.

If n denotes the number of your numbers, I'd say it's O(n). The method described here (which looks like what you were trying to do) also has an asymptotic time complexity of O(n). I used the term complexity in a broader sense in my previous post. Let's take a deeper look at what happens in both approaches. Note that even if operating on the list argument is an option, the second method still has to make a copy, because the algorithm needs both lists.

@ WaltP:

Unless you can prove to me recursion uses fewer resources than non-recursion.

The term you're looking for is iteration. And I don't have to prove anything. What you said is a fact.

Consider this:

#include <stdio.h>

inline int gcdRec(int a, int b) { return b == 0 ? a : gcdRec(b, a % b); }

inline int gcdLoop(int a, int b)
{
    while (b != 0)
    {
        int temp = a % b;
        a = b;
        b = temp;
    }

    return a;
}

int main()
{
    printf("%d\n", gcdRec (12, 18));
    printf("%d\n", gcdLoop(12, 18));

    return 0;
}

This is what my compiler generated for the gcdRec and gcdLoop functions, respectively:

[...]

    movl    $12, %eax
    movl    $18, %ecx
    jmp L17
    .p2align 2,,3
L19:
    movl    %ecx, %eax
    movl    %edx, %ecx
L17:
    cltd
    idivl   %ecx
    testl   %edx, %edx
    jne L19

[...] …
m4ster_r0shi 142 Posting Whiz in Training

Less overhead

Not really. I don't know what compiler you're using, but any decent one would seize the opportunity to perform tail call optimization in np complete's code, and generate output identical to the one corresponding to an iterative implementation.

easier to read

I think this is the first time I see someone claiming that imperative style code is more readable than functional style code :D So, you really think that a loop is more readable than this one-liner?

int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }

Why go through all the GCD calculations?

Well, at least np complete provided something that could help the OP reduce the complexity of his/her algorithm (which, BTW, is not quite correct - it's not guaranteed to find the least common multiple). Folding a list of numbers using a binary LCM function looks much better than what the OP is trying to do.

What did you contribute to the thread with your post, apart from biased, misleading statements?

why not just calculate the LCM?

So, tell us, how exactly would you do that in a simple and efficient way without using GCD? What algorithm do you have in mind? Prime factorization? Something else? (What?)

nitin1 commented: hey man! you are simply awesome. Daniweb is full of great people! keep it up! +2
m4ster_r0shi 142 Posting Whiz in Training

I fixed it. i downloaded the dll from a website and added it to my bin folder.

Downloading dlls from random sites is not a very wise thing to do. You never know what kind of code these dlls may contain. I'm talking about security issues. Your pc could as well be monitored by someone right now.

but now its saying ' cant open because libgcc_s_dw1-2.dll is missing from your computer, try re dwnloading the program'

This is what I meant here by saying that you don't have the correct version of MinGW. (Also, I just noticed that the SFML instructions link I posted is for SFML 1.2. The ones for SFML 1.6 are here.)

m4ster_r0shi 142 Posting Whiz in Training

Could you post the code?

m4ster_r0shi 142 Posting Whiz in Training

Ok so what i was thinking was add the nodes in sequence. so the text file would be

Does it have 4 legs?
Does it purr?
Cat
Dog
Does it swim?
fish

What you do here is called printing the tree using preorder traversal.

Does this require recursive functions?

No, but it is greatly simplified if you use recursion to implement it.

Now that i think about it that ^above way would work right?

Yes, but it needs a slight modification. You have to also output the null nodes:

Does it have 4 legs?
Does it purr?
Cat
null
null
Dog
null
null
Does it swim?
fish
null
null
null

What you want to do is called binary tree (de)serialization.
If you google this term, you'll get some interesting results.

m4ster_r0shi 142 Posting Whiz in Training

There are no tests what-so-ever in your code.

Yes, there are. They are inside the strncpy and strncat functions.

I've had some people say to do result_maxlength-1

They are right. In your first concat call, this -> result[result_maxlength] = '\0';
turns to -> c[5] = '\0';. You're going out of bounds. Same with the following calls.

strncat (result, b, result_maxlength);

strncat doesn't work like this. Check out the link above. What you need here is
this -> strncat (result, b, result_maxlength - 1 - strlen(result));

m4ster_r0shi 142 Posting Whiz in Training

which command were you talking about?

sf::Sprite::setColor

By default it's set to sf::Color(255, 255, 255, 255) (opaque white).
You could set it to sf::Color(i, i, i, 255) and control i with your slidebar.

If this doesn't give you the result you want, I guess you can always try the
'brute force' approach, as ravenous suggests, if you haven't tried it yet.

m4ster_r0shi 142 Posting Whiz in Training

I'm pretty sure the library the OP is using (OpenCV, I presume by looking at some of his/her recent posts) takes care of that.

m4ster_r0shi 142 Posting Whiz in Training

If you use SFML, you can load your image in a sf::Image, then create a sf::Sprite using that image and play with the sprite's color property to adjust the brightness. It's a O(1) operation and it affects every pixel of your image. Maybe the library you're using also has a similar feature and you're not aware of it yet.

m4ster_r0shi 142 Posting Whiz in Training

I was thinking about somehow using a static member that all the matrix cells will be defined by their value + the static value.

This is a very interesting idea. It also is easily generalized. You could have a stack of (different) operations and apply them in order when you want to get the value of a specific element. When you want to set the value of a specific element, you'd have to go backwards and also use the inverse operations. However, that would add a small overhead to every Get / Set call that could quickly become very big (if you keep stacking operations). To solve this problem, you could perform a small number of calculations each time you Get / Set some element. You'd need to also keep track of how many elements you have calculated.

The bottom line is that, while, in the end, you have to make all the calculations, this trick allows very good real time responsiveness for even humongous arrays.

Here's a minimal example.

m4ster_r0shi 142 Posting Whiz in Training

Try disabling checked iterators if you haven't already.

Also, if you're doing this in Debug mode, switch to Release mode.

m4ster_r0shi 142 Posting Whiz in Training

The !ss part essentially checks whether or not you got a (valid) value for your variable.

This should clear things up a bit more.

m4ster_r0shi 142 Posting Whiz in Training

cin is fine too. What you need to do is clear your stringstream's buffer and state before you use it again.
Either add this here -> ss.str(""); ss.clear(); before using ss or create ss right before you use it.

Also, the condition in your if statement should be !ss || !ss.eof().
As it is now, it doesn't work as you want if the user enters a blank line.

m4ster_r0shi 142 Posting Whiz in Training

I have a couple of questions:

What happens if you increase the number of calculations you have to make per iteration?
Are you sure you're timing the hardcoded approach properly?
What optimization flags are you using?

Check this out:

#include <windows.h>
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

template <class Function>
__int64 time_call(Function&& f)
{
    __int64 begin = GetTickCount();
    f();
    return GetTickCount() - begin;
}

int numberOfReps(25000);
int dotFrequency(7500);

const int MY_SIZE = 200;

class PreCalcObj
{
public:
      PreCalcObj()
      {
          for (int i = 0; i < MY_SIZE; ++i)
          {
              for (int j = 0; j < MY_SIZE; ++j)
              {
                  TiTjsumT2.push_back(i * j / 4597.0);
              }
          }
      }
      vector<double> TiTjsumT2;
};

class PreCalcObjArr
{
public:
      PreCalcObjArr()
      {
          for (int i = 0; i < MY_SIZE; ++i)
          {
              for (int j = 0; j < MY_SIZE; ++j)
              {
                  TiTjsumT2[i * MY_SIZE + j] = i * j / 4597.0;
              }
          }
      }
      double TiTjsumT2[MY_SIZE * MY_SIZE];
};

double CalcAll()
{
    double valReturn = 0;

    for (int iCount = 0; iCount < numberOfReps; ++iCount)
    {
        double bVal(33.23);
        if (iCount % dotFrequency== 0)
        {
            cout << ".";
        }
        for (int i = 1; i < MY_SIZE; ++i)
        {
            for (int j = 1; j < MY_SIZE; ++j)
            {
                valReturn += bVal * i * j / 4597.0;
            }
        }
    }

    cout << valReturn << endl;
    return valReturn;
}

double UsePreCalced(const PreCalcObj& mObj)
{
    double valReturn = 0;
    double bVal(33.23);

    for (int iCount = 0; iCount < numberOfReps; ++iCount) …
Jsplinter commented: Great point about the optimization! +2
m4ster_r0shi 142 Posting Whiz in Training

Now, let's add some basic AI. Nothing too serious, just a simple, suboptimal (you could use the KMP algorithm to improve it), history matcher. It searches the user's previous moves for recurring patterns and uses this information to predict the user's next move. For anyone interested in more advanced stuff, this could be of help.

m4ster_r0shi 142 Posting Whiz in Training

it works well

It's not complete yet, though. An input of 1 0 1 could yield a much simpler output (i.e. x = i or x = -i). An input of 1 -4 4 should only give one solution. Also, an input of 0 for a should be rejected.

to find the gcd ..How do I do that ?

Here's some pseudocode. Make sure the arguments you pass in your gcd function are positive numbers. You could use abs for this.

EDIT: sfuo beat me to it...

m4ster_r0shi 142 Posting Whiz in Training

Yeap. Also, the correct formula is b*b - 4*a*c, not b*b + 4*a*c.

Now, instead of cout << " error !" << endl; you could put something like this:

cout << " x = [" << -b << " + sqrt(" << x << ")] / " << den << endl;
cout << " Or " << endl;
cout << " x = [" << -b << " - sqrt(" << x << ")] / " << den << endl;

I made these corrections and ran the program with 1 -5 6, 3 4 7 and 1 3 -2 as inputs. I got correct results in all cases.

But what you have now is only one of the three possible cases. There is also the case that b*b-4*a*c is zero and the case that b*b-4*a*c is less than zero. Do you know how to handle these?

m4ster_r0shi 142 Posting Whiz in Training

Looks like Perl to me.

m4ster_r0shi 142 Posting Whiz in Training

At this point, I really don't know whether Walt is being serious or not. In any case, his suggestion is a good first step, but it's not enough. Let's see where it falls short. Run the following program and enter 1 3 -2 as input.

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    int a, b, c;
    int num, den;

    cin >> a >> b >> c;

    den = 2 * a;

    num = - b + sqrt(b * b - 4 * a * c);
    cout << "x1 = " << num << '/' << den << endl;

    num = - b - sqrt(b * b - 4 * a * c);
    cout << "x2 = " << num << '/' << den << endl;
}

You'll get 1/2 and -7/2, which, obviously, is wrong,
as ... (1/2)^2 + 3*( 1/2) - 2 == -1/4 != 0
and (-7/2)^2 + 3*(-7/2) - 2 == -1/4 != 0

The problem here is that b * b - 4 * a * c is 17. The square root of 17 is an irrational number (as is the square root of any prime number) and is approximately equal to 4.123. However, the decimal part is lost during the integer conversion that follows, and you get a wrong answer. The solution here is simple. Just don't use the square root in your output when the result is not an integer. How can you do that? Again, it's …

m4ster_r0shi 142 Posting Whiz in Training

Ok, I don't disagree. I guess the OP could get the integer part of sqrt(b*b-4*a*c), square it, and see if it gives b*b-4*a*c. If yes, it's ok to use sqrt.

m4ster_r0shi 142 Posting Whiz in Training

num = ((-b) + sqrt(b*b-4*a*c))
den = (2*a)

It's unlikely that sqrt(b*b-4*a*c) will be an integer (or even a rational number).

A better approach would be something like this:

...
p = -b
q = b*b-4*a*c
r = 2*a
...
print "x = ("
print p
print " +/- sqrt("
print q
print ")) / "
print r
...
m4ster_r0shi 142 Posting Whiz in Training

Or better yet, vectors, since the number of lines in the file is not known during compilation.

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

using namespace std;

int main()
{
    ifstream fin("main.cpp");

    vector<string> lines;

    string curLine;

    while (getline(fin, curLine)) lines.push_back(curLine);

    for (size_t i = 0, size = lines.size(); i < size; ++ i)
        cout << lines[i] << endl;
}
m4ster_r0shi 142 Posting Whiz in Training

I wonder which is better :to start learning a new programming language or develop my skills in the C++ language ?

Both have advantages. What you should do depends on several things. One of these things is what is it that makes you face this dilemma. Do you have some specific goals in mind and you wonder if C++ is enough or there are better options (e.g. if you want to write a compiler, a functional language is by far a better choice), or are you just wondering which option is better for your evolution as a programmer?

In the first case, you'll first have to tell us what goals you have in mind.

In the second case, the answer depends on how much C++ you know. This -> "I started learning C++ since 7 months" doesn't tell us much. Walt, probably judging by personal experience, assumes that you're still a beginner, but this may not be the case. It would be better if you had said something like:

"I know conditionals, loops, arrays and functions, but I have a really hard time getting my head around pointers. I think I'll move to classes now and come back to that later."

Or something like:

"I have read and completely understood the tutorial on this site. I am familiar with using a big part of the standard library, and recently I started making my first step towards design patterns."

In the first sub-case, …

m4ster_r0shi 142 Posting Whiz in Training

Sorry, I was wrong. Looking more closely, your code doesn't have the problem I thought it had. This problem only arises when you use random_shuffle carelessly (as I deliberately did in my second example). So, your code that uses std::set is fine.

To make amends for my mistake, let me answer some of your questions.

And also most of the time the four numbers starts with a 0 even there's no 0 value in the array.

There are several zero values in your array :) Check this out:

#include <iostream>

using namespace std;

int main()
{
    int array[3][3] = {
        { 1, 2, 3 },
        { 4, 5 },
        { 6 }
    };

    for (int i = 0; i < 3; ++ i)
    {
        for (int j = 0; j < 3; ++ j)
            cout << array[i][j];

        cout << endl;
    }
}

What's the difference between the two version?

The difference is that the while loop runs as many times as needed to fill the set with four (different) numbers, while the for loop always runs four times. After these four runs, the set may have four (different) values, but it may also have only three or two or even one. Take a look at std::set and how it works.

Also, I want to add here that your code relies on value uniqueness, while the examples I posted rely on index uniqueness. This difference is irrelevant to the method used to get …

m4ster_r0shi 142 Posting Whiz in Training

There is a problem with the logic you use to generate the random indexes.

Let's start with something simpler. Suppose you want to get three unique random values from a unidimensional array of four elements. The easiest way to do this is by using random_shuffle:

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

using namespace std;

int main()
{
    srand(time(0));

    string value_array[4] = { "one", "two", "three", "four" };

    int index_array[4] = { 0, 1, 2, 3 };

    random_shuffle(index_array, index_array + 4);

    for (int i = 0; i < 3; ++ i)
        cout << value_array[index_array[i]] << endl;
}

Now, there are two ways to scale this in order to accommodate for bidimensional arrays. One of them is wrong (and is very similar to what you're doing) and the other is right. Let's see the wrong way first:

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

using namespace std;

int main()
{
    srand(time(0));

    string value_array[3][4] = {
        { "one-a", "two-a", "three-a", "four-a" },
        { "one-b", "two-b", "three-b", "four-b" },
        { "one-c", "two-c", "three-c", "four-c" }
    };

    int index_array_a[3] = { 0, 1, 2 };
    int index_array_b[4] = { 0, 1, 2, 3 };

    random_shuffle(index_array_a, index_array_a + 3);
    random_shuffle(index_array_b, index_array_b + 4);

    for (int i = 0; i < 3; ++ i)
        cout << value_array[index_array_a[i]][index_array_b[i]] << endl;
}

One problem with this is that it just doesn't work if the number of your picks is bigger than the smallest dimension.

But the real problem is that …

m4ster_r0shi 142 Posting Whiz in Training

i couldnt even get SFML to install right or work with code blocks....i think im gonna pass.

Don't give up so easily. Since you're using Code::Blocks, my guess is that you don't have the correct version of MinGW.

Here's what you'll do:

  1. Get the latest MinGW from here (use the GUI installer), and install the C and C++ compilers in C:\MinGW.

  2. Open Code::Blocks and from the menu bar go Settings -> Compiler and debugger...

  3. Go to the Toolchain executables tab and change the compiler directory from
    C:\Program Files\CodeBlocks\MinGW (or whatever it currently is) to C:\MinGW.

Now, you should be able to make SFML 1.6 work by following these instructions.

If you face any problems don't hesitate to post.

m4ster_r0shi 142 Posting Whiz in Training

Just let the OP do what he feels he wants to next.

I have no intention of doing otherwise. Actually, even if I had the intention, I wouldn't be able to do it. The OP can do whatever (s)he wants regardless of what I say. However, doing something because you want to do it is not the same as doing something because you think is right or / and easy while in fact is not.

If the OP had said that (s)he wants to remain in the console because (s)he really likes its vertical scrolling bar and the grey characters on the black background, I wouldn't have a reason to continue. It's his / her personal preference and I respect that. But (s)he didn't say that. (s)he said that (paraphrased) most programmers use the console to write real games because it's easy.

As someone who has more (not much more though) experience than the OP in the topic, I feel obliged to present the alternatives and make sure (s)he understands which one is better in what way and why. But after that, of course, the OP can do anything (s)he desires.

I didn't have any intention to upset you (or anyone else), and I apologize if I did.

m4ster_r0shi 142 Posting Whiz in Training

Now masterroshi kindly posted a starter template for tic-tac-toe.

That code is completely broken though :S I was in a hurry when I wrote it and when I realized there were problems it was too late to edit my post. So, here's a fixed version, in case the OP decides to use it:

#include <iostream>

void drawGrid(int grid[3][3])
{
    std::cout << std::endl;

    for (int i = 0; i < 3; ++i)
    {
        if (i != 0) std::cout << "------" << std::endl;

        for (int j = 0; j < 3; ++j)
        {
            char ch;

            switch (grid[i][j])
            {
                case 0 : ch = ' '; break;
                case 1 : ch = 'X'; break;
                case 2 : ch = 'O';
            }

            if (j != 0) std::cout << '|';

            std::cout << ch;
        }

        std::cout << std::endl;
    }

    std::cout << std::endl;
}

int main()
{
    int grid[3][3] =
    {
        {0, 0, 1},
        {0, 1, 0},
        {2, 0, 0}
    };

    while (true)
    {
        // add more stuff here...

        drawGrid(grid);

        // add more stuff here...

        std::cout << "quit? (y/n) ";

        char ch;

        std::cin >> ch;

        if (ch == 'y' || ch == 'Y') break;
    }

    return 0;
}

I still insist on using a finite state machine instead of a flowchart to model the game logic though.

I quote from here:

...some people do not see the true difference between the two. The confusion starts with the missing understanding of a state which is not known in a flowcharts. [...]

m4ster_r0shi 142 Posting Whiz in Training

Because i personally think my first real game should be in the CP because thats what most programmers do.

One problematic thing with this line of reasoning is that 'real games' and 'CP' have nothing to do with each other. Another is that what most beginner (<- you forgot that adjective above) programmers do is not what is right.

And for obvious reasons, like, it being more simple and Programmer-Friendly. :)

This statement is just plain wrong. The console is actually a very hostile environment for game development. I think you didn't check the first link I posted, so, you'd better do it now.

ive never thought of writing a flowchart. i think i might do that.

Don't do it. A flowchart is not the best technique to use when designing a game. It may be enough for something simple as tic-tac-toe, but it scales very poorly as you move to bigger and more complex games. When designing a game, it's better to think in terms of state and events that affect that state. For example, ask yourself questions like:

  1. "What are the different game states I'll have to deal with?"

  2. "In what way exactly can the user interact with the game in each state?"

  3. "What are the events (either user or game generated) that trigger state transitions?"

And then answer these questions:

  1. "There will be an initialization state, where the user chooses whether (s)he will play against the computer or …

m4ster_r0shi 142 Posting Whiz in Training

i dont want to jump into graphics yet

Why is that?

So, what kind of game do you want to make?

PS: Something I found regarding your original question
("how hard would it be to make a text-based zork-like game?")

m4ster_r0shi 142 Posting Whiz in Training

We don't know what OS the OP is using. Yes this matters, linux or Mac users will normally find using 3rd party libraries slightly more tricky.

Ok. But if you are a linux user you might actually find this fun :) Plus, it will only be difficult the first time you'll do it. Oh, and the key word here is 'slightly'.

We don't know what IDE the OP is using. Yes this matters, because where do you put the directory, do you have to add compiler/linking switches? All this makes it much more difficult.

No, it doesn't make it much more difficult. You are nitpicking now.

How you can just brush it off 'as a very poor argument' without no reasons for justification? Now the OP not only has to learn the semantics of another library but also OOP idioms.

Huh? I think you missed my point above. Read it again, more carefully. All I said was that introducing graphics doesn't have to introduce OOP. You can use CSFML or SDL and leave OOP out if you find it confusing.

Again, sorry but have to disagree here. You can adequately write a console version of tic-tac-toe without knowing how to use graphics.

Again, you missed the point. Let me restate it: The language features you need in order to write a console version of tic-tac-toe are the same language features you need in order to write a tic-tac-toe game with graphics. If …

m4ster_r0shi 142 Posting Whiz in Training

After only 1 week, you don't have the background in the language to even think about graphics yet. Learn the language first. Graphics can come later.

This doesn't really make sense, because modern graphics libraries render language knowledge and graphics orthogonal concepts.

Suppose you want to write a Tic-Tac-Toe game. In console, you would do something like this:

#include <iostream>

void drawGrid()
{
    for (int i = 0; i < 3; ++i)
    {
        for (int j = 0; j < 3; ++j)
        {
            char ch;

            switch (grid[i][j])
            {
                case 0 : ch = ' '; break;
                case 1 : ch = 'X'; break;
                case 2 : ch = 'O';
            }

            std::cout << ch;
        }

        std::cout << endl;
    }
}

int main()
{
    int grid[3][3];

    while ( /* user doesn't want to quit */ )
    {
        // do some stuff...

        drawGrid();

        // do some more stuff...
    }
}

Using SFML, you would do something like this:

#include <SFML/Graphics.hpp>

void drawGrid(sf::RenderWindow & window, sf::Sprite & sptX, sf::Sprite & sptO)
{
    for (int i = 0; i < 3; ++i)
    {
        for (int j = 0; j < 3; ++j)
        {
            switch (grid[i][j])
            {
                case 1 : sptX.SetPosition(i * BLOCK_SIZE, j * BLOCK_SIZE);
                         window.Draw(sptX); break;
                case 1 : sptO.SetPosition(i * BLOCK_SIZE, j * BLOCK_SIZE);
                         window.Draw(sptO);
            }
        }
    }
}

int main()
{
    int grid[3][3];

    sf::Image imgX, imgO;

    imgX.LoadFromFile("X.png");
    imgO.LoadFromFile("X.png");

    sf::Sprite sptX(imgX), sptO(imgO);

    sf::RenderWindow window(/* window params (e.g. resolution) */);

    while ( /* user doesn't want to quit */ …
m4ster_r0shi 142 Posting Whiz in Training

im thinking of a game in the Command Prompt

Read this first.

IMO, the thing with the best result-to-effort ratio you can do right now is grabbing a graphics library (e.g. SFML) and writing a simple scrolling shooter. And if you 're worrying about your artistic skills, don't. Computer software nowadays allows you to create really cool stuff without a lot of effort. I'm working on a 2D puzzle game myself, and, recently, I remade the graphics using Blender. You can see the result here (I also put the previous version for comparison).

m4ster_r0shi 142 Posting Whiz in Training

Here's an idea:

#include <iostream>
#include <string>

template <class A, class B> struct SameType { static const bool Result = false; };
template <class A> struct SameType <A, A>   { static const bool Result = true;  };

template <bool C, class True, class False> struct IfThenElse;
template <class True, class False> struct IfThenElse <true,  True, False> { typedef True  Result; };
template <class True, class False> struct IfThenElse <false, True, False> { typedef False Result; };

template <class T>
struct MyClass
{
    struct DoItStr  { void operator()() { std::cout << "std::string stuff..." << std::endl; } };
    struct DoItChar { void operator()() { std::cout << "char stuff..."        << std::endl; } };
    struct DontDoIt { void operator()(); /* using this will trigger a compilation error ;) */ };

    void doIt()
    {
        typedef typename IfThenElse <SameType<T, std::string>::Result, DoItStr,  DontDoIt>::Result DoIt_;
        typedef typename IfThenElse <SameType<T, char>::Result,        DoItChar, DoIt_   >::Result DoIt;

        DoIt()();
    }
};

int main()
{
    // MyClass<int>().doIt(); // uncomment to get an error
    MyClass<char>().doIt();
    // MyClass<double>().doIt(); // uncomment to get an error
    MyClass<std::string>().doIt();

    std::cin.get();
}

Ok, I think I'm done editing...

m4ster_r0shi 142 Posting Whiz in Training

I've tried to do some research on this minimax thing, but I couldn't find anything helpful.

How much did you search? I just googled connect four c++ minimax and I found this video on youtube. In the description of that video, I found this link, There, you can see a functional implementation of minimax for connect four, which is as good as pseudocode, followed by a detailed explanation. If this is not enough, the guy has also coded implementations in several other languages (including c++), and you can view the full source code on github. And if you want to test his ai, you can play against it on your browser.

m4ster_r0shi 142 Posting Whiz in Training

Based on his actual problem statement, it looks like buffered input is his problem. Maybe his description was still ambiguous and confusing since it wasn't a linear description of the problem -- or was it?.

Did anybody else read this several times trying to make sense out of it, or should I feel bad about myself?

WaltP commented: Probably not, and no you shouldn't. If you wish to do that much work, go for it. I want a clear explanation. +14
Lucaci Andrew commented: Nah, that was the problem. +0
m4ster_r0shi 142 Posting Whiz in Training

You are missing endl or flush at the end of most of your output statements.

This is a joke, right? It has to be a joke, because neither is it true nor does it have anything to do with the OP's problem.

The OP's problem arises from mixing istream::operator >> with getline calls, and it's another very common mistake among beginners. The solution is to either use only one or the other, or make sure you clear the buffer from any leftovers of the one before using the other.

Here's an example that demonstrates the problem and an easy fix:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string name;
    string color;

    cout << "Enter your name (one word): ";
    cin >> name;

    cout << "Enter your favourite color (e.g. light blue): ";
    //{ string temp; getline(cin, temp); } // uncomment to fix
    getline(cin, color);

    cout << "Hello, " << name << "!" << endl;
    cout << "Your favourite color is " << color << endl;

    cin.get();
}
m4ster_r0shi 142 Posting Whiz in Training

Judging by the way you use getline, teamnamesquestion must be a char array. The problem with this is that teamnamesquestion == "no" performs a pointer equality check, that will, obviously, always return false.

If you don't believe me, try this:

#include <iostream>

using namespace std;

int main()
{
    char str[10];

    cin.getline(str, 5);

    if (str !=  "no") cout << "foo" << endl;
    if (str != "yes") cout << "bar" << endl;

    std::cin.get();
}

What you can do is either use strcmp instead of the == operator...

#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    char str[10];

    cin.getline(str, 5);

    if (strcmp(str,  "no") == 0) cout << "foo" << endl;
    if (strcmp(str, "yes") == 0) cout << "bar" << endl;

    std::cin.get();
}

...or use a std::string instead of a char array, as lucaciandrew suggested...

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str;

    getline(cin, str);

    if (str ==  "no") cout << "foo" << endl;
    if (str == "yes") cout << "bar" << endl;

    std::cin.get();
}
m4ster_r0shi 142 Posting Whiz in Training

Okay, I calculated the binomial coefficient for n = 1600 and k = 800 using the factorial approach and a smart memoization method I found here. As you can see from the results, it turns out that the former way is more efficient in terms of both time consumption and memory usage. So, if I didn't do anything wrong, and if there isn't a better memoization technique for this, what we learned today is that (while recursion can be extremely useful, as rubberman noticed) for this particular problem (computing binomial / multinomial coefficients), arbitrary precision arithmetic is the way to go.

m4ster_r0shi 142 Posting Whiz in Training

Yes. It seems that the author's primary concern was that the intermediate results were smaller than the final one, so, he overlooked the fact that the latter might not fit in a size_t... I had to replace three occurrences of size_t with unsigned long long to get the expected result.

m4ster_r0shi 142 Posting Whiz in Training

So, what you essentially want is efficient calculation of multinomial coefficients. I googled that, and the first link I got was this.

m4ster_r0shi 142 Posting Whiz in Training

Well, you do initialize your globals in globals.h. You shouldn't be doing this. Also, you forgot some const qualifiers in your main.cpp. Read the relevant post of mine in the previous page again, more carefully this time :P

m4ster_r0shi 142 Posting Whiz in Training

Post your code. Post the relevant first lines of globals.h, main.cpp and playa.cpp.

m4ster_r0shi 142 Posting Whiz in Training

I want to clarify something to avoid a potential misunderstanding. JasonHippy's suggestion creates a different set of globals for each module the global header is included in. This, obviously, works fine if you only want global constants. But if you want global variables, it's not enough, as you'll probably want modifications made to a particular global variable in one module to be reflected in every other module. This is why you have to use extern.

m4ster_r0shi 142 Posting Whiz in Training

Personally I'd avoid using extern and just stick them in a header which can be included in any modules that require them.

Er... That's what I suggested too. And you can't do that without extern, to the best of my knowledge.

About the problem, now:

 extern const int SCREEN_WIDTH = 640;
 extern const int SCREEN_HEIGHT = 480;
 extern const int SQUARE_HEIGHT = 22;
 extern const int SQUARE_WIDTH = 10;
 extern SDL_Surface *image = NULL;
 extern SDL_Event event; 

Don't do this in globals.h. Do this instead:

 extern const int SCREEN_WIDTH;
 extern const int SCREEN_HEIGHT;
 extern const int SQUARE_HEIGHT;
 extern const int SQUARE_WIDTH;
 extern SDL_Surface *image;
 extern SDL_Event event;

Notice that I don't initialize them here. This should be done in main.cpp:

 const int SCREEN_WIDTH = 640;
 const int SCREEN_HEIGHT = 480;
 const int SQUARE_HEIGHT = 22;
 const int SQUARE_WIDTH = 10;
 SDL_Surface *image = NULL;
 SDL_Event event;
m4ster_r0shi 142 Posting Whiz in Training

What global variables did you get this error for? How / where do you define these variables? Did you read the link I mentioned above?

m4ster_r0shi 142 Posting Whiz in Training

It looks like you have to include the appropriate SDL headers in playa.cpp. What are the headers (*.h files) that you include in main? Try including them in playa.cpp too. Also, it looks like you have some global variables (e.g. event). Reading this could help. Though, you should try to minimize the use of global variables in your programs.

m4ster_r0shi 142 Posting Whiz in Training

there are certain functions in playa.cpp that require defined things in main.cpp

You mean global variables or other functions? If it's the former, you could modify the functions in playa.cpp to accept these things as arguments. If it's the latter, you could add declarations for these functions at the beginning of playa.cpp.

m4ster_r0shi 142 Posting Whiz in Training

I added the return NULL, but I got the same error

Hmmm... I don't know then. It looks ok to me. Maybe I'm missing something...

I have playa.h and main.cpp included in playa.cpp and playa.h included in main.cpp.

You shouldn't include main.cpp in playa.cpp.

m4ster_r0shi 142 Posting Whiz in Training

To help with the problem of getting votes on less visited forums, I would suggest that, at least, all snippets should have a link posted on this thread, and ask that moderators try to take the time to check out each submission, even if it is in a foreign programming language (as in, not the mod's preferred language).

I agree with this. I was worried about that problem too. I'm in the process of writing something that will help me automate as much of my work as possible and I'm considering submitting a (self-contained) part of it to the competition. I'm using haskell for this, as functional languages are better suited for writing programs like the one I write (I heavily (ab)use pattern matching). I found a way, though, to write the part I want to submit in c++ (yes, there is native support for (even nested) pattern mathing in c++ (those of you who understand what I mean, please don't tell the others what I'm talking about)), and that's what I'll be submitting. But even if this solves the problem for me, others might not have such an option, so, once again, I agree with mike's suggestion.

I have a couple of questions too:

-> Are we allowed to use freely available 3rd party libraries?
-> Are we allowed to submit more than one code snippets?