dusktreader 137 Posting Whiz in Training

My friend, you are suffering through pointer hell. The best way to avoid this is to use the standard template library. Vectors are infinitely nicer than dynamically allocated arrays of pointers. In order to understand your code, I had to work through it. In the process, i utilized the standard template library. The code worked almost immediately after eliminating compiler errors. Here it is:

#include <iostream>
#include <vector>

class neuron
{
public:
    // Other members and constructors omitted

    std::vector<neuron*> connections;

    void connect( const std::vector<neuron*>& inconnections )
    {
        connections.clear();
        for( unsigned int i=0; i<inconnections.size(); i++ )
        {
            if( this == inconnections[i] )
                continue;
            connections.push_back( inconnections[i] );
        }
    }

    //Printing functions ommitted
};


class network
{
public:
    std::vector<neuron*> neurons;


    neuron*& slot( int i, int j )
    {
        return neurons[ i * w + j ];
    }

    network( int w, int h ): w(w), h(h)
    {
        neurons = std::vector<neuron*>( w * h, NULL );
        for( int i=0; i<h; i++ )
        {
            for( int j=0; j<w; j++ )
            {
                slot( i, j ) = new neuron( i, j );
            }
        }
        for( unsigned int i=0; i<neurons.size(); i++ )
            neurons[i]->connect( neurons );
    }

    // Destructor and printing functions ommitted
};

using namespace std;

int main()
{
    network net(2,2);
    net.printNetwork();
    return 0;
}

Outut:

Network structure: 
-------------------
My name is: [0,0]
I am connected to: 
0,1
1,0
1,1
My name is: [0,1]
I am connected to: 
0,0
1,0
1,1
My name is: [1,0]
I am connected to: 
0,0
0,1
1,1
My name is: [1,1] …
dusktreader 137 Posting Whiz in Training

Readability >>> clever tricks

This code is painful:

ostream & operator << (ostream &out, const std::vector<beamlet> &b)
  std::ostream out1,out2;
for (b::const_iterator it=b.begin();it!=b.end();++b){
	    if (it!=b.end()-2) out1 << it.left << "," << it.right << ",\n";
	    else out2 << it.left << "," << it.right << "\n";
	    out << out1 << out2;
	    return out;
	}

This code does exactly the same thing, and it is much plainer what is happening:

ostream& operator<<( ostream &out, const std::vector<beamlet>& b )
{
    unsigned int i = b.size() - 2;
    out << b[i].left << "," << b[i].right << endl;
    for( i=0; i<b.size(); i++ )
    {
        if( i == b.size() -2 )
            continue;
        out << b[i].left << "," << b[i].right << "," << endl;
    }
    return out;
}

I'd like to make a few points

1. When using a std::vector, there is no advantage to using an iterator over indexing to the member. The vector container can access members by index in constant time. I think indexing looks much cleaner, because the syntax for iterators in for loops is pure hell. Now, if you are iterating through a list, you should use an iterator.

2. cout << "\n"; is not guranteed to flush the output stream. endl is guranteed to flush the output stream, and it is more explicit anyway. I highly recommend using endl with c++ ostreams. It's a very clear way of expressing what is happening using a reserved keyword. "\n" can be easy to miss when skimming code.

3. Do …

dusktreader 137 Posting Whiz in Training

I get no errors, I run it and a window appears saying "Polymorphism.exe has stopped working." Don't know if it is relevant, but I am using Dev-C++.

In this case, you should put in some lines that print debugging information. Try adding lines around the part that you think is causing problems. Here is an example

int someVal=10;
    cout << "someVal == " << someVal;
    someVal = someTroublesomeFunction( someVal );
    cout << "someVal == " << someVal;

This will let you know where you are crashing and what the values of different variables are at the time of the crash.

dusktreader 137 Posting Whiz in Training

There are still some problems.

First of all, I don't know why your generate() functions are returning doubles. Neither a Die or a Coin use floating point values. They both return integers. The rand() function also returns integers. There is no need for returning doubles or using the fmod function. I would change your genereate functions to return integers and use the % operator instead. Try this, and see how it goes.

dusktreader 137 Posting Whiz in Training

Please read the end of my previous post.

You should not call srand() more than once each time you execute the program. That is why I reccommended adding the srand() call to the constructor of the base class, and protecting this with a static boolean flag so that it is only executed once. Alternatively, you could call srand() at the beginning of your main function.

Calling srand() multiple times, even if it is within the scope of two separate classes in two separate files, re-seeds the same random number generator. The generator only needs to be seeded once per instance of your program.

This isn't why your program is crashing, but it is a critical logic error.

Please post the error output. Is it just a segmentation fault?

dusktreader 137 Posting Whiz in Training

Your solution is not recursive. Recursive logic is very elegant and powerful, and for algorithm junkies like myself, completely awesome. The trick is understanding how recursion works. I'll use your reverse problem as an example.

Suppose we want to reverse the string "Hello". Well, the fundamental problem is switching the location of each letter. The first step would be putting "H" at the end of the string:

Hello
|____
     v
 elloH

Well, that's all fine and good, but if we continue to use that logic within the same fuction, we will just get the original string back:

elloH
|____
     v
 lloHe

lloH
|____
     v
 loHel

The key is to do this swap at different levels:

Hello
|____
     v
 elloH

ello   [H]
|___
    v
 lloe  [H]

llo   [eH]
|__
   v
 lol  [eH]

lo   [leH]
|__
   v
  ol  [leH]

o
|
v
o [lleH]

