Labdabeta 182 Posting Pro in Training Featured Poster

Is there any tutorial, or information webpage, somewhere that would explain how to use wchar_t's and wfstream's? Do they act like normal char's and fstream's? How to I specify unicode characters in C++? How do wchar_t and wfstream respond to normal ASCII input (given that unicode is for the most part backwards compatible with ASCII)? Basically, could you show me an implementation of the function:

int countOccurencesOfUnicodeCharacter(const char *filename, int unicode)
{
    //somehow return the frequency of 'unicode' in the file specified by filename.
    //of particular interest to me is how to get unicode characters and how to compare with them.
}

Once I have the constituent parts of that function I should be able to adapt them to my needs.

Labdabeta 182 Posting Pro in Training Featured Poster

@NathanOliver yes, I know that ╠ happens to be expressible by ASCII 204, but some of my other symbols (like ₆ for example) are not expressible in ASCII, but rather require full Unicode (₆ is Unicode 2086 I think). I am not sure if locale will help me too much as I think it is more concerned with multiple interpretations of things, while Unicode is (theoretically) a universal standard.

@Suzie999 I think wchar_t is exactly the type who's name I was trying to remember (assuming that it is the one that supports full unicode?). Now I just need to know if I can extract those directly from an std::fstream object or if I have to do something special, and how to input my unusual symbols into my source files.

Note: I believe all of the symbols which I am referencing are a part of UTF-16 (none have Unicode values higher than FFFF), but I am not well educated on exactly how unicode works.

Labdabeta 182 Posting Pro in Training Featured Poster

Hello,

I have a file which I need to read which contains some unusual characters (EG: '╠') and I need to be able to read it and convert those characters to numbers. As an example of what I am looking for would be code that reads a file and prints "Found" whenever '╠' is encountered. How do I do this with native std::fstream compatibility?

EG:

void testFile(const char *str)
{
    std::fstream file(str);
    char temp;
    int count=0;
    while (!file.eof())
    {
        file>>temp;
        if (temp=='╠')//I highly doubt this would work
            count++;
    }
    cout<<"Found "<<count<<" ╠s"<<endl;
}

I am sure that there is a way to store unicode characters into a char, and I seem to recall its 'u####' or something like that, and I think I need a different type for my char, but for the life of me I can't seem to remember what it is called. On top of that I am unsure how reading those larger chars from std::fstream objects works.

Labdabeta 182 Posting Pro in Training Featured Poster

Heavy rain followed by negative temperatures = black ice... black ice everywhere :O. (Waterloo, ON... I think Toronto, ON too)

Labdabeta 182 Posting Pro in Training Featured Poster

I find that "Quinary son of a genetic algorithm" rolls of the tongue quite nicely when I want to let off some steam. As for a single word... Queueing's vowels sound awesome. (as noted by Randall http://xkcd.com/853/)

Labdabeta 182 Posting Pro in Training Featured Poster

Excellent response as usual! Of course I have implemented the logical functions, as well as optimized them as far as I possibly could. I was sort of hoping that the response would use them, at least to a certain extent.

That method also has the benefit of often only doing very simple bitwise operations (bitshift by 1 bit [or 8 bits unrolled], check last bit, etc) which can be done extremely quickly on my raw data.

Thank you.

Labdabeta 182 Posting Pro in Training Featured Poster

Yeah, sorry about that. I actually have the class wrapped in a namespace so that ambiguity is avoided. Does that count as a valid naming convention? (IE: LAB::Int)

Labdabeta 182 Posting Pro in Training Featured Poster

These are arbitrary-precision integer datatypes, sorry if I didn't make that clear. IE: Not int but Int which is a class that stores integers in an array of smaller integers.

Labdabeta 182 Posting Pro in Training Featured Poster

There are a few issues with your code, however the one causing the issue is a simple OBOE (off-by-one-error). The number one thing that jumps out at me is that you really should be using an array here, it will literally make the part of the code that deals with word## 10 times smaller!

In case you are not familiar with arrays, they are (for the purposes of this discussion) a way to make a large number of variables that you can index with a number. You declare them with square brackets.

Another thing that will make your code easier to read (and thus easier to fix) would be to modulize more. Each function should do a simple task, so having one function that does multiple tasks makes it hard to read.

In the end, the WordCharacter function should end up looking like this:

//this function does the job of removing punctuation from a string
string removePunctuation(string input)
{
    string temp = input;
    int punct = 0;
    int length = temp.length();
    for (int x = 0; x < length; x++)
    {
        if (ispunct(temp.at(x)))
            punct++;
    }
    int x1 = 0;
      for (int x = 0; x < length; x++)
    {
        if (!ispunct(temp.at(x)))
            temp.at(x1++) = temp.at(x);
    }
    return temp;
}

