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

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

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

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

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

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

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

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

If you have to do it using sscanf, you could do it like this:

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
    string path = "main/articles/animals/giraffe";

    char * cPath1 = new char[path.size()];
    char * cPath2 = new char[path.size()];

    sscanf(path.c_str(), "%[^'/']/%[]", cPath1, cPath2);

    string path1(cPath1), path2(cPath2);

    delete[] cPath1; delete[] cPath2;

    cout << path1 << '\n' << path2 << endl;

    cin.get();
}

But why not do it the C++ way?

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    string path = "main/articles/animals/giraffe";

    stringstream stream(path);
    string part1, part2;

    getline(stream, part1, '/');
    getline(stream, part2);

    cout << part1 << '\n' << part2 << endl;

    cin.get();
}

A couple of useful links -> sscanf, stringstream, getline

OrangeTree commented: Clearly and useful. +0
m4ster_r0shi 142 Posting Whiz in Training

Why not just create array as a large array? Say int array[1000]?

While this would work if this is just homework, it's not a good idea in general, as it creates a huge security hole in the application. Here's an interesting thread I found regarding that matter.

The concept of increasing the array size by one for each and every value entered is so resource heavy that I don't really think a useful solution.

It's not that bad, actually. If the user enters 10000 integers before (s)he stops, the total resizing and copying process would take less than 100 milliseconds. But, of course, it's not the wisest thing to do.

In my opinion, the best thing you can do is emulate the inner workings of a std::vector. That is, create an dynamic array of, let's say, 100 elements, at first. If the user enters more than 100 integers, resize that array to 200 elements (using the functions mentioned above -- no, you can't escape that). If the user enters more than 200 elements, resize your array to hold 400 elements, etc... Once the user decides to stop, you can optionally resize your array one last time, if saving memory is really that important.

m4ster_r0shi 142 Posting Whiz in Training

That way u dont have to change ur function template everytime if u wish to change the m x n of ur array...

This doesn't make sense. You never have to change your function template.

Its faster

No, it's not.

#include <iostream>
#include <boost/timer.hpp>

using namespace std;

double global;

template <int M, int N>
void speedTest(int (& array)[M][N])
{
    for (int i = 0; i < M; ++i)
        for (int j = 0; j < N; ++j)
            array[i][j] = 0;

    global++;
}

void speedTestPtr(int * array, int M, int N)
{
    for (int i = 0; i < M; ++i)
        for (int j = 0; j < N; ++j)
            array[i*N + j] = 0;

    global++;
}

int main()
{
    int arr2x2[2][2] = {{1, 2}, {3, 4}};

    boost::timer timer;

    timer.restart();

    for (long i = 0; i < 10000000; ++i)
    for (long j = 0; j < 15; ++j)
        speedTest(arr2x2);

    cout << "time 1: " << timer.elapsed() << endl;

    timer.restart();

    for (long i = 0; i < 10000000; ++i)
    for (long j = 0; j < 15; ++j)
        speedTestPtr(&arr2x2[0][0], 2, 2);

    cout << "time 2: " << timer.elapsed() << endl;

    cout << global << endl;

    cin.get();
}

I tested the above with zero, -O1, -O2 and -O3 speed optimizations. The results I got were, respectively:

time 1: 3.5
time 2: 4.1

time 1: 0.7
time 2: 1.7

time 1: 0.234
time 2: 0.281

time 1: 0.187
time 2: 0.187

can be …

m4ster_r0shi 142 Posting Whiz in Training

Don't forget to get the debug privilege before opening a process other than your own. Useful link.
Also, don't forget to close your handles once you're done (I forgot to do it...). Another useful link.

m4ster_r0shi 142 Posting Whiz in Training

Here's another good link. My personal favourite is the Box Layout:

import java.awt.Dimension;
import java.awt.Font;

import javax.swing.*;

public class Main extends JFrame {