This can be done rather easily with recursion. The trick is to understand how to order your function so that the correct logic is used. Here's the pseudo code for the recursive reverse function:

string reverseR( string target ):
    if length( target ) == 1:          # if the target is only one character long
        return target                  #   there is no need to reverse it
    character first := target[0]       # remove first letter and save it for later
    string newTarget := target[1:end]  # now, reverse the rest of the letters
    newTarget := reverseR( newTarget ) # the remaining letters have been reversed
    string result …
dusktreader 137 Posting Whiz in Training

First of all, you should post the code for your classes so we can see the underlying logic.

Secondly, you really don't need to do any casting here. Because the generate() function (I assume) is a virtual member of your base class, you should be able to call ptr->generate() with any pointer to any derived instance of your base class.

Here's some example code showing this concept:

#include <iostream>
#include <vector>

using namespace std;

class Base
{
public:
    virtual ~Base(){}
    virtual string name()
    {
        return "Base";
    }
};

class Derived0 : public Base
{
public:
    virtual ~Derived0(){}
    virtual string name()
    {
        return "Derived0";
    }
};

class Derived1 : public Base
{
public:
    virtual ~Derived1(){}
    virtual string name()
    {
        return "Derived1";
    }
};

int main(int argc, char *argv[])
{
    Base* arr[3];
    arr[0] = new Derived0();
    arr[1] = new Derived1();
    arr[2] = new Base();
    for( int i=0; i<3; i++ )
        cout << "arr[" << i << "]->name(): " << arr[i]->name() << endl;
    return 0;
}

The real key here is understanding inheritance. If you have a container that can hold pointers to different derived classes, you probably don't want to have to keep track of what kind of class to which each pointer refers. Inheritance allows you to have many different kinds of classes that all use some basic interface. This way, you can use many similar but different objects in identical ways. Dynamic casting has its uses, but it is not necessary to take advantage of the benefits …

dusktreader 137 Posting Whiz in Training

Often, the act of asking the question, leads to you discovering the solution yourself. Please don't just make the thread solved, with a "found the problem", please take the trouble to tell us what you did wrong. Even if it is brain dead stupid, we may laugh, but we all have been there and done it [and in my case, I seem to continue to have BDS moments]. You certainly will earn a lot more respect for admitting the error than the "found the problem" post.

Great point. Sharing your solution may help others (that may be googling) who are experiencing the same problem. I know that when I read Linux threads looking for help on config issues, there is nothing more frustrating than finding a thread with my exact same problem that the OP marked solved with no explanation.

jonsca commented: Rep for the main post +4
dusktreader 137 Posting Whiz in Training

When you run your program from the command line, redirect stderr to a file: $ myprogram 2> log.txt

dusktreader 137 Posting Whiz in Training

The problem here is that you are declaring an instance of a variable inside of your header file. You are essentially making messages or channels global variables. This would be fine if the header was only included by a single source file. Here's what's happening. Every source file that includes your header file will get its own seperate variable in the global scope with the given name. This works fine for compiling, as each object file doesn't care what is defined in other object files. However, when you link the objects together, the linker sees multiple variables with the same name in the same scope. This isn't legal, so it fails.

As a rule, it is bad practice to use global variables, so you're going down that wrong road. You should consider using a class with accessor functions for getting to the data. In any case, those variables should be declared within the scope of a source file.

I also notice that you used "using namespace std;" in your header file. This is also bad practice. Prefix all of your stl types with std:: in a header file, and only use "using namespace std;" in a source file.

dusktreader 137 Posting Whiz in Training

i guess all you need is to place each input in an array and then do a bubble sort on that array, then output the first and last values.

There are two huge problems with your approach. First, your solution is doing way more than is necessary. If I was a professor giving this assignment, and you implemented your proposed solution, I would give you B even if the program worked flawlessly. You need to solve the problem without adding extra complexity. If all you need to do is find the min and max values, why would you sort?

Secondly, you are suggesting a bubble sort! Bubble sort is among the most inefficient of sorting methods. It's time complexity is O(n^2). Finding the max and min of a problem set is only O(n). So, basically, your solution would require however much time it would take to simply pass over the loop squared. That is a huge waste of time! Imagine you had a file with 1 billion integer entries. Do you really want to use a bubble sort on this list? Do you really want to save this list in memory?

I didn't mean to go on the offensive so much, but you need to understand the magnitude of such an error. Computer Scientists search for the simplest and most efficient correct solution. The solution you are suggesting is correct, in a way. However, it terribly inefficient and tremendously over complicated.

john jr commented: Find the maximum number of entries in the three-digit number, javacipt and html +0
dusktreader 137 Posting Whiz in Training

I notice that there are many, many threads where posters receive few if any comments. When I open these threads, it is usually obvious right away why no one has bothered to reply. The problems with these posts vary from deliberate solicitation for homework solutions to poorly composed questions. I have assembled here 5 simple methods to make your post more interesting and clear to people who want to help you

1. Make your title descriptive
No one gets excited about clicking on a thread that says, "Please help!! T_T". The first thing I think when I see that link is, "This person is too lazy to summarize their problem, so the explanation inside is probably even worse." People on this forum want to help you, but they do not want to spend valuable time trying to deduce what the problem is. If you want people to read and reply, use a title that is descriptive of your problem. Here are some examples of interesting thread titles that will probably earn responses:

[B]Problem inserting nodes into linked list[/B]
[B]Compiler error in template class constructor[/B]
[B]Trouble sorting Automobile Class[/B]
[B]How can I return two values from a function?[/B]