//deal with number in main() only deal with printing the number of words of each length here
void printWordCharacter(string &input)
{
    int word[10];//declare 10 ints called word[0], word[1], etc... (note that they start at 0, not 1)
    string newString;//newString is a …
Labdabeta 182 Posting Pro in Training Featured Poster

Hello,

I wrote a library for arbitrary precision arithmetic recently and spent a long time implementing efficient multiplication algorithms. Now I am looking to see if it is possible for me to optimize anywhere else. One place that I thought should be more optimizeable is my division algorithm. Right now I use (hiding some internal implementation stuff):

Int divide(Int numerator, Int denominator)const
{
    if (denominator==0)
        return DIVIDE_BY_ZERO_ERROR;
    if (numerator==0)
        return 0;
    if (numerator.sign()!=denominator.sign())//result is negative
        return -((-numerator)/denominator);
    if (numerator==denominator)
        return 1;
    Int num=numerator.abs();
    Int den=denominator.abs();
    Int ret=0;
    while (num>den)
    {
        ret++;
        num-=den;
    }
    return ret;
}

Which is fairly slow, especially since subtraction takes awhile when done on Int's instead of on the individual digits of those Int's. Is there a faster way to get the integer part of the quotient of two numbers? Perhaps one that actually uses their internal digit-array representation?

Labdabeta 182 Posting Pro in Training Featured Poster

You have 1 syntax problem and a few redundancy problems. First lets tackle the syntax problem so that you can get your code to run.

The syntax error is that void distance(miles) is not valid C++ code. When you have parameters in a function it must have a type. What you want is void distance(double miles) which is exactly what you wrote in the class description.

This leads to the next issue, namely that you are going to end up asknig the user for the miles variable twice. Instead you want to pass miles into the function, like vmanes said. Thus your fixed distance function is:

void distance(double miles) {
    fuelLevel-=miles/mpg;
}

Finally, there is a redundancy in your constructor. While it works fine, it is very silly. Here is your constructor:

Car::Car(double mpg, double capacity): mpg(mpg), fuel_capacity(capacity){
mpg = mpg;
fuel_capacity = capacity;
fuelLevel = 0.0;
}

Which is essentially the same as:

Car::Car(double mpg, double capacity): mpg(mpg), fuel_capacity(capacity){
//:mpg(mpg) becomes:
mpg = mpg;
//:fuel_capacity(capacity) becames:
fuel_capacity = capacity;
//now the next two lines are redundant:
mpg = mpg;
fuel_capacity = capacity;
fuelLevel = 0.0;
}

A better constructor is:

Car::Car(double mpg, double capacity):  mpg(mpg), 
                                        fuel_capacity(capacity),
                                        fuelLevel(0.0)//you can set these to values too
                                        {/*no function body at all!*/}

Hope this helps!

Labdabeta 182 Posting Pro in Training Featured Poster

You have 1 syntax problem and a few redundancy problems. First lets tackle the syntax problem so that you can get your code to run.

The syntax error is that void distance(miles) is not valid C++ code. When you have parameters in a function it must have a type. What you want is void distance(double miles) which is exactly what you wrote in the class description.

This leads to the next issue, namely that you are going to end up asknig the user for the miles variable twice. Instead you want to pass miles into the function, like vmanes said. Thus your fixed distance function is:

void distance(double miles) {
    fuelLevel-=miles/mpg;
}

Finally, there is a redundancy in your constructor. While it works fine, it is very silly. Here is your constructor:

Car::Car(double mpg, double capacity): mpg(mpg), fuel_capacity(capacity){
mpg = mpg;
fuel_capacity = capacity;
fuelLevel = 0.0;
}

Which is essentially the same as:

Car::Car(double mpg, double capacity): mpg(mpg), fuel_capacity(capacity){
//:mpg(mpg) becomes:
mpg = mpg;
//:fuel_capacity(capacity) becames:
fuel_capacity = capacity;
//now the next two lines are redundant:
mpg = mpg;
fuel_capacity = capacity;
fuelLevel = 0.0;
}

A better constructor is:

Car::Car(double mpg, double capacity):  mpg(mpg), 
                                        fuel_capacity(capacity),
                                        fuelLevel(0.0)//you can set these to values too
                                        {/*no function body at all!*/}

Hope this helps!

Labdabeta 182 Posting Pro in Training Featured Poster

I am not 100% sure what you are asking since I can't access the code. However I think I understand what you are asking. You have two classes that refer to each other and want to have each in their own headers. The key to remember is that the #include "fileName.h" line acts identically to a copy-paste of the contents of fileName.h into your file, turning your entire program into one big file (see http://en.cppreference.com/w/cpp/language/translation_phases).

To have two classes refer to each other in one file this is how you do it:

#include <iostream>
class A; //forward declaration of class A
class B; //forward declaration of class B
class A
{
    B *b;
    public:
    A():b(NULL){}
    A(B *b):b(b){}
    A &set(B *b){this->b=b;return *this;}
    A &print(){std::cout<<"A"<<std::endl;return *this;}
    B *get(){return b;}
};
class B
{
    A *a;
    public:
    B():a(NULL){}
    B(A *a):a(a){}
    B &set(A *a){this->a=a;return *this;}
    B &print(){std::cout<<"B"<<std::endl;return *this;}
    A *get(){return a;}
};
int main()
{
    A a;
    B b(&a);
    a.set(&b);
    a.print();
    b.print();
    a.get()->print();
    b.get()->print();
    return 0;
}

Which works as expected, printing ABBA across four lines. Now when we make our header files we want to ensure that including them generates the same code. As such we link the class files with a header file that contains the forward declarations, like so:

AB.h:

#ifndef AB_H
#define AB_H

#include <iostream>

class A;//forward declaration
class B;//forward declaration

#include "A.h"
#include "B.h"

#endif //AB_H

A.h:

#ifndef A_H
#define A_H

class A
{
    B *b;
    public:
    A():b(NULL){}
    A(B *b):b(b){}
    A &set(B …
Labdabeta 182 Posting Pro in Training Featured Poster

Ah, perfect. Thank you. :)

Labdabeta 182 Posting Pro in Training Featured Poster

Thanks for the clarification, but what really has me confused is that I can't seem to force explicit conversion either. It makes sense why a=b would be ambiguous, because it has to choose between B->A->const A&->A and B->double->int->A but when I explicitly say a=(A)b why does it call the A constructor on an implicitly cast version of b instead of calling the A operator in b? Is there a way to explicitly call a typecast operator?

Labdabeta 182 Posting Pro in Training Featured Poster

Hello,

I have a particular set up of cast operators and constructors which is leading to a compile-time ambiguity error. I am wondering if somebody can explain why this is happening and what can be done to fix it.

For example, here we have 2 classes:

class A
{
    int val;
    public:
    A(){val=0;}
    A(const A& o){val=o.val;}
    A(int i){val=i;}
    A&operator=(const A&o){val=o.val;return *this;}
    A&operator=(int i){val=i;return *this;}
    operator int(){return val;}
};
class B
{
    int val;
    public:
    B(int i){val=i;}
    operator A(){return A(val);}
    operator double(){return 0.0;}
};

They work fine but don't really do anything at all. The purpose of the A operator in B is to allow such constructs as a=(A)b. However when I try to compile this:

A a;
B b(7);
a=(A)b;

or even this:

A a;
B b(7);
a=b;

I get a compiler error telling me that there is an ambiguous call. I can understand which functions are being called ambiguously, but I would have thought that conversion would only go one level deep (b becomes type A, gets copied to a) why would the compiler even try the implicit int conversion on the A version of b? or the conversion path of B->double->int->A?

Labdabeta 182 Posting Pro in Training Featured Poster

The issue is that you set charges=number*PRICE_CONSTANT each time, without saving the old value. Basically here is what happens if you trace charges (program tracing is a very valuable debugging tool):

Charges: ??? (since its un-initiated it could be anything, changing line 24 to double charges=0.0; would fix this)
Choice: Coffee, number: 2
Charges: 2.00 (charges=number*COFFEE;//=2*1.00=2.00)
Choice: Hot Chocolate, number: 1
Charges: 1.25 (note that the old value of 2.00 is gone)
Choice: EXIT
Charges: 1.25, TOTAL: 1.25

The solution is thus to add charges to total as you create them. Moving line 77 to just after line 71 should fix your problem.

Labdabeta 182 Posting Pro in Training Featured Poster

Check your types, noting that char x[] is identical to char *x. So you can think of char *colors[3][10] as being the same as char ***colors or char colors[][3][10] either way you can see that colors is one level of pointers too deep. Removing the * on line 5 should fix the issue.

Labdabeta 182 Posting Pro in Training Featured Poster

For learning GameMaker there are these tutorials: http://sandbox.yoyogames.com/make/tutorials (Note: I haven't actually checked them out, so I am not sure if they are any good)

For learning C++ console applications there are these tutorials:
http://www.learncpp.com/

For learning SDL (2D graphics) in C++ there are these tutorials:
http://lazyfoo.net/SDL_tutorials/

As for learning OpenGL (3D graphics) that is a much larger endeaver. One which admittedly I have yet to complete. I have not found any good up-to-date tutorials. I taught myself using NeHe productions, but have been told that the resulting code is extremely out of date. If you find a good up-to-date OpenGL tutorial, please, let me know!

Once you have made a few C++ games I would suggest looking into learning other languages and other engines. Some things to look into would be such tools as the Unity (C#) and Unreal (C++/URS) game engines.

Labdabeta 182 Posting Pro in Training Featured Poster

Making games is difficult. I would put off making your current idea for a game until later and here is why.

Ideas are cheap in the game industry. If you think about, say, the novel industry a good unique idea is valuable. The reason is that most good book ideas have already been used, so having a unique idea is very valuable, then all it takes is time, effort and a good editor and anybody with a real unique idea can become a bestseller. However the video game industry has the opposite situation. Everybody has plenty of unique ideas that would create wonderful games, but not enough people have the skills necessary to create a game and fewer still the will to actually make the games a reality.

My advice is to save your idea away until you are comfortable making games, and then pull it out to make a game out of it. Your first game should be simple, a game with easy mechanics, definately in 2D, and simple graphics and sounds. The reason is that until you have made a game you can't really appreciate just how much work it takes to make all the resources come together. Every single game I have made took me at least 2x as long as I had planned, either because of a programming bug, or a difficult mechanic, or just about anything!

As for getting started with making games I would suggest you start with a game engine, such as

Labdabeta 182 Posting Pro in Training Featured Poster

I am not certain due to the ambiguity in your post, but I think you want to know how to do a deep copy. That is, how to copy pointer values of one class to another such that they don't point to the same object. For this I would point you to mike_2000_17's RAII tutorial (http://www.daniweb.com/software-development/cpp/tutorials/373787/beginning-c0x-making-a-raii-class) however the basis behind a deep copy is to create a duplicate of whatever data is pointed to.

Labdabeta 182 Posting Pro in Training Featured Poster

The solution will depend on your specifications, you are being very vague about how you want to encrypt it.

If all you want to do is make it hard for somebody to use unless they have a decryption key you can just open the .exe file as you would any other binary file (see binary flag http://www.cplusplus.com/reference/fstream/fstream/open/ ) and load its data into variables, manipulate it in some hard to reverse way, then save it back to the file. Of course this means that the file will no longer run as an executable unless you decrypt it.

So, assuming you have a function that can take a string of numbers and encrypt them this code should work:

#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

vector<int> encrypt(vector<int> in)
{
    //here you encrypt the 'in' vector and return it
}

int main()
{
    fstream file("myExecutable.exe",ios_base::in|ios_base::binary);
    vector<int> data;
    while (!file.eof())//load the whole file into data
    {
        int temp;
        file>>temp;
        data.push_back(temp);
    }
    vector<int> encryptedData;
    encryptedData=encrypt(data);
    file.close();
    file.open("myExecutableEncrypted.exe",ios_base::out|ios_base::binary);
    for (int i=0;i<encryptedData.size(); ++i)
        file<<encryptedData[i];
    file.close();
    return 0;
}

Of course you should also have decryption functionality or all you will be doing is corrupting executables. Hope this helps.

Labdabeta 182 Posting Pro in Training Featured Poster

I am not sure exactly what you mean by #2, but I can tell you about #1. The difference is that, as far as I know, you cannot create an array variable without setting it to point to a value. Specifically when you say int a[5]={1,2,3,4,5}; it sets a to point to the address where the 1 is stored, while ensuring that 2,3,4,5 are in the following address spaces. If you were to then move where a points you would have an issue because you would lose access to your original array (and I am not sure if C would clean it up for you). However, in the context of function parameters arrays and pointers can be used almost interchangeably. For example:

void arrayTest(int a[])
{
    a[0]=7;
}

Is the same as:

void pointerTest(int *a)
{
    *a=7;
}

Just like:

int arrayAccess(int a[])
{
    return a[7];
}

Is the same as:

int pointerAccess(int *a)
{
    return *(a+7);
}

And of course a[7] and *(a+7) can be interchanged.

So the reason we declare pointers seperately is two-fold:

1) It doesn't automatically create the object we wish to point to.
2) It describes what the variable is, making code more legible.

Labdabeta 182 Posting Pro in Training Featured Poster

Step 1: Install Compiler/IDE (I like to use Code::Blocks/G++)
Step 2: Write program (You can learn C++ from many sites, I taught myself using learncpp.com)
Step 3: Compile program (I set up Code::Blocks to use g++, but using the built-in MinGW works too)

My guess is that you have either been skipping class, or not paying attention during it, and now an assignment is due and you want strangers on the internet to do your assignment for you. If that is the case you have come to the wrong site. However if you need help fixing your code or IDE or compiler, that is where we can help. We will not do your work for you, but we are happy to help you once you have made a genuine effort.

Labdabeta 182 Posting Pro in Training Featured Poster

Basically, when a function is called in assembly language (which is what your C++ code gets turned into by the compiler) it actually takes real time to set up the function and return from it. In pseudocode this is what a function actually is (C++ hides this from you):

  1. Save all temporary variables that you use (Assembly has a finite number of temporary registers, if you want to use one you have to save its state)
  2. Load the arguments of the function into some of those temporary variables.
  3. Use those variables somehow.
  4. Save the result in a special temporary variable (or to memory)
  5. Load all the same registers again.
  6. Return from the program.

So you can imagine that this:

int add(int a, int b)
{
    return a+b;
}
//...
int c;
c=add(1,2);

Becomes something more like this in assembly (obviously the code shown is not a real assembly language):

add://its a label, thats what assembly uses a lot of, please don't use them often in C++
    //this 'function' assumes that r0 (one of the temp registers) contains a
    //  and that r1 (another register) contains b already!
    push r2 //if we want to use r2 (yet another register) we need to save its state on the stack
    r2=r0+r1 //or more likely add r2,r0,r1, but the point is to store the value in r2
    //now lets assume we 'return' the value by storing it back into r0
    r0=r2
    pop r2 //reset the value of the register we …
Labdabeta 182 Posting Pro in Training Featured Poster

The issue is that char is an integer type, so a+b will add the ASCII values of a and b, which gives weird output. Converting them to strings works fine, except that strcat uses char* c-style strings and you used std::string c++ style strings.

Here you have 2 options:

Option A: C-Style strings

char result[3];//a,b,NULL
result[0]=a;
result[1]=b;
result[2]=0;//null terminate

cout<<result<<endl;

Option B: C++-Style strings

string c=(string)a;
string d=(string)b;

cout<<c+d<<endl;

For obvious reasons the C++ style is usually considered better. However the c-style version likely takes less memory. Both should work though.

Hope this helps!

Labdabeta 182 Posting Pro in Training Featured Poster

Thank you very much.

Labdabeta 182 Posting Pro in Training Featured Poster

Hello,

I have a quick question about c/c++ syntax. Basically I am wondering when it is allowable to have numbers in identifiers. My compiler happens to allow numbers in:

  • Function names
  • Class names
  • Variable names
  • Pre-processor names

As long as they do not begin with numbers. Is this standard functionality? I just ask because it feels weird to have a function called euler2 (for calculating eulerian numbers of the second kind). Is there any reason I should rename it to eulerTwo?

I checked the ISO C specification and it seems to suggest that it should be okay for all identifiers, but then it is rather vague about what identifiers are, exactly.

For now I am assuming that this is okay, I just wanted to double check and could not find anything else about this online.

Thanks.

Labdabeta 182 Posting Pro in Training Featured Poster

Hello,

I have used taylor polynomials to approximate floating-point values before. I am wondering whether there is a way to still apply them to functions with complex arguments, and if there is a way what its constraints would be. For example, to calculate the sine of a floating-point number to a specific precision I keep adding terms until the error value is less than the precision. However, I noticed (by testing it with the taylor expansion of ln(x) ) that this gives the wrong value when I use complex numbers (with the standard operators appropriately defined). For example:

ln(0.5)~=-(0.5+(0.5^2)/2+(0.5^3)/3)     --- gives -0.66, real is -0.69                Close enough
ln(0.5i)~=-(0.5i+(0.5i^2)/2+(0.5i^3)/3) --- gives -0.25+0.33i, real is -0.69+1.57i    WHAAT?!

How can I approximate imaginary functions to within an error range? Basically I need a method such that if I give you any given function's definition, a complex number, and a rational number (floating-point value) you can give me the value of that given function, at that given complex number, accurate in both real and imaginary parts, to within +- the given rational number. Clearly standard taylor polynomials dont always work, so what does?

Labdabeta 182 Posting Pro in Training Featured Poster

The issue is that inFile isn't global, so every single function gets its own brand new version of inFile. The result is that you open it, then close it, then start trying to extract data from nothing. Either make inFile global, or pass it to each function that uses it and your problem should go away.

Labdabeta 182 Posting Pro in Training Featured Poster

You should initialize it to MAX_ITERATIONS, just in case you never get a term less than 0.00001.

Labdabeta 182 Posting Pro in Training Featured Poster

cout<<"There were "<<numIterations<<" terms used in the series approximation."<<endl;

The whole point of saving i to numIterations is because outside the for loop 'i' doesn't exist, so its value (if it exists at all) is undetermined. The 'i' you created on line 65 is NOT the same 'i' as the one in the for loop.

Labdabeta 182 Posting Pro in Training Featured Poster

Can you upload your new code so I can see where the issue is?

Labdabeta 182 Posting Pro in Training Featured Poster

Your problem is that when you check that each term is >.0001 you check it against x. Your term is not x, its pow(x,2*i)/factorial(2*i) so you just need to modify your for loop. There is another problem however. The 'i' in your loop will be out of scope on line 96 (which will never be reached because its after a return statement). Also your loop will always loop 100 times because you never told it to 'break'. Here is your corrected loop:

int numIterations;
for (int i=0; i<=MAX_ITERATIONS; i++)
{
    //save the value of the term:
    double term=pow(x,2*i)/factorial(2*i);

    //Test the values
    if (i==0||fabs(term)>0.00001)
    {
        if (i%2==1) //if i is odd
            sum-=term;//a-=b is the same as a=a-b
        else 
            sum+=term;
    }
    else //we are done, we need to save 'i' and leave the loop
    {
        numIterations=i;
        break;
    }
}

cout<<"There were "<<i<<" terms used in the series approximation"<<endl;
return sum;
Labdabeta 182 Posting Pro in Training Featured Poster

Thank you, this should be perfect.

Labdabeta 182 Posting Pro in Training Featured Poster

That works fine, except it still renders the drawing to the screen does it not? I want to render directly into the pixel array without drawing to the screen, if at all possible.

By reading the description of glReadPixels from the link it says that it returns data from the framebuffer, I assume there must be a way to redirect it, I just don't understand what the framebuffer is or how I can get/set it. From what I understand I will have to create some kind of buffer (it looks like I will need a pixel buffer) and bind it to the framebuffer somehow using glBindBuffer? What is the code to do this?

Labdabeta 182 Posting Pro in Training Featured Poster

There are a few problems with your code, but the only critical errors are in the calculate function so I will start there.

First of all when you declare temp and x you dont give them values, so they can be any value they want. This means that when you say:

temp = temp - (pow(ang, i+1)/factorial(i));

The result could, technically, be anything!

Secondly your implementation is extremely redundant. Trace the i in your for loop and you will see that it is always odd, so only one of your if statements will ever execute. Not to mention the fact that you could have merely used an else statement to write the second if.

Finally there is the overall logical error. The pseudo-code for computing cosines is as follows:

Option 1: Count by 2s, store (-1)^n
1. Set the total sum to 0.
2. Set the subtract flag to false. (We add the first term)
3. Set the counter, i, to 0. (This is your for loop)
4. Set temp to the current term: temp=x^i/i!
5. If the subtract flag is true negate temp.
6. Invert the subtract flag
7. Add temp to the sum.
8. Add 2 to i
9. Go to 3

Option 2: Count by 1s, calculate 2n
1. Set the total sum to 0.
2. Set the counter, i, to 0. (This is your for loop)
3. Add (-1^i)x^2i/2i! to the sum.

mike_2000_17 commented: Nice and thorough! +14
Labdabeta 182 Posting Pro in Training Featured Poster

Hello,

I can get OpenGL to render 3D scenes to the screen, but I want to render them to a pixel array. Basically I want some magical code to fill in the blanks for this code segment:

int width=500;
int height=500;
uint32_t *colours=new uint32_t[width*height];

//Magic code!

glBegin(GL_TRIANGLES);
//other drawing stuff, preferably no magic here?
glEnd();

//Magic code!

uint32_t c=*colours;//c should be the top-left pixel rendered by opengl

From my research it seems as though I should use a framebuffer object to do this, I am just not sure exactly how they work. Any help?

Labdabeta 182 Posting Pro in Training Featured Poster

Hello,

Unfortunately I learnt OpenGL from NeHe tutorials, which means that all of my current methods for OpenGL-ing are extremely deprecated. I tried to find a more up-to-date tutorial, but all they seem to do is teach how to get really complicated stuff out of OpenGL. I just want to know: What is the current method of drawing 3D triangles with either coloured or textured vertices to the screen?

I know how to use the simple:

glBegin(GL_TRIANGLES);
//Draw a colourful triangle:
    glNormal3f(nx,ny,nz);//where nx,ny,nz are calculated based on the vertices

    glColour3b(a,b,c);//I usually use a preprocessor to allow my canadian spelling
    glVertex3f(a,b,c);
    glColour3b(a,b,c);
    glVertex3f(a,b,c);
    glColour3b(a,b,c);
    glVertex3f(a,b,c);
//Draw a textured triangle:
//I actually forget how to load a new texture for each triangle, since I usually use 1 texture for all my triangles
    glNormal3f(nx,ny,nz);//again
    glTexCoord3f(a,b,c);
    glVertex3f(a,b,c);
    glTexCoord3f(a,b,c);
    glVertex3f(a,b,c);
    glTexCoord3f(a,b,c);
    glVertex3f(a,b,c);
glEnd();

I also know how to embed the above into a display list and then call that.

From what I have read, both of the above are considered depricated since they really don't use much effective hardware accelleration. I want to know what the current technique for doing this simple task is, without having to include a ton of extra files.

Basically, I need to be able to implement a function like this: (here by 'like' I mean similar to, I realize my data structures may not 'agree' with OpenGL)

struct Vector3D
{
    float x,y,z;
};
struct Coord2D
{
    int x,y;
};
typedef uint32_t Colour;//0xAARRGGBB
struct ColourTriangle
{
    Vector3D a,b,c,n;//n …
Labdabeta 182 Posting Pro in Training Featured Poster

Okay, here goes:

//                  A | B | C 
TOH(3,A,B,C)//     123|   |   
{
    if (3==1)
    {//it doesn't matter what's in here anyways
    }
    TOH(3-1,A,C,B);//note that B,C got switched
    //the above actually moves 3-1=2 disks from A to C
    //              A | B | C
    //              3 |   | 12
    //we will look at how it does this next
    move from A->B;// | 3 | 12
    TOH(3-1,C,B,A);//note that A,C got switched
    //the above actually moves 3-1=2 disks from C to B
    //              A | B | C
    //                |123|
    //ta-da!
}
//now we need to look at TOH(2,A,C,B) [line 7]
//                  A | C | B <-- note the new order!
TOH(2,A,C,B)//      12|   | 
{
    if (2==1)
    {//it doesnt matter
    }
    TOH(2-1,A,B,C);//note that C,B got switched
    //the above actually moves 2-1=1 disk from A to B
    //              A | C | B
    //              2 |   | 1
    //We will also look at this later
    move from A->C;   | 2 | 1
    TOH(2-1,B,C,A);//note that order is reversed
    //the above actually moves 2-1=1 disk from B to C
    //              A | C | B
    //                | 21|
    //ta-da!
}
//now we also need to look at TOH(2,C,B,A) [line 13]
//however it should be clear that it will work exactly like the ones above
//so we can be pretty sure that it WILL correctly move 2 disks from C to B

//finally lets look at TOH(1,A,B,C) [line 26]
TOH(1,A,B,C)//<---Read: Move 1 disk from A to B
{
    if (1==1)
    {
        move from A->B;//yay! …
Labdabeta 182 Posting Pro in Training Featured Poster

Its actually not changing num at all. Instead it creates a brand new version of num in the next function call, starting from scratch. You can picture recursive functions as infinite code like this:

void printNum(int num)
{
    cout<<num;
    if (num<9)
    {
        printNum(num+1);
    }
    cout<<num;
}

//is basically the same as:
void printNum(int num)
{
    cout<<num;
    if (num<9)
    {
        //this is what printNum(num+1) does:
        int num2=num+1;
        cout<<num2;
        if (num2<9)
        {
            //this is what printNum(num2+1) does:
            int num3=num2+1;
            //etc...
        }
    }
    cout<<num;
}

This is because each function call is isolated from the others. A decent example is a recursive fibonacci example. I assume you know the fibonacci sequence. It is defined as f(x)=f(x-1)+f(x-2) and of course f(x-1)=f((x-1))=f((x-1)-1)+f((x-1)-2), etc. So a common recursive implementation of the fibonacci sequence is:

int fibonacci(int x)
{
    if (x<2)//f(1)=f(0)=1
        return 1;
    return fibonacci(x-1)+fibonacci(x-2);
}

In this example the execution for fibonacci(3) is:

fibonacci(3){
    if (3<2)
        return 1;//nope
    return fibonacci(3-1)+fibonacci(3-2);
}
//now we have called fibonacci(3-1) = fibonacci(2) so we have to find out what that is:
fibonacci(2){
    if (2<2)
        return 1;//still nope :C
    return fibonacci(2-1)+fibonacci(2-2);
}
//now we have called fibonacci(2-1) = fibonacci(1) so we have to find out what that is:
fibonacci(1){
    if (1<2)
        return 1;//yay!
    //we never get here anyways!
}
//so fibonacci(1)=1, so fibonacci(2)=1+fibonacci(2-2)
//now we have called fibonacci(2-2) = fibonacci(0) so we have to find out what that is:
fibonacci(0){
    if (0<2)
        return 1;//yay still
    //again, we dont care about what is here
}
//so fibonacci(0)=1, …
Labdabeta 182 Posting Pro in Training Featured Poster

Ok, thanks. I was thinking maybe there existed a way to duplicate the block in memory where the class is stored and use that, but I guess that would require a sizeof(Base*)<==>sizeof(Derived) situation which isn't really possible.

PS: I have GOT to start remembering my virtual destructors >< thanks for the reminders!

Labdabeta 182 Posting Pro in Training Featured Poster

Ok, I did it! Now its your turn.

This forum is not for people to do things for you. Its to help you. Make an attempt before asking for help.

Instead of posting "Write this for me!" post "I wrote this: <code here> but it doesn't work, can you explain why?"

As for the function you intend to write, it is a fairly rudimentary example of C++ syntax. If you understand how functions, variables and if statements work then you should be fine.

Labdabeta 182 Posting Pro in Training Featured Poster

This is a classic problem in computer science. Basically it is a neat case of induction.

For towers named A,B,C:
Start with a tower of just 1 disk. Transferring it is as easy as moving it from A->C.

If you have more than 1 disk its a bit more complicated. Start my moving all but 1 disk to the extra peg. How? By following these same instructions! Next move the biggest disk onto the final peg. Next move all the other disks from the extra peg to the final peg. This can also be done by following the same steps. Now you are done!

The key is that you change which peg is the initial, final, and extra peg, then keep recursively moving smaller towers until all you need to do is move towers of 1 disk, which is easy!

This is exactly what your code does.

1 disk: if only 1 disk, then move it.

if (d==1)
{
    cout<<"\nShift top disk from tower"<<tower1<<"to tower"<<tower2;
    return;
}

n+1 disks:
Step 1: move n disks to extra tower (tower3), while doing this the final tower (tower2) acts as the extra tower.

TOH(d-1,tower1,tower3,tower2); //TOH(n,initial,final,extra)

Step 2: move 1 disk to final tower (tower2)

cout<<"\nShift top disk from tower"<<tower1<<"to tower"<<tower2;

Step 3: move n disks from the extra tower (tower3) to the final tower (tower2) using the initial tower (tower1) as the extra.

TOH(d-1,tower3,tower2,tower1);

So for d=3 you have: (using A,B,C as the …

ddanbe commented: For the effort :) +15
Labdabeta 182 Posting Pro in Training Featured Poster

Hello,

I am working on an event driven library and am having one minor problem. Basically I have two ways to get what I want done.

Method 1: Smart pointers and factory functions

#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class Object
{
    public:
    virtual int getInt(){return 0;}
    static shared_ptr<Object> create()
    {// of course this could be replaced with the templated version to make it work for any constructor
        return shared_ptr<Object>(new Object());
    }
};
class One:public Object
{
    public:
    virtual int getInt(){return 1;}
    static shared_ptr<One> create()
    {
        return shared_ptr<One>(new One());
    }
};
class Incrementer:public Object
{
    int x;
    public:
    Incrementer():x(0){}
    Incrementer(int i):x(i){}
    virtual int getInt(){return x++;}
    static shared_ptr<Incrementer> create()
    {
        return shared_ptr<Incrementer>(new Incrementer());
    }
};
class Scene
{
    vector<shared_ptr<Object> > os;
    public:
    Scene &add(shared_ptr<Object> o)
    {
        os.push_back(o);
        return *this;
    }
    Scene &print(){
        for (size_t i=0; i<os.size(); ++i)
            cout<<os[i]->getInt()<<endl;
        return *this;
    }
};
int main() {
    Scene s;
    s.add(One::create());
    s.add(Incrementer::create());
    s.print().print().print();
    return 0;
}

Method 2: Clone function

#include <iostream>
#include <vector>
using namespace std;
class Object
{
    public:
    virtual int getInt(){return 0;}
    virtual Object* clone(){return new Object;}
};
class One:public Object
{
    public:
    virtual int getInt(){return 1;}
    virtual One* clone(){return new One;}
};
class Incrementer:public Object
{
    int x;
    public:
    Incrementer():x(0){}
    Incrementer(int i):x(i){}
    virtual int getInt(){return x++;}
    virtual Incrementer* clone(){return new Incrementer(x);}
};
class Scene
{
    vector<Object *> os;
    public:
    Scene &add(Object *o)
    {
        os.push_back(o->clone());
    }
    Scene &print(){
        for (size_t i=0; i<os.size(); ++i)
            cout<<os[i]->getInt()<<endl;
        return *this;
    }
    ~Scene()
    {
        for (size_t i=0; i<os.size(); ++i)
            delete …
Labdabeta 182 Posting Pro in Training Featured Poster

we lack a clear set of requirements.

I think that is exactly the problem, when I first posted this thread I did not have a clear set of requirements, but now I do. I tend to start making my supporting classes/headers/libraries/etc by first deciding how I want the resulting use of the code to look like. Once I know what I want the result to be I try to create an interface that meets those requirements.

Here is my sample:
(Note that for obvious reasons it is untested [I haven't created the header yet])

#include "myHeader.h"
using namespace EG;//just to let you know that everything in myHeader is hiding in a namespace
class Player:public Object
{// private:
    int x,y;
    public:
    Player():x(0),y(0){}
    Player(int x, int y):x(x),y(y){}
    Reaction onKeyPress(Key k)
    {
        switch (k)
        {
            case ESCAPE:
            return FULL_EXIT;
            case SPACE:
            return DELETE_OBJECT;
            default:
            return Object::onKeyPress(k);
        }
    }
    Reaction onStep(const InputState &is)
    {
        if (is.getKey(UP_ARROW))
            y--;
        if (is.getKey(DOWN_ARROW))
            y++;
        if (is.getKey(LEFT_ARROW))
            x--;
        if (is.getKey(RIGHT_ARROW))
            x++;
        return Object::onStep(is);
    }
};
class Audio:public Object
{// private:
    bool muted;
    int volume;
    public:
    Audio():muted(false),volume(10){}
    Reaction onKeyPress(Key k)
    {
        switch (k)
        {
            case 'M':
            muted=!muted;
            return 0;//success return value
            case PLUS:
            volume++;
            return 0;
            case MINUS:
            volume--;
            return 0;
        }
    }
}
class HUD:public Object
{// private:
    int mx,my;
    Sprite cur;
    public:
    //scene is a protected member of Object, a pointer to the handler of the objects
    HUD():mx(0):my(0):cur("myCursor.png"){}
    Reaction onAdd(const InputState &is)
    {
        if (!scene) return NO_SCENE;
        mx=is.mouse.x;
        my=is.mouse.y;
        return Object::onAdd(is);
    }
    Reaction onMouseMove(int …
Labdabeta 182 Posting Pro in Training Featured Poster

Perfect, as usual! I just want to double-check that I fully understand.

Ideally I would want to do something like this:

Test t;
Incrementer i;
Object o=t|i;
o.onEvent();//fails, even if Objects are instantiable since I cannot access the derived functions in the Accumulating object

Since I can't access derived functions from an Object this will not work, leaving me with 3 options:

Option 1: raw pointers

Test t;
Incrementer i;
Object *o;
Cumulator c=t|i;
o=&c;
o->onEvent();//Yay!

Pros: Valid in old C++. Easy to implement.
Cons: Leads to complicated code (this is what I meant by pointers being complicated, they themselves aren't but they lead to complicated code). User must manage objects intelligently to prevent the "pointee"s from going out of scope.

Option 2: smart pointers

//Please excuse any minor lapses in syntax
Test t;
Incrementer i;
unique_ptr<Object> o(&t/&i);//perhaps I can define '/' as pointer version of |
o->onEvent();//Yay!

Pros: Pointer-safe (User can't 'break' the pointers). Easy to use. Can be placed in vectors.
Cons: Only valid in C++11. Harder to implement (requires extensive knowledge of smart pointers)

Option 3: Instantiable Objects

Test t;
Incrementer i;
(t|i).onEvent();//Yay?

Pros: Pointer-free. Easy to use.
Cons: Ridiculous to implement. My first attempt:

class Object
{// private:
    bool (*onE)();//function pointer to onE (I think this has to be a unique_ptr
    public:
    Object()
    {
        onE=[](){return false;};
    }
    virtual bool onEvent()
    {
        return onE();
    }
    Object &operator|(Object &o)
    {
        bool (*tmpE)()=onE;
        onE=[]()
            {//I don't know …
Labdabeta 182 Posting Pro in Training Featured Poster

Wow, thank you. I honestly did not think this would be such an interesting topic. Anyways, I have yet to make myself comfortable with the C++11 standard (even though I know I should) so I tried to implement using standard unsafe pointers and ugly references, since I do not yet fully understand how the C++11 safe pointers work. I can see how some kind of auto-managed pointer would be very helpful here, so I will try to understand them better once I get the general idea correct.

I got it to compile, but the output is not what I expected. Basically here is my test code:

#include <iostream>
#include <vector>
using namespace std; //its just a test code-segment
class Object
{// private:
    public:
    virtual bool onEvent()=0;
};
class test:public Object
{// private:
    public:
    virtual bool onEvent(){cout<<"Test"<<endl;return 0;}
};
class inc:public Object
{//private:
    int x;
    public:
    virtual bool onEvent(){cout<<"X="<<x++<<endl;return 0;}
};
class Cumulator:public Object
{// private:
    Object &a,&b;
    public:
    Cumulator(Object &a, Object &b):a(a),b(b){}
    virtual bool onEvent(){return a.onEvent()|b.onEvent();}//no more short-circuit
};
//when I put const Object & before it was just a force of habit
Cumulator operator|(Object &a,Object &b)
{
    return Cumulator(a,b);
}

int main() {
    vector<Object*> objs;
    test t;
    inc i;
    objs.push_back(&t);
    objs.push_back(&i);
    Object *o;
    *o=t|i;
    objs.push_back(o);
    for (int i=0; i<10; ++i){
        for (auto x:objs)
        {
            x->onEvent();
        }
    }
    return 0;
}

I would expect that this would output would be:

Test
X=1
Test
X=2
Test
...

Or possibly:

Test
X=1
X=2
Test
Test
X=3
... …
Labdabeta 182 Posting Pro in Training Featured Poster

After giving it more thought I realize that it is impossible as I initially presented it since I cannot create a brand new class in a function but rather can only create a new object. As such I think I will likely need an intermediate type which will manage function pointers to allow for | chaining? I am still iffy on the details as to how this can be done...

Labdabeta 182 Posting Pro in Training Featured Poster

Hello,

I am having a particularly nasty case of "What is the syntax?" while working on an event driven library. Basically this is what I want:

class Object
{// private:
    public:
    virtual bool onEvent(Event e)=0;//all objects have to react to events
    Object operator|(const Object &o)
    {
        // I want to return an Object which will execute both onEvents...
        // How can I do this... IF I can do this...
        // my example attempt: (I have yet to fully memorize the lambda expression syntax in c++11)
        return Object::onEvent(Event e)=[]{return (*this).onEvent(e) || o.onEvent(e);}
    }
};
class Test1:public Object
{// private:
    public:
    virtual bool onEvent(Event e)
    {
        cout<<"Test1"<<endl;
        return 0;//do not delete
    }
};
class Test2:public Object
{// private:
    public:
    virtual bool onEvent(Event e)
    {
        cout<<"Test2"<<endl;
        return 0;//do not delete
    }
};
//a more complex test
class Incrementer:public Object
{// private:
    int x;
    public:
    Incrementer():x(0){}
    virtual bool onEvent(Event e)
    {
        cout<<"Counter is: "<<x<<endl;
        return 0;
    }
};

So that this code:

Test1 t1;
Test2 t2;
Incrementer i;
f(t1|t2|i);

Will pass an object to f() whose onEvent function consists of:

cout<<"Test1"<<endl;
cout<<"Test2"<<endl;
cout<<"Counter is: "<<x<<endl;

Is this even possible? If it is, what would its constraints be? I would think that Test1 and Test2 should be possible (since they could easily be implemented via an array of function pointers) but how will Incrementer have access to i if it is currently an Object?