    void init() {

        // we'll use a main panel and four row-panels

        JPanel basicPanel = new JPanel(); basicPanel.setLayout(
            new BoxLayout(basicPanel, BoxLayout.Y_AXIS));

        JPanel titleRow = new JPanel(); titleRow.setLayout(
            new BoxLayout(titleRow, BoxLayout.Y_AXIS));

        JPanel usernameRow = new JPanel(); usernameRow.setLayout(
            new BoxLayout(usernameRow, BoxLayout.X_AXIS));

        JPanel passwordRow = new JPanel(); passwordRow.setLayout(
            new BoxLayout(passwordRow, BoxLayout.X_AXIS));

        JPanel buttonRow = new JPanel(); buttonRow.setLayout(
            new BoxLayout(buttonRow, BoxLayout.X_AXIS));

        // =-=-=-=-=-=-=-=-=-=-=-=-=-=-= title panel =-=-=-=-=-=-=-=-=-=-=-=-=-=-=

        JLabel lblAdmin = new JLabel("ADMIN"); lblAdmin.setAlignmentX(0.5f);
        lblAdmin.setFont(lblAdmin.getFont().deriveFont(Font.BOLD).deriveFont(50f));

        JLabel lblConsole = new JLabel("CONSOLE"); lblConsole.setAlignmentX(0.5f);
        lblConsole.setFont(lblConsole.getFont().deriveFont(Font.ITALIC).deriveFont(40f));

        titleRow.add(lblAdmin);
        titleRow.add(lblConsole);

        // =-=-=-=-=-=-=-=-=-=-=-=-=-=-= username panel =-=-=-=-=-=-=-=-=-=-=-=-=-=-=

        JLabel lblUsername = new JLabel("username:");
        JTextField txtUsername = new JTextField();
        txtUsername.setMaximumSize(new Dimension(125, 25));

        usernameRow.add(lblUsername);
        usernameRow.add(Box.createRigidArea(new Dimension(10, 0)));
        usernameRow.add(txtUsername);

        // =-=-=-=-=-=-=-=-=-=-=-=-=-=-= password panel =-=-=-=-=-=-=-=-=-=-=-=-=-=-=

        JLabel lblPassword = new JLabel("password:");
        JTextField txtPassword = new JTextField();
        txtPassword.setMaximumSize(new Dimension(125, 25));

        passwordRow.add(lblPassword);
        passwordRow.add(Box.createRigidArea(new Dimension(10, 0)));
        passwordRow.add(txtPassword);

        // =-=-=-=-=-=-=-=-=-=-=-=-=-=-= button panel =-=-=-=-=-=-=-=-=-=-=-=-=-=-=

        JButton btnLogIn = new JButton("Log In");
        JButton btnCancel = new JButton("Cancel");

        btnLogIn.setMinimumSize(new Dimension(80, 30));
        btnLogIn.setMaximumSize(new Dimension(80, 30));

        btnCancel.setMinimumSize(new Dimension(80, 30));
        btnCancel.setMaximumSize(new Dimension(80, 30));

        buttonRow.add(btnLogIn);
        buttonRow.add(Box.createRigidArea(new Dimension(10, 0)));
        buttonRow.add(btnCancel);

        // =-=-=-=-=-=-=-=-=-=-=-=-=-=-= main panel =-=-=-=-=-=-=-=-=-=-=-=-=-=-=

        basicPanel.add(Box.createVerticalGlue());
        basicPanel.add(titleRow);
        basicPanel.add(Box.createRigidArea(new Dimension(0, 30)));
        basicPanel.add(usernameRow);
        basicPanel.add(Box.createRigidArea(new Dimension(0, 10)));
        basicPanel.add(passwordRow);
        basicPanel.add(Box.createRigidArea(new Dimension(0, 20)));
        basicPanel.add(buttonRow);
        basicPanel.add(Box.createVerticalGlue());

        // =-=-=-=-=-=-=-=-=-=-=-=-=-=-= frame stuff =-=-=-=-=-=-=-=-=-=-=-=-=-=-=

        add(basicPanel);

        setSize(240, 320);
        setTitle("Box Layout Example");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {

                Main app = new Main();

                app.init();
                app.setVisible(true);
            }           
        });
    }
}
m4ster_r0shi 142 Posting Whiz in Training

If you have to code this yourself, one way to do it would be to use the inverse transformation and acceptance-rejection methods.

I had to simulate normal distribution a while ago and that's how I did it:

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

using namespace std;

double random() { return rand() / double(RAND_MAX); }

struct Distribution
{
    virtual double Draw() { return 0.0; }
    virtual ~Distribution() {}
};

struct UniformDistribution : Distribution
{
    double a, b;

    UniformDistribution(double a_ = 0.0, double b_ = 1.0) :  a(a_), b(b_) {}
    ~UniformDistribution() {}

    // inverse transform sampling
    double Draw() { return a + (b - a) * random(); }
};

struct NormalDistribution : Distribution
{
    UniformDistribution ud1, ud2;

    double mean, dev, max;

    NormalDistribution(double mean_, double dev_) : mean(mean_), dev(dev_)
    {
        max = 1.0 / sqrt(2 * 3.14159265 * dev * dev);

        ud1 = UniformDistribution(mean - 4 * dev, mean + 4 * dev);
        ud2 = UniformDistribution(0, max);
    }
    ~NormalDistribution() {}

    double density(double x) { return max * exp(- (x - mean) * (x - mean) / (2 * dev * dev)); }