It is most important that your title describes what kind of help you are looking for. I imagine that, like me, most readers skim the forum for interesting posts and ignore any that seem too inane. Finally, make sure that at least your title uses proper English. A thread title …

StuXYZ commented: Excellent! +3
Lusiphur commented: This should be stickied in every coding forum... +1
Ancient Dragon commented: Great post :) +31
Aranarth commented: Excellent! Now all that's left is that people read this post before starting a topic... +1
dusktreader 137 Posting Whiz in Training

As a fanboy of Qt, I recommend you research it a little. It's a very powerful cross platform GUI based on c++. Any programs you write using the Qt API can be built on windows, mac, and linux ( among others ). While drawing shapes in a QGraphicsView is not especially simple ( the QGraphicsView widget has a ton of capabilities ), the Qt API is fairly easy to use. Like I said previously, it is very powerful, but it is also very well documented. There are many tutorials online, and the online documentation is extensive. To top it all off, Trolltech (the maker of Qt) has a free integrated IDE called QtCreator for creating Qt projects. QtCreator is a full featured c++ IDE with a graphical designer for Qt widgets. Anyhow, I highly recommend Qt for anyone seeking to make interactive graphical programs in c++.

Qt Homepage
Qt Documentation

dusktreader 137 Posting Whiz in Training
myLinkedList ( )  {                                                         //TESTED
                 head = NULL;
                 last = NULL;
                 cout<<"Linked List is created with default constructor\n";
}

	
myLinkedList ( myLinkedList &arr) {                                        //TESTED
                 if (arr.head == NULL){head=NULL; last=NULL;}
                 else{
                      head = NULL;
                      last = NULL;
                      temp2 = new node;
                      temp2 = arr.head;
                      while(temp2!=NULL){
                                        insertLast(temp2->item);
                                        temp2 = temp2->next;
                      }
                 }
                 cout<<"Linked List is created with copy constructor\n";
}
	

~myLinkedList () {                                                         //TESTED
                  while (head!=NULL)
                        deletee(1);
                  cout<<"Linked List is deallocated!!\n";
}

and in my other class' constructor i wanted to call copyconstructor:

class dynamicArr {
private:
    myLinkedList data;
public:
	// CONSTRUCTORS
	dynamicArr ( ) {}
	dynamicArr ( dynamicArr& arr) {myLinkedList(arr.data);}
	~dynamicArr ( ) {data.~myLinkedList();}

You were correct to make dynamicArr a derived class of myLinkedList. Once you have done that, you don't need to have a member of dynamicArr that is an instance of myLinkedList. One huge problem exists in your copy constructor of myLinkedList. When you detect that the other linked list is not empty, you create many copies of the data found in the other linked list, but you never anchor those nodes to the copy. So, head is still pointing at NULL, your temp variables go out of scope, and you have a massive memory leak and an empty list. You should modify the copy constructor to look more like this:

myLinkedList ( const myLinkedList& other )
{
    if( other.head == NULL )
        head = last = NULL;
    else
    {
        head = new node( other.head );
        node* temp = other.head;
        tail = head;
        while( temp->next != …
dusktreader 137 Posting Whiz in Training

@dusktreader: You can combine your convert code into 1 :

template<typename ReturnType, typename InputType>
ReturnType convertTo(const InputType& in){
 std::stringstream ss;
 ss << in;
 ReturnType ret = ReturnType();
 if( (ss >> ret).fail()) throw std::exception("Conversion failed");
 return ret;
}

int main(){
 float pi = convertTo<float>("3.1415");
 string strPi = convertTo<string>(pi);
}

Very nice. I like this.

dusktreader 137 Posting Whiz in Training

Here's a litte bit of code that will help with your string/number conversion:

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

/** Converts a number to a string
  * @param  number - The number to convert
  * @param  prec   - Floating point precision to use
  * @param  w      - Width of the string
  * @return A string representation of the number
  */
template <class T>
std::string num2str( T number, int prec=2, int w=0 )
{
    std::ostringstream ss;
    ss.setf( std::ios::showpoint | std::ios::fixed );
    ss.precision( prec );
    ss.fill( ' ' );
    ss.width( w );
    ss << number;
    return ss.str();
}

/** Converts a string to a number
  * @param  str    - The string to convert
  * @param  number - The storage for the number
  */
template <class T>
void str2num( std::string str, T &number )
{
    std::istringstream ss( str );
    ss >> number;
}

using namespace std;

void test()
{
    int testInt;
    double testDbl;
    string testStr;
    
    testStr = num2str( "42.00001" );
    cout << "testStr=" << testStr << endl;

    str2num( "81.9954", testDbl );
    cout << "testDbl=" << testDbl << endl;

    str2num( "-42", testInt );
    cout << "testInt=" << testInt << endl;
}

The num2str and str2num functions would normally go in my tools.h header file that is filled with all sorts of useful goodies. Give it a try!

As far as extracting the data from the input, I would want to use a regular expression for that. I know it's a simple case you could probably parse by hand, but regular …

dusktreader 137 Posting Whiz in Training

Very informative. Very much appreciated, also.

At the end you mention every time it calls someOtherFunction available memory would be decreased. You mean every time a dynamic allocation is created and not deleted right? The way that's worded has me questioning if I call a function within a dynamically allocated class I could have problems.

Also that raises the question for me. Is there any benefits to dynamic allocation vs normal allocation performance wise?

other than not having to initialize an object in one call than it's pointer in another of course.

You are correct with your first assumption. Any time you don't deallocate a dynamically allocated object, you lose some memory from the heap. Calling a function inside of a dynamically allocated class creates no memory leak intrinsically, so that is completely safe.

Generally, dynamic allocation has benefits when you are dealing with large objects. The stack has only a limited amount of memory available, and it is reserved for objects created within a closed scope { any code between curly braces }. The stack should mainly be used for local native data types like ints, doubles, bools, and strings. If you are going to create a large array, or a large object, you should probably dynamically allocate it. There is the additional advantage that a dynamically allocated object persists even after you leave the scope where it is created. This can be useful because you only need to keep track of its pointer (memory address) instead of …

dusktreader 137 Posting Whiz in Training

Read this:
http://www.daniweb.com/forums/thread78223.html

You need to show that you have tried to come up with a solution first. Also, why, oh, why is this posted as a poll?

dusktreader 137 Posting Whiz in Training

The first problem is in your class definition. The scope operator( :: )is only used when your class is declared in one place (like a .h header file) and the functions are defined in another place (like a .cpp source file). When you are declaring and defining a function in one place, using the :: operator is incorrect. The class should be declared/defined in one place like so:

class SomeClass
{
    SomeClass()
    {
        // Some initialization here
    }

    SomeClass( int someVal )
    {
        // Some initalization here
    }
};

If you want to split the class declaration and definition, proceed like so:

// Declaration of class.  Probably appears in a .h file
class SomeClass
{
    SomeClass();
    SomeClass( int someVal );
};

// Definition of class functions.  Probably appears in a .cpp file
SomeClass::SomeClass()
{
    // some initialization here
}

SomeClass::SomeClass( int someVal )
{
    // some initialization here
}
  1. When a pointer is declared

where is it pointing to? Does it create a memory address not attached to a variable where Player() is initialized?

Think I'm not understanding new as you can't declare

as new Player() is a pointer type.

The key here is understanding the new operator. Whenever you use the new operator, you are asking for dynamic allocation. Basically, the program reserves some space in the heap for the new object instance, initializes it using the provided constructor, and returns a pointer to the location in memory of the new object. …

dusktreader 137 Posting Whiz in Training

Well, I don't really see what's causing the first error. It seems to be that there is another location where a class called Controller is defined. Everything in the header appears fine. Please post the Menu header file also.

The second error is occurring because you have two display functions defined within the scope of Menu. The first is on line 12 and the second on line 49. Obviously you only need on of these. There is a somewhat finer point to mention here. In the body of the display() function, you are calling Controller::display. Now, since Controller::display is a virtual function, classes that inherit from Controller can implement there own display() functions, and these will be called whenever an instance of the derived class calls its display function. However, if the derived class doesn't need to do anything but call the base class display() function, there is no need to implement a display() function at all. Instead, the display() function of the base class will be called, which is what you are doing anyway.

dusktreader 137 Posting Whiz in Training

Please post your input file.

I think you are getting the value of an unitialized variable. In c and c++, when you declare a variable like:

int someVariable;

The program is simply reserving an int sized memory block somewhere on the stack. Please note, the program only reserves the spot, it doesn't do anything with the memory. So, whatever data resided there before you declared the variable will become the value of the variable. You have to explicitly set the values of your variables if you want them to be fully intialized:

int someVariable = 0;

I would try this with your variables and run it again. I think you'll see that the huge number is gone.

You should also check the values that you are reading in as a debugging step. This step can be removed later when you are sure that your program is functioning correctly. After you read in the three values, print their values to the screen:

inFile >> var0 >> var1 >> var2;
cout << "var0" << var0 << endl;
cout << "var1" << var1 << endl;
cout << "var2" << var2 << endl;

That way, you can verify what is actually being read by your program. I suspect that whatever is in your input file is being read into none, the first, or the first two variables and at least one of the variables is not getting any input. Add the debugging couts and see what happens.

dusktreader 137 Posting Whiz in Training

Hello,

I need to know how the get the integer value of a byte and vice versa.

As the first respondent answered in unformatted code, it's as simple as a cast. I would additionally point out that it is useful to understand the type system in c++.

There are several integer types. These include

char
unsigned char
short
unsigned short
int
unsigned int
long
unsigned long

All of these types may be cast between each other directly.

dusktreader 137 Posting Whiz in Training

Hmm... I may be thinking about circular doubly linked list. I implemented only that kind of doubly linked list because I don't need to carry 2 nodes (head or tail). Also, it is very simple how to find out when you are at the end is that when your next node is 'head'. Nothing magical there.

Doubly linked rings also have the advantage in that you don't need any special cases for insertion or deletion. It is always the same mechanics regardless of where it takes place. The only thing you have to manage is the head pointer.

However, academic exercises commonly call for lists over rings to inflict additional suffering upon the students.

dusktreader 137 Posting Whiz in Training

The problem is (most likely) that you have to define a template function in the same file where it is declared. For a good over-view and specifics on the multi-file problem, see this.

So, you need to move your implementation of the split2 function to your header file. I know this will be ugly, but it's the only way to make it work well. You'll notice that many projects that use temlate classes and functions make use of a .hpp extension for header files with template implementations. This gives an indication that the header will contain both function declarations and definitions.

dusktreader 137 Posting Whiz in Training

It looks like you're trying to get us to solve your homework for you. If you have specific questions about the theory or mechanics behind any one question, I'll be happy to help. I'm not going to solve specific homework problems for you.

dusktreader 137 Posting Whiz in Training

Could you please post your header files for the Controller and Menu class?

dusktreader 137 Posting Whiz in Training

Doubly linked list should never point to a NULL.

That's not true. The HEAD node of a doubly linked list (DLL) should have its PREV pointer set to NULL. The TAIL node of a DLL should have its NEXT pointer set to NULL. Otherwise, how could you determine if you were at the head or tail when you were traversing the list.

dusktreader 137 Posting Whiz in Training

If a function is void, the only way you can display the result is to write to console immediately right after the calculation. In this case, while you are displaying each row, at the last column, which is the letter grade, call the function (may pass in total score depending on how you implement your variable). In the function, compute the grade from total and display it.

Actually not true:

void calcAverage( double* gradeArray, int arrayLength, double& average );

You can use a void function to modify local variables if you pass the variables by reference. This is most useful if you need to have a function return more than one value:

void calcMeanAndStdv( double* gradeArray, int arrayLength, double& mean, double& stdv );

This way, you can have the function calculate the value of the mean and standard deviation in one function.

I was thinking if in the calculating average function to assign the average of each line to a separate variable and use a while loop to do that. I am not sure if that is an effiecent way to do that. Ill post up the code once try it out. But for now, can anoyone tell how they would a approach this problem?

That isn't necessary. I would proceed by processing one line at a time:

1.  Read in the next Line
2.  Parse the line.
3.  Store the Name as a string and the scores in an array
4.  Use the average function …
dusktreader 137 Posting Whiz in Training

You should also only seed the random number generator once early in the lifecycle of the program. time() measures seconds, so if you seed twice in the same second, the generated numbers will be the same.

dusktreader 137 Posting Whiz in Training

You need to first realize that there is no [][] operator. In fact whenever you see matrix2D[][] or matrix3D[][][] or matrixND[][]...[], you are actually seeing multiple nested calls on the [] operator.

Consider the case for a 2D matrix. If you declare the matrix like so:

int rows = 5;
int cols = 7;
int** myMatrix = new int*[rows];
for( int i=0; i<rows; i++ )
    myMatrix[i] = new int[cols];

You are actually first declaring an array of int pointers. Each one of these int pointers is then pointing at another array of ints. The way this lies in memory can be looked at like this

array[ *, *, * ]
       |  |  |
       |  |  |---> array[ i, i, i ]
       |  |
       |  |------> array[ i, i, i ]
       |
       |---------> array[ i, i, i ]

So, when you are accessing an element of a Matrix like this:

myMatrix[1][2];

You are actually first accessing the element of the pointer array at position [COLOR="Red"]1[/COLOR], and then accessing the element of the nested int array at position 2:

          1
          |
array[ *, *, * ]
       |  |  |
       |  |  |---> array[ i, i, i ]
       |  |
       |  |------> array[ i, i, i ]
       |                        |
       |                        2
       |
       |---------> array[ i, i, i ]

So, you can't really design a custom class that can in and of itself process the nested [] operators ( [][] ). You can, however, overload …

dusktreader 137 Posting Whiz in Training

You need to declare the static member outside of the class definition like so

#ifndef DIE_H
#define DIE_H

#include "aRandomNumberGenerator.h"

class aDie
{
    public:
        aDie();
        double roll(); 
        void seed (int s);
        int inputSeed();
        ~aDie();
        
    private:
        static aRandomNumberGenerator gen;
};

#endif


#include <iostream>
#include "aDie.h"
#include <cmath>
using namespace std;

aRandomNumberGenerator aDie::gen;
// or
// aRandomNumberGenerator aDie::gen( ... );
// or
// aRandomNumberGenerator aDie::gen = new aRandomNumberGenerator( ... );


aDie::aDie()
{
   
}

double aDie::roll()
{   
    return (fmod(gen.generate(), 6) + 1);
}

void aDie::seed(int s)
{
    gen.setSeed(s);
}

int aDie::inputSeed()
{
    int value;
    
    cout << "Please enter a seed value: ";
    cin >> value;
    
    seed(value);
    
    return value;
}

aDie::~aDie()
{
    //Destructor does nothing in this case.
}
dusktreader 137 Posting Whiz in Training

The basic problem with detecting bodies is the inconsistency of orientation. You'll notice that the Face detector is really only good at detecting faces that are pointed more or less toward the camera, and the detector does not find rotated faces well. This is because it is looking for similar structure at multiple scales in a single orientation. Detecting bodies is going to be much more difficult if you can't count on the bodies being oriented in the same direction and can't count on the bodies having the same pose.

In order to detect bodies, you would need some sort of detector that operated by detecting features of bodies and looking for clusters or connected components of these. This is not a trivial problem whatsoever. Using the detectors that ship with OpenCV will not help you much with this regardless of how many training images you supply.

Furthermore, we typically dress our bodies in clothing of different colors. If you were only detecting naked bodies, it would be much simpler. However, any sort of detector that you built would have to first be able to segment the structure of the body. This would most likely require some sort of edge finding, because you couldn't train it by color or gray level alone. Imagine how difficult it would be to isolate one torso dressed in a shirt with wide horizontal stripes and another one dressed in a camouflage shirt.

Like I said previously, this is not a trivial …

jonsca commented: Excellent points +4
dusktreader 137 Posting Whiz in Training

i need to the code for drawing square

Here's a better link for you:

You need to the rules for posting questions

dusktreader 137 Posting Whiz in Training

Hi,

I have code as follows wherein I pass a 2D array to a function and want to receive this array with its contents tripled.

The error I get is 'error: cannot convert 'int (*)[4]' to 'int**' in return'.
I was able to send and receive a 1D array using 'pass by value' but for 2D I hit this error. Please advice.

The most obvious solution is to not return anything from the function. Since the array is passed to the triple function by reference, there is no need to return its address. You can simply pass the array to the function, modify it in place in the function, and when the function returns, the array will have been modified and its address will be the same. There is absolutely no need to return a pointer from the function. For example:

#include <iostream>
using namespace std;

int* modify( int arr[4] )
{
    for( int i=0; i<4; i++ )
        arr[i] += 1;
    return (int*)(arr);
}

int main()
{
    int origArr[4];
    memset( origArr, 0, 4 * sizeof(int) );  // fill with 0's
    int* newPtr = modify( origArr );  // Now it is filled with 1's
    cout << ( newPtr == origArr ) << endl;  // The pointer references the same location as the original array
    return 0;
}

You could instead simply do this:

#include <iostream>
using namespace std;

void modify( int arr[4] )
{
    for( int i=0; i<4; i++ )
        arr[i] += 1;
}

int main()
{
    int …
dusktreader 137 Posting Whiz in Training

If all you need to do from c++ is extract text information from a python file, any sort of file i/o will work:

google: fstream

If you need to check how recently a file was modified, you simply need to use C system calls:

google: lstat

If you are trying to interface running python code to running c++ code, read my previous post.

dusktreader 137 Posting Whiz in Training

My first recommendation would be to use Python exclusively. Python is a fully-featured programming language with thousands of libraries for doing just about everything. There are 3 principle GUI toolkits for Python. These are PyQt, wxPython, and Tkinter. PyQt (my preference) and wxPython are very powerful and higly supported. Tkinter is probably easier for extremely basic UI programs, but it is old, ugly, and under-documented. Of course, Python is much slower than c++ and lacks the natural obfuscation that comes with a compiled language.

If you really must write the bulk of the program in C++, there are many options for interfacing to Python. First, you can use the Python/C API that's built into Python. I wouldn't recommend this. The built in API has a very steep learning curve. However, there are many wrappers for the API that aim to improve instant usability. These include SWiG, Pyrex/Cython, Ctypes, and many others. Finally, the Boost library provides a full interoperability package for C++ and Python.

If you want to begin exploring some options for yourself, try googling "c++ python"

dusktreader 137 Posting Whiz in Training

Hi.This is my program but it runs a lot of unnecessary stuff.
Please post your program.:)

You are very close with your implementation. As far as I can tell, your algorithm prints out all possible partition schemes for the range. However, it prints a lot of redundant copies of many of the partitioned subsets.

For example, I ran your code against the same set I tested Nathan's with and got the following output with 35 partitioning schemes:
L = 7, M = 4

1  2  34567  
1  23  4567  
1  234  567  
1  2345  67  
1  23456  7  
12  3  4567  
12  34  567  
12  345  67  
12  3456  7  
123  4  567  
123  45  67  
123  456  7  
1234  5  67  
1234  56  7  
12345  6  7  
12  3  4567  
12  34  567  
12  345  67  
12  3456  7  
123  4  567  
123  45  67  
123  456  7  
1234  5  67  
1234  56  7  
12345  6  7  
123  4  567  
123  45  67  
123  456  7  
1234  5  67  
1234  56  7  
12345  6  7  
1234  5  67  
1234  56  7  
12345  6  7  
12345  6  7

There are only 15 possible partition schemes, and you can see from the output above that there are many duplicate lines.

dusktreader 137 Posting Whiz in Training

alright I looked into it and i forgot to add a least case scenario since my algorithm for making the sets always found the largest set to make the permutations. Now I'm running my minimum value to 2 since i already have 1 covered in the largest first set. my machine is a little old running and only has a 500 MHz processor with 640 MB ram so my total time was 120 ms with L = 7 and M = 3. I also fixed another error in my code. I forgot to have a return if the set was evenly divisible by M.
my output was

[[0,1,2,3,4], [5], [6]]
[[0], [1,2,3,4,5], [6]]
[[0], [1], [2,3,4,5,6]]
[[0,1,2,3], [4,5], [6]]
[[0,1], [2,3,4,5], [6]]
[[0,1,2,3], [4], [5,6]]
[[0], [1,2,3,4], [5,6]]
[[0,1], [2], [3,4,5,6]]
[[0], [1,2], [3,4,5,6]]
[[0,1,2], [3,4,5], [6]]
[[0,1,2], [3], [4,5,6]]
[[0], [1,2,3], [4,5,6]]
[[0,1], [2,3], [4,5,6]]
[[0,1], [2,3,4], [5,6]]
[[0,1,2], [3,4], [5,6]]

if there is anything else that isn't right let me know. BTW that is a nice algorithm you have dusktreader. One thing I'm curious about is why do you use negative numbers?

It looks like you have it correct now.

The reason I used negative numbers in my example was because I specified in my original description that the algorithm should partition any range of integers. Of course, you only need to do the partitioning from 0 to L and then offset all the numbers in the partitions by i0 where i0 is the first integer in the range. I just used a set spanning zero to demonstrate that it worked according to my original description. In practice I would never use negative numbers, and the range would always be a subset of [0..256).

dusktreader 137 Posting Whiz in Training

Well to start things off i have be going a little STL crazy lately. I'm having fun playing around with all the things you can do so I decided to give this an entire STL approach. There is probably a faster way but this was fun and some good practice. I hope you guys enjoy this one.

You almost got it, Nathan. In fact, I was convinced you did have it until I ran your code on a large set. I use this algorithm to do Multi-level Otsu thresholding on grayscale images, so my set is (usually) 256 elements. Running your code on 256 elements with 4 divisions ran in 7 ms while mine took 400. I was impressed, but a little suspicious. It turned out that your program was finding 2087 partitions while mine found 2731135. So, I ran them again side by side on a 7 element set with 3 partitions and compared the results. It appears you are missing a few of the possible partitionings. Here is the comparison

dusktreader's implementation:
found 15 possible partitionings
[ 0 ] [ 1 ] [ 2 3 4 5 6 ] 
[ 0 ] [ 1 2 ] [ 3 4 5 6 ] 
[ 0 ] [ 1 2 3 ] [ 4 5 6 ] 
[ 0 ] [ 1 2 3 4 ] [ 5 6 ] 
[ 0 ] [ 1 2 3 4 5 ] [ 6 ] 
[ 0 1 ] [ 2 ] [ 3 4 5 6 ] 
[ 0 1 ] [ 2 3 ] [ 4 5 6 ] 
[ 0 1 ] [ 2 3 4 ] [ 5 6 ] 
[ 0 1 ] [ 2 3 4 5 ] [ 6 ] 
[ 0 1 2 ] [ 3 ] [ 4 5 6 ] 
[ 0 1 2 ] [ 3 4 ] [ 5 6 ] 
[ 0 1 2 ] [ 3 4 5 ] [ 6 ] 
[ 0 1 2 3 ] [ 4 ] [ 5 6 ] 
[ 0 1 2 3 ] [ 4 5 ] [ 6 ] 
[ 0 1 2 3 4 ] [ 5 ] [ 6 ] 

nathan's implementation
found 12 possible partitionings
[[0,1,2,3,4], [5], [6]]
[[0], [1,2,3,4,5], [6]]
[[0], [1], [2,3,4,5,6]]
[[0,1,2,3], [4,5], [6]]
[[0,1], [2,3,4,5], [6]]
[[0,1,2,3], [4], [5,6]]
[[0], [1,2,3,4], [5,6]]
[[0,1], [2], [3,4,5,6]]
[[0], [1,2], [3,4,5,6]]
[[0,1,2], [3,4,5], [6]]
[[0,1,2], [3], [4,5,6]]
[[0], [1,2,3], [4,5,6]]

It looks like the trouble comes when the partitions are nearly equal.

dusktreader 137 Posting Whiz in Training

First, lets establish some variables. Let L be the length of the range. Let M be the number of partitions to create in the range.

The first thing I noticed in this problem is that creating M partitions requires M-1 dividers in the range. Let D be the set of dividers for a particular partitioning. The following range has been partitioned into 3 subsets, and the dividers are at index 1 and 4: { 7 8 | 9 10 11 | 12 } . The indices for the dividers must all be unique, and D > D[i-1]. Using this sort of logic, a sort of enumeration quickly appears for the possible divider indices.

Given L=7 and M=4, let's step through the possible values for D

D                   P(L)
0, 1, 2  ->  [0][1][2][3,4,5,6]
0, 1, 3  ->  [0][1][2,3][4,5,6]
...
0, 1, 5  ->  [0][1][2,3,4,5][6]

We can't increment the D[2] anymore with out making the division invalid, so, we have to increment D[1]. This of course means that D[2] must be made 1 greater than D[1] because of our original constraints.

0, 2, 3  ->  [0][1,2][3][4,5,6]
0, 2, 4  ->  [0][1,2][3,4][5,6]
0, 2, 5  ->  [0][1,2][3,4,5][6]

Again, the D[2] can't increment further so we increment D[1] again and set D[2] = D[1] + 1

0, 3, 4  ->  [0][1,2,3][4][5,6]
...
0, 4, 5  ->  [0][1,2,3,4][5][6]

Now, D[1] can't be incremented any further without invalidating the divisions, so we must increment D[0] and set D[1] = D[0] + …

dusktreader 137 Posting Whiz in Training

Go ahead and post your solution, Nathan. I'll post mine probably tomorrow

dusktreader 137 Posting Whiz in Training

I ran into this particular problem at work and found it quite interesting. While implementing a multi-level image threshholding algorithm, I discovered that I needed to find all the ways I could partition a range of integers into some number of consecutive groups. I like my solution, but there may be better approaches. Here is the problem: given some set S of consecutive integers, find all possible partitions of S into M disjoint subsets of consecutive integers such that S is covered its subsets for example:
if N=7, M=4, and S=[0,1,2,3,4,5,6], all the valid partition sets are:

[[0], [1, 2, 3], [4], [5, 6]]
[[0, 1, 2, 3], [4], [5], [6]]
[[0, 1], [2], [3, 4, 5], [6]]
[[0, 1], [2, 3], [4, 5], [6]]
[[0, 1, 2], [3], [4], [5, 6]]
[[0], [1], [2], [3, 4, 5, 6]]
[[0, 1], [2, 3, 4], [5], [6]]
[[0, 1], [2, 3], [4], [5, 6]]
[[0, 1, 2], [3], [4, 5], [6]]
[[0], [1, 2, 3, 4], [5], [6]]
[[0], [1], [2, 3, 4, 5], [6]]
[[0], [1, 2, 3], [4, 5], [6]]
[[0], [1], [2, 3], [4, 5, 6]]
[[0, 1], [2], [3], [4, 5, 6]]
[[0, 1, 2], [3, 4], [5], [6]]
[[0], [1, 2], [3, 4, 5], [6]]
[[0], [1, 2], [3, 4], [5, 6]]
[[0], [1], [2, 3, 4], [5, 6]]
[[0], [1, 2], [3], [4, 5, 6]]
[[0, 1], [2], [3, 4], [5, 6]]

Good luck!

dusktreader 137 Posting Whiz in Training

I know this thread is cold, but I recently had this problem myself. There is no round function in <cmath> for windows. Instead, you have to implement it yourself. This is rather easy, however:

inline double round( double d )
{
    return floor( d + 0.5 );
}

If you look at this MSDN page, you'll find that while our "friends" at M$ saw fit to include floor() and ceil() but no round().

dusktreader 137 Posting Whiz in Training

Ah, yes.

In developing the system of equations, I overlooked one simple reduction

Given:

Fn( m ) = ceiling( ( log( m ) + log( sqrt(5) ) ) / log( phi ) )
n( d ) = Fn( 10^( d - 1 ) )

If we select a base 10 logarithm for the Fn function, and collapse the two functions together we get: n( d ) = ceiling( ( log_10( 10^(d-1) ) + log_10( sqrt(5) ) ) / log_10( phi ) ) Since we know that log_10( 10^k) == k, we can simply reduce the function to: n( d ) = ceiling( ( d - 1 + log_10( sqrt(5) ) ) / log_10( phi ) ) Finally, if we really don't like finding the square root of 5 every time, we can simplify that logarithm by log_b( a^x ) == x * log_b( a ) to get: n( d ) = ceiling( ( d - 1 + 0.5 * log_10( 5 ) ) / log_10( phi ) ) Of course, this equation should be robust against overflow for VERY large numbers indeed. It is also the equation you arrived at.

dusktreader 137 Posting Whiz in Training

The essential problem is to determine the index i of the first Fibonacci number Fn to have at least d digits. The specific challenge is to determine the index of the first Fibonacci number to have 1000 digits.

Obviously, this problem could be brute forced by stepping through all the Fibonacci numbers and determining the answer. However, this is not very mathematically pleasing, nor is it very efficient. Instead, we will develop an algorithm to determine the answer using some nifty Fibonacci mathematics.

At this point, I'd like to introduce Mr. J. P. M. Binet. Binet was a French Mathematician and Physicist that lived and worked around the turn of the 19th century. Binet discovered a formula for calculating the nth Fibonacci number without having to know anything about the preceding Fibonacci numbers. His formula had been previously discovered by Euler and a fellow named Moivre, but the Formula is credited to Binet commonly. Binet's formula expressed the nth Fibonacci number in terms of the golden ratio (phi). phi = ( 1 + sqrt(5) ) / 2 and Fn( n ) = ( phi^n - ( -phi^-n ) ) / sqrt( 5 ) This is a tremendous time saving formula that allows instant calculation of any Fibonacci number. Interestingly enough, this formula always returns an integer even though it involves products of irrational numbers ( phi and sqrt(5) ). In any case, it should also be noted that if n is a real number, Fn will also be …

dusktreader 137 Posting Whiz in Training

Oh, for the love of Darwin.

Thank you for restoring my sanity (and sorry for the brain fart).

Glad to help.

caffeine commented: Thank you for being patient with my stupid mistake! +1
dusktreader 137 Posting Whiz in Training

Are you not allowed to use cin to get whole strings from an input file? cin >> someString; If you are, you could fetch an entire string at a time and process each string individually.

dusktreader 137 Posting Whiz in Training

Try including <sstream> in SafeArrayUtil.h

dusktreader 137 Posting Whiz in Training

How can I access (get) the individual pixels of the data in an LPDIRECT3DTEXTURE9?

Thanks.

Well, your first step would probably involve asking this question in a more appropriate forum:

"LPDIRECT3DTEXTURE9 get pixel"

"How to get the color of one pixel of shadow map"

dusktreader 137 Posting Whiz in Training

I have a bunch of code that looks like:

// Local block scope
{
    ostringstream  ostr;
    ostr.fixed;
    ostr.precision(2);
    ostr.width(20);
    ostr << foo->bar[trno];
    SafeArrayPut2D( retArray, 3, i, (void *) ostr.str().c_str() );
}
{
    ostringstream  ostr;
    ostr.fixed;
    ostr.precision(4);
    ostr.width(22);
    ostr << foo->foobar[trno];
    SafeArrayPut2D( retArray, 4, i, (void *) ostr.str().c_str() );
}

So I wanted to write a function to abbreviate the process. Here's what I did. In the header file:

void ostreamStringHelper( ostringstream& oss, streamsize prec, streamsize width );

In the cpp file:

void ostreamStringHelper( ostringstream& oss, streamsize prec, streamsize width )
{
    oss.fixed;
    oss.precision(prec);
    oss.width(width);
}

However, it's giving me errors:

1>Compiling...
1>SafeArrayUtil.cpp
1>c:\safearrayutil.cpp(32) : error C2027: use of undefined type 'std::basic_ostringstream<_Elem,_Traits,_Alloc>'
1>        with
1>        [
1>            _Elem=char,
1>            _Traits=std::char_traits<char>,
1>            _Alloc=std::allocator<char>
1>        ]
1>c:\safearrayutil.cpp(32) : error C2228: left of '.fixed' must have class/struct/union
1>c:\projects\cashflow\trancheinfodll\safearrayutil.cpp(33) : error 

I don't understand --- what exactly is the problem with the ostreamStringHelper() function? oss is a reference to a class, not a pointer; why is the syntax invalid?

Thanks!

It's hard to say, when you haven't given enough source code to determine what line the error is actually coming from. I implemented a quick demo:

void helper( ostringstream& oss, streamsize prec, streamsize width )
{
    oss.fixed;
    oss.precision( prec );
    oss.width( width );
}

int main(int argc, char *argv[])
{
    ostringstream ostr;
    helper( ostr, 3, 6 );
    return 0;
}

This compiled and ran fine …