    // rejection sampling
    double Draw()
    {
        double x = ud1.Draw();
        double y = ud2.Draw();

        if (y <= density(x)) return x;
        else return Draw();
    }
};

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

    NormalDistribution nd(10, 2);

    vector<double> random_numbers;

    for (size_t i = 0; i < 100; ++i) random_numbers.push_back(nd.Draw());

    sort(random_numbers.begin(), random_numbers.end());

    for (size_t i = 0; i < 100; ++i) cout << random_numbers[i] << endl;
} …
m4ster_r0shi 142 Posting Whiz in Training

I'm not sure how I would check if the values are 'parse-able' or not

You could use a stringstream for that. First, get rid of the trailing whitespace characters in your input. Then, create a stringstream out of your input and use it to set your variable's value. If the operation succeeds and there is no data left in your stringstream object, you're OK.

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

template <class T>
bool TryParse(string input, T & var)
{
    static const string ws(" \t\f\v\n\r");

    size_t pos = input.find_last_not_of(ws);

    if (pos != string::npos)
        input.erase(pos + 1);
    else input.clear();

    stringstream buffer(input);

    return buffer >> var && buffer.eof();
}

int main()
{
    string input;

    int n;
    double d;

    while (cin) // CTRL-Z (or CTRL-D) and enter to quit
    {
        cout << "enter int: "; getline(cin, input);
        if (TryParse(input, n))
            cout << "you entered: " << n << endl;
        else cout << "error" << endl;

        cout << "enter double: "; getline(cin, input);
        if (TryParse(input, d))
            cout << "you entered: " << d << endl;
        else cout << "error" << endl;
    }
}
m4ster_r0shi 142 Posting Whiz in Training

What if you make your get functions return references?

vector<string> & getcoursename() {return coursename;}
vector<double> & getmark() {return mark;}
NathanOliver commented: I missed that one. Good Job +0
m4ster_r0shi 142 Posting Whiz in Training

Okay. In this case, an indirect_iterator is exactly what you need.

daviddoria commented: Yep, that is certainly what I was looking for! +12
m4ster_r0shi 142 Posting Whiz in Training

You don't have to call strlen or any other function to compute your word's length.
Notice that, inside your loop, c represents the number of correct consecutive letters.
Just add a bool variable outside your loop and modify it appropriately inside the loop:

bool found = false;

while(true)
{
    if (word[c] == '\0' && ( /* rather verbose condition, involving spaces */ )) { found = true; break; }

    if (para[i] == '\0') break; // found == false

    //...
}
m4ster_r0shi 142 Posting Whiz in Training
m4ster_r0shi 142 Posting Whiz in Training

I just would like some input/critics/heads up on my class definition and implementation I did for my project.

Looks good. There are a couple of small issues, but other than that looks good. About the small issues now...

Your m_vector doesn't have to be a vector pointer. A vector object would be fine. This would greatly simplify
some things. E.g. your assignment operator (which, by the way, should return a reference) would look like this:

PNVector & PNVector::operator=(const PNVector &other) {
    if (this!= &other)
        this->m_vector = other.m_vector;
    return *this;
}

The rest of your operators could use some const qualifiers.
E.g. PNVector operator+(const PNVector &rhs) [B]const[/B]; Don't forget that at() performs bounds checking, which is unnecessary
in many cases in your code. You could just use operator[] instead.

If you intend to also provide +=, *=, ... etc operators (which is a good idea), you
should implement +, *, ... etc in terms of +=, *=, ... and not the other way around.

I.e. it should look like this:

PNVector & PNVector::operator += (double val)
{
    // ...

    return *this;
}

PNVector PNVector::operator + (double val)
{
    PNVector ret(*this);

    ret += val;

    return ret;
}

Is the only solution to make this work to overload the binary * and / respectively?

Yes. You have to also write global operator overloads (note that both global
and member operators are binary operators, as they accept two arguments).

Finally, note that if …

m4ster_r0shi 142 Posting Whiz in Training

While multithreading is indeed the way to go in such cases, I believe the OP might be able to get away with just a _kbhit call.

#include <windows.h>
#include <conio.h>

#include <iostream>

int main()
{
    int counter = 0;
    char ch = 0;

    while (true)
    {
        ch = 0;

        if (_kbhit()) ch = _getch();

        // hit esc to quit
        if (ch == 27) break;

        std::cout << counter++;

        if (ch) std::cout << ' ' << ch;

        std::cout << std::endl;

        Sleep(150);
    }

    return 0;
}

By the way, something I've been wanting to ask for a while now, what does the 's' in "jsw" stand for?

sergent commented: much easier then Narue's. Same thing I had in mind! +5
m4ster_r0shi 142 Posting Whiz in Training

This isn't much of a challenge as it is now, so I decided to do the interesting stuff during compilation.

EDIT: A boost preprocessor array can't have more than 25 elements. That's why I had to split the letters like that.

#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/preprocessor/comparison/less.hpp>
#include <boost/preprocessor/arithmetic/add.hpp>
#include <boost/preprocessor/arithmetic/sub.hpp>
#include <boost/preprocessor/arithmetic/div.hpp>
#include <boost/preprocessor/arithmetic/mod.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/array/elem.hpp>
#include <boost/preprocessor/control/if.hpp>

#define LETTERS_a_m (13, ("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"))
#define LETTERS_n_z (13, ("n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"))
#define LETTERS_A_M (13, ("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M"))
#define LETTERS_N_Z (13, ("N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"))

#define LETTER_LOWER(n) \
BOOST_PP_IF(BOOST_PP_LESS(n, 13), \
    BOOST_PP_ARRAY_ELEM(n, LETTERS_a_m), \
    BOOST_PP_ARRAY_ELEM(BOOST_PP_SUB(n, 13), LETTERS_n_z))

#define LETTER_UPPER(n) \
BOOST_PP_IF(BOOST_PP_LESS(n, 13), \
    BOOST_PP_ARRAY_ELEM(n, LETTERS_A_M), \
    BOOST_PP_ARRAY_ELEM(BOOST_PP_SUB(n, 13), LETTERS_N_Z))

#define LETTER(z, n, letter_id) \
BOOST_PP_IF(BOOST_PP_LESS(letter_id, 27), \
    LETTER_LOWER(BOOST_PP_SUB(letter_id, 1)), \
    LETTER_UPPER(BOOST_PP_SUB(letter_id, 27)))

#define PRINT_LETTER(r, unused, n) \
BOOST_PP_REPEAT(BOOST_PP_ADD(BOOST_PP_DIV(n, 52), 1), LETTER, BOOST_PP_MOD(n, 52)) "\n"

#include <cstdio>

#define INPUT (1)(2)(4)(8)(16)(32)(50)(64)(100)(128)(150)

int main()
{
    const char * output = BOOST_PP_SEQ_FOR_EACH(PRINT_LETTER, ~, INPUT);

    printf(output);
    fflush(stdout);

    return 0;
}

Compiler output:

.file	"main.cpp"
	.def	___main;	.scl	2;	.type	32;	.endef
	.section .rdata,"dr"
LC0:
	.ascii [B]"a\12b\12d\12h\12p\12F\12X\12ll\12VV\12xxx\12TTT\0"[/B]
	.text
.globl _main
	.def	_main;	.scl	2;	.type	32;	.endef
_main:
	pushl	%ebp
	movl	%esp, %ebp
	andl	$-16, %esp
	subl	$16, %esp
	call	___main
	movl	$LC0, (%esp)
	call	_puts
	movl	__imp___iob, %eax
	addl	$32, %eax
	movl	%eax, (%esp) …
mrnutty commented: show off +13
m4ster_r0shi 142 Posting Whiz in Training

I want to do the same thing with a 3D vector. How would the code look?

You can do it like this:

vector<vector<vector<float> > > vec (5, vector<vector<float> > (5, vector<float> (5, 0) ) );

The above creates a 5 x 5 x 5 3D vector, with all initial values set to zero.

How do I index a 3D vector like this?

You can do it like this:

vec.at(1).at(2).at(3) = 5.5;

//or, if you don't want bounds checking...

vec[1][2][3] = 5.5;

However, for performance reasons, it would be better to create
a wrapper around a 1D vector that mimics 3D behaviour, like this:

#include <iostream>
#include <vector>

template <class T>
class Vector3D
{
public:

    Vector3D(unsigned size_i_, unsigned size_j_, unsigned size_k_):
        size_i(size_i_), size_j(size_j_), size_k(size_k_)
        { data.resize(size_i*size_j*size_k); }

    Vector3D(unsigned size_i_, unsigned size_j_, unsigned size_k_, const T & default_value):
        size_i(size_i_), size_j(size_j_), size_k(size_k_)
        { data.assign(size_i*size_j*size_k, default_value); }

    T & operator () (unsigned i, unsigned j, unsigned k)
        { return data[i*size_j*size_k + j*size_k + k]; }

        // or, if you want bounds checking...
        // data.at(i*size_j*size_k + j*size_k + k);

    const T & operator () (unsigned i, unsigned j, unsigned k) const
        { return data[i*size_j*size_k + j*size_k + k]; }

        // or, if you want bounds checking...
        // data.at(i*size_j*size_k + j*size_k + k);

    //...

    // more member functions
    // (e.g. resize etc...)

    //...

private:

    unsigned size_i;
    unsigned size_j;
    unsigned size_k;

    std::vector<T> data;
};

int main()
{
    Vector3D<int> v3d(2,3,4,100);

    v3d(1,2,3) = 0;

    std::cout << v3d(0,1,2) << std::endl;
    std::cout << v3d(1,2,3) << std::endl; …
m4ster_r0shi 142 Posting Whiz in Training

I don't know what you mean by saying "hook", but if you want to hide the console cursor, you can do it like this:

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

int main()
{
    HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_CURSOR_INFO cursor_info;

    GetConsoleCursorInfo(console, &cursor_info);

    cursor_info.bVisible = false;

    SetConsoleCursorInfo(console, &cursor_info);

    std::cout << "See? No cursor! -> ";

    Sleep(3000);
}

Useful links:

http://msdn.microsoft.com/en-us/library/ms683163(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/ms686019(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/ms682068(v=vs.85).aspx

m4ster_r0shi 142 Posting Whiz in Training

How about something less tricky. Something like this:

#include <windows.h>
#include <iostream>
#include <cmath>

bool IsPressed(int vkey) { return GetAsyncKeyState(vkey) >> 15; }

void MouseMove(int dx, int dy)
{
    POINT point; GetCursorPos(&point);
    SetCursorPos(point.x + dx, point.y + dy);
}

const double slope_max    = 1.35;
const double slope_change = 0.15;

const double line_length  = 16;

#define LOOP_BODY \
    dx =  cos(atan(slope)) * line_length; \
    dy = -sin(atan(slope)) * line_length; \
\
    mouse_event(MOUSEEVENTF_LEFTDOWN,0,0,0,0); \
    MouseMove(dx, dy); \
    mouse_event(MOUSEEVENTF_LEFTUP,0,0,0,0); \
\
    Sleep(25);

int main()
{
    std::cout << "hit F8 to begin" << std::endl;

    while (!IsPressed(VK_F8)) Sleep(25);

    double slope, dx, dy;

    for (slope = 0;           slope < slope_max; slope +=  slope_change) { LOOP_BODY }
    for (slope =  slope_max;  slope > 0;         slope -=  slope_change) { LOOP_BODY }
    for (slope = 0;          -slope < slope_max; slope += -slope_change) { LOOP_BODY }
    for (slope = -slope_max; -slope > 0;         slope -= -slope_change) { LOOP_BODY }
}
sergent commented: Thanks! I don't have time right now, I will try that soon! +4
m4ster_r0shi 142 Posting Whiz in Training

The setw manipulator has the same problem. It only affects the next output operation.
AFAIK, there is no way you can avoid setting the width over and over again.
Maybe someone else knows better though. Here's a simple hackish solution:

#include <iostream>
#include <sstream>

using namespace std;

class ostream_w : public ostream
{
    unsigned w;

public:

    ostream_w(ostream & os_, unsigned w_): w(w_)
    {
        rdbuf(os_.rdbuf());
    }

    template <class T>
    ostream_w & operator << (const T & t)
    {
        width(w);

        static_cast<ostream &>(*this) << t;

        return *this;
    }

    // necessary for endl
    ostream_w & operator << (ostream & (*pf)(ostream &))
    {
        pf(static_cast<ostream &>(*this));

        return *this;
    }
};

int main()
{
    ostream_w cout_w6(cout, 6);

    cout_w6.setf(ios::right);

    for (int row = 0; row <= 12; ++row)
    {
        for (int column = 0; column <= 10; ++column)
        {
            stringstream buffer;

            buffer << row << ":" << column;

            cout_w6 << buffer.str();
        }

        cout_w6 << endl;
    }

    return 0;
}
m4ster_r0shi 142 Posting Whiz in Training

As pseudorandom suggested, the first step would be to convert the integer to a string.
Alternatively, if you want to skip that step, you could just get a string from the user.

Now, let's take a look at the algorithm...

Suppose the user enters this -> "1234567890" . The result of add_commas("1234567890") should
be this -> "1,234,567,890" . One way to use recursion would be to make your function work as follows:

add_commas("1234567890") = 

add_commas("1234567") + "," + "890" = 

( add_commas("1234") + "," + "567" ) + "," + "890" = 

( ( add_commas("1") + "," + "234" ) + "," + "567" ) + "," + "890" = 

( ( "1" + "," + "234" ) + "," + "567" ) + "," + "890" = 

( "1,234" + "," + "567" ) + "," + "890" = 

"1,234,567" + "," + "890" = 

"1,234,567,890"

That is, if the string's length is 3 or less, add_commas should return the string intact. Otherwise, it should
break it into two parts, the right one consisting of the 3 rightmost digits and the left one being the rest
of the string. Then, the function should return add_commas(left_part) + "," + right_part Useful link -> http://cplusplus.com/reference/string/string/substr/

Encrypted hint -> Difdl!uif!uisfbet!J!tubsufe/

m4ster_r0shi 142 Posting Whiz in Training

Show me yours and I'll show you mine.

Am I the only one who keeps misinterpreting that?

sergent commented: lol +4
m4ster_r0shi 142 Posting Whiz in Training

I'm pretty sure the statement updating your population should be -> population *= (1 + annualBirth - annualDeath);

m4ster_r0shi 142 Posting Whiz in Training

You can use ReadProcessMemory:

#include <windows.h>
#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    char data[20] = "Hello, World!!!";

    char buffer[20] = { 0 };

    HANDLE my_process = GetCurrentProcess();

    unsigned long address = 0;

    cout << "(before) " << data << endl;

    while (true)
    {
        ReadProcessMemory(my_process, (LPCVOID) address, buffer, 20, 0);

        if (strcmp(data, buffer) == 0)
        {
            cout << "found it!" << endl;

            WriteProcessMemory(my_process, (LPVOID) address, "Yo! What's up?", 20, 0);

            break;
        }

        ++address;
    }

    cout << "(after) " << data << endl;

    cout << "(hit enter to quit...)"; cin.get();

    return 0;
}

[EDIT]

I didn't do it here, as this is just an example, but usually you'll
want to make few ReadProcessMemory calls with big buffers
instead of many ReadProcessMemory calls with small buffers.

It can make a huge difference in performance...

[/EDIT]

If you want to do this with other processes, you'll first have
to get the debug privilege and then use OpenProcess.

That's how you can get the debug privilege:

HANDLE my_process;
HANDLE htoken;
TOKEN_PRIVILEGES tp;
LUID luid;

my_process = GetCurrentProcess();
OpenProcessToken(my_process, TOKEN_ALL_ACCESS, &htoken);

LookupPrivilegeValue(NULL, "SeDebugPrivilege", &luid );

tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

AdjustTokenPrivileges(htoken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), 0, 0);

You can find additional info for all of these functions on MSDN:

http://msdn.microsoft.com/en-us/library/ms683179(v=vs.85).aspx (GetCurrentProcess)

http://msdn.microsoft.com/en-us/library/ms680553(v=vs.85).aspx (ReadProcessMemory)
http://msdn.microsoft.com/en-us/library/ms681674(v=vs.85).aspx (WriteProcessMemory)

http://msdn.microsoft.com/en-us/library/aa379295(v=vs.85).aspx (OpenProcessToken)
http://msdn.microsoft.com/en-us/library/aa379180(v=vs.85).aspx (LookupPrivilegeValue)
http://msdn.microsoft.com/en-us/library/aa375202(v=vs.85).aspx (AdjustTokenPrivileges)

sergent commented: You wrote A LOT +4
alwaysLearning0 commented: nice.. +4
m4ster_r0shi 142 Posting Whiz in Training

Try this:

//...

string = string.replace('\\', '/'); // replace \ with /
string = string.replace('\"', ' '); // replace " with space
string = string.trim(); // remove leading and trailing spaces

//...
m4ster_r0shi 142 Posting Whiz in Training

If you don't print anything how will you get abdc???

I'll try one last time.

(aa)abbbddccc# print 'a' or don't print?

a(aa)bbbddccc# print 'a' or don't print?

aa(ab)bbddccc# print 'a', print 'b' or don't print?

aaa(bb)bddccc# print 'b' or don't print?

aaab(bb)ddccc# print 'b' or don't print?

aaabb(bd)dccc# print 'b', print 'd' or don't print?

aaabbb(dd)ccc# print 'd' or don't print?

aaabbbd(dc)cc# print 'd', print 'c' or don't print?

aaabbbdd(cc)c# print 'c' or don't print?

aaabbbddc(cc)# print 'c' or don't print?

aaabbbddcc(c#) print 'c', print '#' or don't print?

I want you to give me an answer on every question above.
And remember, I want the final output to be this -> abdc

Narue commented: Some people are lost causes. Props for being optimistic. +17
m4ster_r0shi 142 Posting Whiz in Training

What you need is called dynamic memory allocation:

#include <iostream>

using namespace std;

struct Node {};

int main()
{
    int num_n;

    cout << "Enter number of nodes:\n";
    cin >> num_n;

    // Allocate memory dynamically

    Node * my_nodes = new Node[num_n];

    for (int i=0; i<num_n; i++)
    {
        // Set values of members of Node here

        // my_nodes[i] = ...
    }

    // Release memory when done

    delete[] my_nodes;
}

You could also use a vector:

#include <iostream>
#include <vector>

using namespace std;

struct Node {};

int main()
{
    int num_n;

    cout << "Enter number of nodes:\n";
    cin >> num_n;

    vector<Node> my_nodes(num_n);

    for (int i=0; i<num_n; i++)
    {
        // Set values of members of Node here

        // my_nodes[i] = ...
    }
}

Useful links:

http://cplusplus.com/doc/tutorial/dynamic/
http://cplusplus.com/search.do?q=vector

m4ster_r0shi 142 Posting Whiz in Training

Yes, in this case multithreading is the way to go. Well, since I have never used pthreads either (I'm a windows guy), I can't help you on this.

m4ster_r0shi 142 Posting Whiz in Training

It's an interesting topic, so I decided to investigate a bit.

The program you wrote does work with video games.
However, don't forget that in a video game the whole
window is redrawn many times a second. This means
your rectangle is visible merely for some milliseconds.

If you try something like this, you can actually see it:

#include <windows.h>

int main()
{
    HWND wnd;
    HDC dc;

    while (true)
    {
        if (GetAsyncKeyState(VK_ESCAPE) >> 15) break;

        wnd = GetForegroundWindow();
        dc = GetDC(wnd);

        Rectangle(dc, 0, 0, 200, 200);

        ReleaseDC(wnd, dc);

        Sleep(15);
    }
}

But there's a flickering problem, even if you remove the Sleep call.

I googled a bit and discovered the so called layered windows:
http://msdn.microsoft.com/en-us/library/ms997507.aspx

Using info from msdn, I whipped up a small test program:

#define _WIN32_WINNT 0x0500

#include <windows.h>

int main()
{
    HWND hwnd;
    HWND lwnd;
    HDC dc;

    SIZE size;
    POINT ptSrc = {0, 0};
    BLENDFUNCTION blend;

    lwnd = CreateWindowEx(WS_EX_LAYERED | WS_EX_TRANSPARENT |
                          WS_EX_TOOLWINDOW | WS_EX_TOPMOST,
                          0, 0, WS_POPUP | WS_VISIBLE,
                          0, 0, 200, 200, 0, 0, 0, 0);
    size.cx = 200;
    size.cy = 200;

    blend.BlendOp = AC_SRC_OVER;
    blend.BlendFlags = 0;
    blend.AlphaFormat = 0;
    blend.SourceConstantAlpha = 100;

    while (true)
    {
        if (GetAsyncKeyState(VK_ESCAPE) >> 15) break;

        dc = GetDC(lwnd);

        Ellipse(dc, 50, 50, 100, 100);

        ReleaseDC(lwnd,dc);

        hwnd = GetForegroundWindow();

        dc = GetDC(hwnd);

        UpdateLayeredWindow(lwnd, dc, 0, 0, 0, 0, 0, &blend, ULW_OPAQUE);

        ReleaseDC(hwnd,dc);

        Sleep(15);
    }
}

However, the flickering problem is still there...

The fact that the flickering remains …

m4ster_r0shi 142 Posting Whiz in Training

The problem is that your compiler doesn't know how to add/subtract complex numbers using operators +/-

A simple solution is to define two functions for these operations...

//...

cmplxNumber add_cmplx(const cmplxNumber & c1, const cmplxNumber & c2)
{
    //...
}

cmplxNumber sub_cmplx(const cmplxNumber & c1, const cmplxNumber & c2)
{
    //...
}

//...

...and then use them like this:

//...

C = add_cmplx(A, B);

//...

C = sub_cmplx(A, B);

//...
m4ster_r0shi 142 Posting Whiz in Training

Please, don't double post -> http://cplusplus.com/forum/general/45559/

Salem commented: Damn straight - well said! +17
m4ster_r0shi 142 Posting Whiz in Training

It's true. You can build games using C. But you can build better using C++.
Object oriented design helps a lot when you model the game world, entities
and entity interactions. Plus, there are very good libraries available to help.

As for your code request, I guess there are a couple of things I can give you...

The first was my first attempt to write a console based snake game. I attach the cpp file.

The second was an attempt to seduce a girl with an advanced version of the above.
You can get it here -> http://www.4shared.com/file/NXIQiQFA/love_snake.html

I'd appreciate it if you didn't ask whether the attempt was successful or not.

m4ster_r0shi 142 Posting Whiz in Training

This is called padding and it is done by your compiler to improve access speed of the struct members.

Useful link -> http://en.wikipedia.org/wiki/Data_structure_alignment#Data_structure_padding

m4ster_r0shi 142 Posting Whiz in Training

will that work if my program is running in the background of another program?

Absolutely. GetAsyncKeyState is perfect for implementing global hotkeys. And keyloggers :D

Here's a minimal example:

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

bool IsPressed(int virtual_key)
{
    return GetAsyncKeyState(virtual_key) >> 15;
}

int main()
{
    bool key_state[256] = { 0 };

    while (true)
    {
        // hit esc to quit
        if (IsPressed(VK_ESCAPE)) break;

        for (int i = 0; i < 256; ++i)
        {
            if (IsPressed((i)))
            {
                if (key_state[i] == false)
                {
                    key_state[i] = true;
                    std::cout << i << " was pressed!" << std::endl;
                }
            }
            else
            {
                if (key_state[i] == true)
                {
                    key_state[i] = false;
                    std::cout << i << " was released!" << std::endl;
                }
            }
        }
    }

    return 0;
}
PixelatedKarma commented: Excellent answer to the issue I was having +2
m4ster_r0shi 142 Posting Whiz in Training

You can try opening it for reading and check if it's open. If it's not open, it doesn't exist.

//...

#include <fstream>
#include <string>

//...

std::string filename;

//...

std::ifstream fin(filename.c_str());

if (fin.is_open()) { /* file exists */ }
else { /* file does not exist */ }

//...

Useful link -> http://cplusplus.com/doc/tutorial/files/

m4ster_r0shi 142 Posting Whiz in Training

Here's another one:

#include <iostream>

struct B
{
    virtual void print(const char * msg = "wtf? -.-")
    {
        std::cout << msg << std::endl;
    }

    virtual ~B() {}
};

struct D : B
{
    void print(const char * msg = "Hello, World!")
    {
        std::cout << msg << std::endl;
    }
};

int main()
{
    B * pb = new D;

    pb->print();

    delete pb;

    return 0;
}
mrnutty commented: nice 1 +13
mike_2000_17 commented: cool +11
m4ster_r0shi 142 Posting Whiz in Training

... you laugh with things like "Chuck Norris can dereference a void pointer." or "In Soviet Russia, functions call you."

sergent commented: :( I do it all the time +0
m4ster_r0shi 142 Posting Whiz in Training

Err... What is if(argc==1) { cout<<"Either use the -l or -ls arguments\n"; } doing down there? It should be the first thing inside main. In fact, it should be like this:

int main(int argc, char ** argv)
{
    if(argc == 1)
    {
        cout << "Either use the -l or -ls arguments\n";

        cout << "(hit enter to quit...)"; cin.get();

        return 0; // terminate the program
    }

    //...
}

What exactly is the problem again? What do you expect the program to do? What does it do?

Celtrix commented: thanks man that saved me a lot of trouble. +2
m4ster_r0shi 142 Posting Whiz in Training

Q1
The semicolon (;) just indicates the end of a statement. It has nothing to do with the end of the string.
When you use double quotes (") around text, your compiler kindly puts a null character at the end.

Q2
phrase is an array of 13 chars. This -> char phrase[] = "Game Over!!!"; is interpreted by the compiler as char phrase[13] = { 'G', 'a', 'm', 'e', ' ', 'O', 'v', 'e', 'r', '!', '!', '!', '\0' };

crapgarden commented: Very Helpful +3
m4ster_r0shi 142 Posting Whiz in Training

It's an interesting approach, but the scoped color idea is a bit awkward... I would do something like this:

#include <iostream>
#include <iomanip>
#include <windows.h>

struct Color
{
    int color;

    Color(int color_): color(color_) {}

    Color operator + (const Color & other) const { return Color(this->color | other.color); }
};

#define FORE_LIGHT(color) const Color _cfl##color = FOREGROUND_##color | FOREGROUND_INTENSITY;
#define BACK_LIGHT(color) const Color _cbl##color = BACKGROUND_##color | BACKGROUND_INTENSITY;
#define FORE_DARK(color)  const Color _cfd##color = FOREGROUND_##color;
#define BACK_DARK(color)  const Color _cbd##color = BACKGROUND_##color;

FORE_LIGHT(RED) FORE_LIGHT(GREEN) FORE_LIGHT(BLUE)
BACK_LIGHT(RED) BACK_LIGHT(GREEN) BACK_LIGHT(BLUE)
FORE_DARK(RED)  FORE_DARK(GREEN)  FORE_DARK(BLUE)
BACK_DARK(RED)  BACK_DARK(GREEN)  BACK_DARK(BLUE)

const Color _cdefault = _cfdRED + _cfdGREEN + _cfdBLUE;

std::ostream & operator << (std::ostream & os, Color color)
{
    return SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color.color), os;
}

int main()
{
    using std::cout; using std::setw; using std::endl;

    cout << std::setiosflags(std::ios_base::left);

    cout << "Hello, " << _cflRED                        << setw(6) << "Red"    << _cdefault << " World!" << endl;
    cout << "Hello, " <<           _cflGREEN            << setw(6) << "Green"  << _cdefault << " World!" << endl;
    cout << "Hello, " <<                       _cflBLUE << setw(6) << "Blue"   << _cdefault << " World!" << endl;
    cout << "Hello, " << _cflRED + _cflGREEN            << setw(6) << "Yellow" << _cdefault << " World!" << endl;
    cout << "Hello, " << _cflRED             + _cflBLUE << setw(6) << "Pink"   << _cdefault << " World!" << endl;
    cout << "Hello, " <<           _cflGREEN + _cflBLUE << setw(6) << "Cyan"   << _cdefault << " World!" << endl;
    cout << "Hello, " << _cblRED + _cblGREEN + _cblBLUE << setw(6) …
Ancient Dragon commented: nice :) +17