Alex Edwards 321 Posting Shark

It looks like you forgot to include your header file.

Try adding this to the top of your script--

#include "templateq.h"

Edit: Hmm interesting, I made the following changes and it managed to work--

//templateq.h

#ifndef TEMPLATEQ_H

#define TEMPLATEQ_H

#include <iostream>
#include <new>
#include <cstddef>

using namespace std;

class FullTemplateQ								// Exception class
{};


class EmptyTemplateQ								// Exception class
{};


template<class SomeType>	   				// Node template class
struct QueueNode
{
  SomeType  data;									// Data stored in queue node

  QueueNode<SomeType>*  nextPtr;				// Pointer to next queue node
};


template<class SomeType>	   				// Circular queue template class
class TemplateQ
{
  private:
    QueueNode<SomeType>*  rearPtr;			// Pointer to rear of queue

	QueueNode<SomeType>*  frontPtr;			// Pointer to front of queue

    void PrintNext(QueueNode<SomeType>* tempPtr) const; // Print trailing items

  public:
	TemplateQ();									// Default constructor

	~TemplateQ();									// Destructor deallocates every node

	void Enqueue(SomeType newData);			// Adds newdata node to rear of queue

	SomeType Dequeue();							// Removes data node from front of queue,
                                          // returning the stored data

	bool IsFull() const;							// Returns true if queue is full,
                                          // false otherwise

	bool IsEmpty() const;						// Returns true if queue is empty,
                                          // false otherwise

	int Size() const;								// Returns the number of items in queue

    void ForwardPrint() const;             // Prints queue, front to rear

    void ReversePrint() const;             // Prints queue, rear to front
};

//#include "templateq.cpp"					// Very Important!!  Do not delete!!

#endif

Notice I commented out the #include for templateq.cpp.

// templateq.cpp

#include "templateq.h"
#include <new>
#include <cstddef>

using namespace std;


template <class someType>
TemplateQ<someType>::TemplateQ() …
Alex Edwards 321 Posting Shark

is there any advantage to placing it after main? I mean is there any particular reason why it would have been after?

I personally consider code in a Driver Program to be cleaner when the logic of main is known before anything else.

Also, function declarations make code more readable because you know of the functions that are in the program before they are defined (at least hopefully they are defined, otherwise its just unnecessary information).

Other than that, I'm not entirely sure. Though I do know that you don't have to declare a function elsewhere in the same file, you can do so in other files but it would require you to also tag on the word extern to your function declaration to send a flag to your compiler stating the function is defined in a separate file.

Alex Edwards 321 Posting Shark

Yeah, it's usually called "copying contents of memory to a disk file in some format" :lol:

There are some types of memory more enduring than RAM (eg ROM) but using them relies on them being present (i.e. not guaranteed to be available for use on all computers) and also relies on significantly more knowledge than saving data to a disk file.

Yes that's pretty much the point I was getting at, besides the other 2 more reliable (and safer) ways I've already mentioned.

Alex Edwards 321 Posting Shark

There are several ways...

The most popular way would be to save the information to a file then retrieve it later.

Another popular way that isn't done unless absolutely necessary is by querying information to a database then retrieving it later.

There may be a way to fool around with memory and store the information somewhere more permanent, but I don't know how to do that, nor would I recommend it.

Alex Edwards 321 Posting Shark
void printmovie (movies_t movie);

Is a function declaration.

The definition exists elsewhere in the same file.

Short/Simple reason: C++ can be very linear. If you comment out the function declaration, you will get a compiler error. That is because the function printmovie is found after the definition of main, but main is evaluated first during parsing and the compiler wont find the definition of printmovie until after main ( in this case the compiler will most likely flag an error, but then again this is completely dependent on the settings of the compiler).

I'm sure there are some compilers that can be configured to evaluate a function call and determine if it exists somewhere in a document without a need to evaluate the function declaration first, but I have yet to see such a compiler and even if one did exist it would be poor programming practice to code around what one compiler would accept vs multiple popular and conforming compilers.

If you want to use the function printmovie without the declaration, you will have to place the definition of printmovie before main.

Alex Edwards 321 Posting Shark

In C++, you can declare a function, constructor, or operator to accept a type by reference and not value.

For example, the declaration of the function--

void foo(int);

--states that the function foo takes [a copy of] an integer and returns void.

So the following would be legal--

int main(){
   foo(3); // legal
   int x = 4;
   foo(x); // legal
   return 0;
}

--however, you could instead declare a foo to take a reference to an int instead--

void foo(int&);

-- which means foo takes [a reference of] an int and returns void. Before proceeding, let's think of what a reference is.

Reference(programming) - the underlying address of an object, or type.


Hmmm... what does that mean?

Ok, in English... let's say you live at a particular address. Your house sits on top of that address, so therefore in order to access your house I need only to know your address.

If, for example, I sent someone information that contained your address, that individual would know where the house is and be able to access it (well in reality that's a big maybe, but in programming that's true to a certain extent).

int main(){
 //  foo(3); // illegal, because '3' itself is not an address!
 int x = 4;
 foo(x); // legal, because the value x has an address and therefore can be passed by reference
 return 0;
}

The real question is, what is the benefit of …

Alex Edwards 321 Posting Shark

I never wrote a thesis for my Masters, did more of a set of research papers, but honestly I haven't come across any that are more than a few hundred pages.

On a practical side, you do understand that your advisor/panel will be reviewing your thesis and making corrections to it before you present it ? Do you seriously expect them to read 6000 pages ?

>Most likely 2 years to get the first few drafts done @_@, hopefully I can edit it
>within 5 months after that to finish but that's seriously wishful thinking >_<
More like complete fantasy. What you're suggesting is akin in principle to Knuth's TAOCP, which has taken the better part of his life, still isn't finished, and I'd estimate that it totals to about 1500 pages presently (including the index in each volume).

You're like some pharoah, clueless as to just how big the job is, just waking up one day and deciding "I need a pyramid".

More maths, since you seem incapable of grasping something simple like multiplication and division.

5 months = 150 days => 40 pages per day.

Low estimate of a single page = 2000 characters / 300 words.
Low estimate for day (40 pages) = 80,000 characters / 12,000 words.

Bearing in mind that there are only 86,400 seconds in a day, you need to be a hell of a lot quicker than 1 keystroke per second. A pedestrian 20wpm is a solid 10 hour day.

Alex Edwards 321 Posting Shark

That's very ambitious. How long do you think you would take to finish this 6000-page book?

Most likely 2 years to get the first few drafts done @_@, hopefully I can edit it within 5 months after that to finish but that's seriously wishful thinking >_<

-Alex

Alex Edwards 321 Posting Shark

I wouldn't use the terms "Old Testiment" and "New Testiment" because you will immediately get critisizm from the religious people. No point immediately discarding 1/4th the potential readership (and customers).

Good point =)

I'm atheist so something like that didn't matter to me, but it is something to think about! XP

-Alex

Alex Edwards 321 Posting Shark

6000 pages @ 1 page per day ~= 16.5 years.
Planning anything else afterwards, say the world's longest beard perhaps?

Now if you're doing some proper old-time research (and coming up with genuine new ideas, which is what a PhD ought to be), it might take weeks to come up with a single page of useful material.

But if you're planning on copy/pasting whatever google search results, it's doable.
But it would be the ultimate Write Once Read Never tome IMO.

The index would be so large that it would need it's own index ;)

It wouldn't be copy-pasta! >_<

Everything added will be tested and evaluated. Originality would also be implemented for everything added.

Some of the material might be reference to most people, but I'm hoping to introduce something new after I obtain more experience and find something, like a particular domain, that really needs better support (which would be doable, it would just take some work >_<).

That's partly the reason on why I'd start now instead of later @_@.

-Alex

Alex Edwards 321 Posting Shark

I guess you don't know how big a 6,000 page book is! I have a copy of "SQL, The Complete Reference", by James Groff & Paul N Weinberg, which has 998 pages and is 2 1/2 inches thick. Your book would be about 15 inches thick! I have never seen such a huge book.

Ok... maybe I should shed some light on my idea, though I did not want to do this before since I didn't want anyone to steal it @_@

Then again, if someone does steal the idea, I suppose it would be quite a feat to do it in anything less than 6000 pages O_O

Anywho...

I plan on making a book that puts all of the pieces of logic and Software together. From imagination to syntax (in C++) and other useful amounts of information O_O

There would be 4 sections to the book.

Section 1) The "Old Testament" which consists of programming from 1940-1985 and ideas that existed between those times.

Section 2) The "New Testament" which consists of programming from 1986-2008 and of course ideas that existed between those times.

Section 3) Combining concepts of the Old and the New.

Section 4) Problem analysis, Imagination and Implementation.

More likely than not, I'll probably dedicate 2000 pages to both the Old and New Testament and 800 pages to the last 2 section, leaving room for solutions to problems that might exist within certain subsections O_O.

Alex Edwards 321 Posting Shark

Well then...best of luck.

Thank you! =)

Alex Edwards 321 Posting Shark

It happens every now and then, usually when somebody says something so monumentally stupid that I can't find the right words to express myself. Or in your case, when I can't tell if you're joking or not.

Well I am serious! O_O

I thought I'd do some writing on my own and as I learn over time I can refactor and add content.

The editing portion would of course be reviewed by professionals willing to put time into it.

But yeah, I am very serious!!! O_O

-Alex

Alex Edwards 321 Posting Shark

...

I've never seen you speechless before O_O

>_<

-Alex

Alex Edwards 321 Posting Shark

Hmm... I've made it my top priority to get a Master's and Ph.D in Computer Science and Software Systems... however I'd like to know what a suitable Master's Thesis would be?

I'm thinking about making a book, maybe 6000 pages long, pertaining to nothing but Software ideals and technology.

This might be overkill, but it might also be helpful to others who think a lot like me =P.

Then again, I have seen some Thesis' become used by companies. Such Thesis' required a lot of study and usability factors. I hope that my ideas will have the same effect O_O.

There's no way I'll finish now, but I'd like to be steered in the right direction. I especially want to devote most of the Thesis to C++ and how the language is used to interface with Operating Systems to perform human-readable computer logic.

It'll be some time before I have to do this, but I'd like to plan ahead! =)

Thank you!

-Alex

Alex Edwards 321 Posting Shark

You may want to talk to williamhelmsworth or look up a C++ library that allows you to interface with your OS and export/import bitmaps from C++.

Here's a code snippet from william that allows you to create .bmp's from C++, so I can imagine that importing would be a similar process.

I believe his was done with Windows - Snippet

Alex Edwards 321 Posting Shark

You can't declare a method within another method O_O

You'll have to pull all of your other methods (add, subtract etc) outside of the definition of your simp method. Your simp method can have the logic of the continuous play, but it can't have method definitions >_<

-Alex

Alex Edwards 321 Posting Shark

[Linker error] undefined reference to `add()'

Can someone explain that a little? Do i need to include my code to help you guys explain? Thanks

It never hurts to include your code (provided it's not too long! O_O).

Just be sure to use code tags @_@

-Alex

Alex Edwards 321 Posting Shark

It might do you some good to learn RMI from the book Head First Java or get a brief overview by reading Head First Design Patterns. Both books are good and provide more information about programming and Object Orientation than one would expect.

And also, both books are funny XP

jasimp commented: Head First Java is where I first dabbled in RMI. I would have suggested it but that would be more work than clicking on a link ;) +8
Alex Edwards 321 Posting Shark

Hey, thanks, but from exam point of view, what shall i write True or False? From examples it is clear that surely we can add, but it's not recommended, isn't it? So shall i go with option "True"?

I don't believe Menus or certain 'Views' would be possible without some type of Composite structure, so a reference to a Collection (or more appropriately, a Composite) within a Collection is good for specific uses.

It's hard to argue what's right or wrong in the Exam perspective. It depends on how the question is worded.

But since you're just adding a reference to a Collection of the same type, you can think of it as a Composite List of some sort. I don't see any harm in it as long as the reference is set dynamically.

Alex Edwards 321 Posting Shark

Hi
I have come across a question in a collection which says:
One can add a reference of a collection to itself. Is it true or false?
I read the explanation that, we can add the reference to the collection to itself, but it results in the stack overflow of the JVM. Please people tell me what is the correct answer, i am confused because we can add the reference but we should not add it.
Please help me

Ok, let me see if I understand what you're asking.

Let's first determine what a collection is.

Collection (programming) - a structure that holds many objects of some type (in old versions of Java, collections stored arbitrary objects, and in new versions you can specify a Generic collection that is 'at least' the type specified).

Reference (programming) - An address of the underlying object.

So can we add a Reference of a Collection to a Collection? Sure you can. I believe that is called a composite structure, though I'm no professional so I could be wrong =P

/*Declare an ArrayList that can store Object references*/
ArrayList<Object> myArrayList = new ArrayList<Object>(0);

// ... some time later in code...

/*Adding the address of the ArrayList itself to itself*/
myArrayList.add(myArrayList);

--the only way you can make a collection overflow is if you are creating a custom collection and you attempt to declare a globally scoped Reference to a collection that is the same class (or …

Alex Edwards 321 Posting Shark

I'd like to apologize...

the previous example can be forgiven for not implementing Node deletion (since OP has it defined), but can't be forgiven for forgetting appropriate Node declarations in global scope of NodeType structs (in both classes).

This is a corrected version--

#include <iostream>

using std::cout;
using std::cin;
using std::endl;

template<class ItemType>struct NodeType;
template<class ItemType>struct List;

template<> // specialization for chars
struct NodeType<char>{
	char item;
	NodeType<char> *next;
	NodeType(char);
};

NodeType<char>::NodeType(char myItem) : next(0){
	item = myItem;
}


template<> // specialization for chars
struct List<char>{

	NodeType<char> *root;
	List();
	void add(char);
	void viewAll();
};

List<char>::List() : root(0){}

void List<char>::add(char val){
	if(root == NULL){
		root = new NodeType<char>(val);
	}else{
		NodeType<char> *temp = root;

		while(temp->next != NULL)temp = temp->next;

		temp->next = new NodeType<char>(val);
	}
}

void List<char>::viewAll(){

	NodeType<char> *temp = root;
	while(temp != NULL){
		cout << temp->item << endl;
		temp = temp->next;
	}
}


template<class ItemType> // generalized for all other types
struct NodeType{
	ItemType *item; // ptr to prevent "slicing", see Stanley B. Lippman's 'The C++ Object Model' for a thorough explanation
	NodeType<ItemType> *next;
	NodeType(ItemType&);
};

template<class ItemType>
NodeType<ItemType>::NodeType(ItemType& myItem) : next(0) {
	item = &myItem;
}

template<class ItemType> // generalized  for all other types
struct List{

	NodeType<ItemType> *root;
	List();
	void add(ItemType&);
};

template<class ItemType>
List<ItemType>::List() : root(0){}

template<class ItemType>
void List<ItemType>::add(ItemType& val){
	if(root == NULL){
		root = new NodeType<ItemType>(val);
	}else{
		NodeType<ItemType> *temp = root;

		while(temp->next != NULL)temp = temp->next;

		temp->next = new NodeType<ItemType>(val);
	}
}

class MyObject{
	public:
		const char *name;
		MyObject(const char*);
};

MyObject::MyObject(const char * theName) …
Alex Edwards 321 Posting Shark

Please put code tags around your code.

Also, wouldn't it be easier to store the binary value you are computing in a string, inside your binary class ? And then just start at position starting point in the string and then scan for the next zero ?

That would be the ideal way, but also a lot slower.

Question for the original poster - what is a word? Is a word like the definition of a Windows WORD, or is it any 32bit (unsigned) int, or what exactly?

Also it looks like you're searching for the first 0 from the right (or from the "start") of the bitset.

I believe this will work for you O_O --

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <bits.h>
#include <cmath>

using namespace std;

// Print a number in binary:
class Bin{

    public:
        Bin(int num){
            n = num;
        }

        friend ostream& operator<<(ostream& os, const Bin& b){

            unsigned int bit = 1 << (sizeof(int)*CHAR_BIT - 1);

            while (bit){

                os << ((b.n & bit) ? 1 : 0);
                bit >>= 1;
            }

            return os;
        }

    private:
        int n;
};

unsigned int Scan0(unsigned int word, unsigned int startingBit);

int main(){

    unsigned int i, x;

    while (cin >> x){

        cout << setw(10) << x << " base 10 = " << Bin(x) << " base 2" << endl;
        for (i = 0; i < sizeof(unsigned int) * CHAR_BIT; ++i)
            cout << "Scan0(x, " << setw(2) << i << ") = "
            << setw(2) << …
Alex Edwards 321 Posting Shark

You can't make a typedef out of an incomplete type, so the following would be illegal if NodeType is generalized--

typedef NodeType* NodePtr;

struct NodeType
{
    ItemType item;
    NodePtr  next;
};

-- because templates of typedefs are illegal.

You would need to alter your struct to have a variable type, like such--

template<class ItemType>
struct NodeType{

    ItemType* item;
    NodeType* next;

};

--if your Node is declared outside of your List class.

If its outside your list class and you want to create NodeTypes that hold the same type as the list, you'll have to do something like this--

#include <iostream>

using std::cout;
using std::cin;
using std::endl;

template<class ItemType>struct NodeType;
template<class ItemType>struct List;

template<> // specialization for chars
struct NodeType<char>{
	char item;
	NodeType *next;
	NodeType(char);
};

NodeType<char>::NodeType(char myItem) : next(0){
	item = myItem;
}


template<> // specialization for chars
struct List<char>{

	NodeType<char> *root;
	List();
	void add(char);
	void viewAll();
};

List<char>::List() : root(0){}

void List<char>::add(char val){
	if(root == NULL){
		root = new NodeType<char>(val);
	}else{
		NodeType<char> *temp = root;

		while(temp->next != NULL)temp = temp->next;

		temp->next = new NodeType<char>(val);
	}
}

void List<char>::viewAll(){

	NodeType<char> *temp = root;
	while(temp != NULL){
		cout << temp->item << endl;
		temp = temp->next;
	}
}


template<class ItemType> // generalized for all other types
struct NodeType{
	ItemType *item; // ptr to prevent "slicing", see Stanley B. Lippman's 'The C++ Object Model' for a thorough explanation
	NodeType *next;
	NodeType(ItemType&);
};

template<class ItemType>
NodeType<ItemType>::NodeType(ItemType& myItem) : next(0) {
	item = &myItem;
}

template<class ItemType> // generalized  for …
Alex Edwards 321 Posting Shark

This managed to work for me--

import java.util.*;

public class TestClass1{
	static String seatLayout = null;
	static String fn = null;

	public static void main(String... args){
		System.out.println(showAllSeats("1294"));
	}

	public static String showAllSeats(String flightNumber){

		fn = flightNumber;

		// Make a set of arrays for each flight. This is only one flight. If the flightNumber is "1294"  ...
		if(fn.equalsIgnoreCase("1294")){

			ArrayList<String> r1 = new ArrayList<String>();
			r1.add("Row 1");
			r1.add("_");
			r1.add("_");
			r1.add("_");
			String row1 = r1.toString();

			ArrayList<String> r2 = new ArrayList<String>();
			r2.add("Row 2");
			r2.add("_");
			r2.add("_");
			r2.add("_");
			String row2 = r2.toString();

			ArrayList<String> r3 = new ArrayList<String>();
			r3.add("Row 3");
			r3.add("_");
			r3.add("_");
			r3.add("_");
			String row3 = r3.toString();

			seatLayout = row1 + row2 + row3;
		}
		return seatLayout;
	}
}
Tyster commented: Thanks for your help! +2
Alex Edwards 321 Posting Shark

I think you will need assistance from a Regex library.

Example (for unmanaged C++) here

Alex Edwards 321 Posting Shark

Hey everyone! =)

I'm starting an Application Development club at my college!

However, there are a fair amount of programmers with multiple backgrounds who want to be a part of the club and partake in some of the Software we will create.

Most of the people who are joining the club know C++, PHP, HTML, Java and MySQL/Oracle.

Bridging the gap between the Database-heavy individuals and Java will be a breeze. Bridging databases with C++ will also be a breeze. HTML-to-database communication can also be done.

Communicating between HTML and Java is easy, but communicating between C++ and HTML apparently is no walk in the park.

I've done some research, and found a few libraries that support C++ to HTML communication (via C++ Servlet containers), and found libraries such as SWILL (which has limitations on concurrency and is considered unsafe) and C++ES (which happens to be an individuals Master's Thesis O_O ), but I'd like to know if there is some kind of Boost implementation of a C++ Servlet container, or if there's any practical way for interfacing C++ with web-based applications?

I'd just like to be steered into the right direction =). I don't want anyone who joins the club to feel left out and unable to really contribute to a project.

Of course we're going to start with very simple applications that are very useful (i.e., a convenient collection of information or tools for Students in a class to use …

Alex Edwards 321 Posting Shark

Thanks! =)

And just for aesthetics O_O --

#include <iostream>
#include <ctime>
#include <iomanip>

using std::cout;
using std::cin;
using std::endl;
using std::ostream;
using std::setw;
using std::setfill;

ostream& operator << (ostream&,const tm&);

tm mytime; // not quite safe

int main(){


 //   tm mytime; // safer implementation
    mytime.tm_mday = 10;
    mytime.tm_mon = 5;
    mytime.tm_year = 2008;
    mytime.tm_hour = 3;
    mytime.tm_min = 8;
    mytime.tm_sec = 30;

    cout << mytime << endl;
    cin.ignore();
    cin.get();

    return 0;
}

ostream& operator<<(ostream& out,const tm& theTime){
    out << setfill('0') << setw(2) << theTime.tm_mon << "/"
        << setw(2) << theTime.tm_mday << "/"
        << setw(4) << theTime.tm_year;
    out << "\t"<< setw(2) << setfill('0')
        << setw(2) << theTime.tm_hour << ":"
        << setw(2) << theTime.tm_min << ":";
    out << setfill('0') << setw(2) << theTime.tm_sec;
    return out;
}
Alex Edwards 321 Posting Shark

Interesting that you want to use a format specifically meant for separating individual values with commas, but need to retain information with commas inside it.

A good way of doing this would be to make your own tokenizer and only parse information when a stack is empty.

When you encounter quotes, push it onto the stack and read characters contiguously, even if it is a comma.

When you encounter quotes again, pop the original quote off of the stack and let your custom tokenizer do its thing, like normal.

Alex Edwards 321 Posting Shark

Alex: using stringstream as you did is not necessary -- cout already knows how to do it.

Do I need to implement some header for an output implementation? I was getting weird results without using some defensive measures, and I'm tired @_@.

Here's a better version--

#include <iostream>
#include <ctime>

using std::cout;
using std::cin;
using std::endl;
using std::ostream;

ostream& operator << (ostream&, const tm&);

tm mytime; // not quite safe

int main(){


 //   tm mytime; // safer implementation
    mytime.tm_mday = 10;
    mytime.tm_mon = 5;
    mytime.tm_year = 2008;
    mytime.tm_hour = 3;
    mytime.tm_min = 8;
    mytime.tm_sec = 30;

    cout << mytime << endl;
    cin.ignore();
    cin.get();

    return 0;
}

ostream& operator<<(ostream& out, const tm& theTime){
    out << theTime.tm_mon << "/" << theTime.tm_mday << "/" << theTime.tm_year;
    out << "\t" << theTime.tm_hour << ":" << (theTime.tm_min < 10 ? "0": "") << theTime.tm_min << ":";
    out << (theTime.tm_sec < 10 ? "0": "") << theTime.tm_sec;
    return out;
}
Alex Edwards 321 Posting Shark

I believe declarations and definitions are allowed outside main, but assignments are not.

This example compiles fine--

#include <iostream>
#include <ctime>
#include <sstream>

using std::cout;
using std::cin;
using std::endl;
using std::ostream;
using std::stringstream;

ostream& operator << (ostream&, const tm&);

tm mytime; // not quite safe

int main(){


 //   tm mytime; // safer implementation
    mytime.tm_mday = 10;
    mytime.tm_mon = 5;
    mytime.tm_year = 2008;
    mytime.tm_hour = 3;
    mytime.tm_min = 8;
    mytime.tm_sec = 30;

    cout << mytime << endl;
    cin.ignore();
    cin.get();

    return 0;
}

ostream& operator<<(ostream& out, const tm& theTime){
    stringstream ss1 (stringstream::in | stringstream::out);
    stringstream ss2 (stringstream::in | stringstream::out);
    ss1 << 0 << theTime.tm_min;
    ss2 << theTime.tm_min;
    out << theTime.tm_mon << "/" << theTime.tm_mday << "/" << theTime.tm_year;
    out << "\t" << theTime.tm_hour << ":" << ((theTime.tm_min < 10 )
                                             ?  ss1.str() : ss2.str() ) << ":" << theTime.tm_sec;
    return out;
}
Alex Edwards 321 Posting Shark

You could use a State Machine, or State Pattern based on how many times an object has been encountered, or the State of an object can depend on the type of object it encounters...

It may simplify things, but only if you can work out the different possible states of objects.

I think this is the closest thing to a solution to your problem, though considering I know what you're trying to do, and State patterns can be bulky... it can be somewhat complicated @_@

I still struggle making State Patterns, unless I study the behavior between objects thoroughly. Below is just a sample program. a collides into b multiple times, and the behavior is different each time.

Of course this is just a test program, but the concept may be powerful enough to provide a solution to the problem O_O

/**
 * Just testing the State Pattern =)
 */
public class TestingGrounds{

	/**
	 * Interface for all Collidable objects
	 */
	interface Collidable{

		public void collideInto(Collidable other); // collide into the object

		public void react(Collidable theCollider); // triggered from another object

		public void setState(SomeObjectState behavior); // set the behavior of the object
	}

	/**
	 * The State of SomeObject has the same exact interface as the Object itself
	 */
	abstract class SomeObjectState implements Collidable{

		protected Collidable ref = null;

		public SomeObjectState(Collidable ref){
			this.ref = ref;
		}

		public void setState(SomeObjectState behavior){} // hook, States aren't meant to be composite @_@
	}

	/**
	 * The Normal State …
Alex Edwards 321 Posting Shark

In case anyone is interested, here's a meta-program solution to the original problem--

#include <iostream>

using std::cin;
using std::cout;
using std::endl;
using std::ostream;
using std::size_t;
template< size_t, size_t, size_t> class TwoDimensional;
template< size_t, size_t > class Multiplier;

template<>
class Multiplier<0, 0>{
    public:
        enum{TRUE_M = 1};
};

template< size_t Mult, size_t Times>
class Multiplier{
    public:
        enum{TRUE_M = Mult * Multiplier< ( (Times > 0 ) ?  Mult : 0) , ( (Times > 0) ? Times - 1 : 0)>::TRUE_M};
};

template< size_t R, size_t C, size_t M>
class TwoDimensional{
    private:
        enum {TRUE_R = Multiplier<M, R - 1>::TRUE_M};
        enum {TRUE_C = Multiplier<M, C - 1>::TRUE_M};
        enum {AREA = TRUE_R * TRUE_C};

        int dummyArray[TRUE_R][TRUE_C];
        int row[TRUE_R][TRUE_C];

    public:

        TwoDimensional(){
            int myArray[TRUE_C] = {0};// initialize to have 0 in all indices
            for(size_t i = 0; i < TRUE_R; i++)
                memcpy(row[i], myArray, TRUE_C * sizeof(int)); // copy contents of myArray into row[i]
        }

        size_t getRowSize(){
            return TRUE_R;
        }

        size_t getColSize(){
            return TRUE_C;
        }

        size_t getArea(){
            return AREA;
        }

        ostream& showContents(ostream& out = cout){
            for(size_t i = 0; i < TRUE_R; i++){
                for(size_t j = 0; j < TRUE_C; j++)
                    out << row[i][j] << " ";
                out << endl;
            }
            return out;
        }

        int* operator[] (size_t indice){
            if(indice >= 0 && indice < TRUE_R){
                return row[indice];
            }
            return dummyArray[indice];
        }
};


int main(){

    TwoDimensional<3, 4, 2> td;
    td[1][3] = 5;
    td.showContents() << endl;
    cin.ignore();
    cin.get();

    return 0;
}
Alex Edwards 321 Posting Shark

Whoo! O_O

Thanks to those error messages, I was able to track down the issue @_@

Even though I try to safely specify 0 as the argument of the other value, the 2nd argument will be decremented by 1...

for example..

template<1, 2>
{

       enum{
            TRUE_R = 2 * template<0, 0>::TRUE_R /*which equals 1... however...*/ 
       };
       enum{
            TRUE_C = 2 * 
                       template<0, 1>{
                                  
                             enum{TRUE_R = 2 * template<-1, 0>{
                                     /* infinite expansions >_< */
                              }::TRUE_R /*BAD! O_O*/};         
                             
                             enum{TRUE_C = 2 * template<0, 0>::TRUE_C /*which equals 1*/ };
             }::TRUE_C

             

       };


}

Thanks Dave! =)

Alex Edwards 321 Posting Shark

I tried implementing a template Array-class that allows initial size of global arrays to be known at compile time, specified by the user.

When I specify a class of type <1, 1> size, the file compiles fine. However, when I specify a class of any other numeric type, in either "parameter" where both aren't 1, I get this message--

-------------- Build: Debug in Reform_2DArray ---------------

main.cpp
Process terminated with status -1073741819 (0 minutes, 1 seconds)
0 errors, 0 warnings

via Code::Blocks IDE, Microsoft Visual C++ 2005/2008 compiler, on Windows XP.

The code is a modified version of something I posted in someone elses topic. It doesn't quite solve their problem, but it does provide an interesting means of cleanly creating a 2D array at compile time.

#include <iostream>

using std::cin;
using std::cout;
using std::endl;
using std::ostream;
using std::size_t;
template< size_t, size_t> class TwoDimensional;

template< size_t R, size_t C>
class TwoDimensional{
    private:
        enum {TRUE_R = 2 * TwoDimensional<R-1, 0>::TRUE_R};
        enum {TRUE_C = 2 * TwoDimensional<0, C-1>::TRUE_C};

    //    int dummyArray[TRUE_R][TRUE_C];
    //    int row[TRUE_R][TRUE_C];

    //public:
/*
        TwoDimensional(){
            int myArray[TRUE_C] = {0};// initialize to have 0 in all indices
         //   cout << "Initializing 2Darray to be of 'area' : [" << TRUE_R << " x " << TRUE_C << "]" << endl;
            for(size_t i = 0; i < TRUE_R; i++)
                memcpy(row[i], myArray, TRUE_C * sizeof(int)); // copy contents of myArray into row[i]
        }

        size_t getRowSize(){
            return TRUE_R;
        }

        size_t getColSize(){
            return TRUE_C;
        }

        ostream& showContents(ostream& out = cout){
            for(size_t i …
Alex Edwards 321 Posting Shark

Here's an example of encapsulating a 2D vector and emulating the behavior or a 2D vector through a class--

#include <iostream>
#include <vector>
#include <cmath>

using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::ostream;
using std::size_t;

class TwoDimensional{

    vector<int> dummyVec;
    vector< vector<int> > rowContent;

    public:
        TwoDimensional(unsigned int rowSize = 0, unsigned int columnSize = 0){
            rowContent = vector< vector<int> >( static_cast<int>( pow(static_cast<double>(2), static_cast<double>(rowSize)) ),
                         vector<int>( static_cast<int>( pow(static_cast<double>(2), static_cast<double>(columnSize))), 0));
        }

        ostream& showDimensions(ostream& out = cout){
            out << "Column Size: " << rowContent[0].size() << "\n";
            out << "\nRow Size: " << rowContent.size();
            return out;
        }

        ostream& showContents(ostream& out = cout){
            for(size_t i = 0; i < rowContent.size(); i++){
                for(size_t j = 0; j < rowContent[i].size(); j++){
                    out << rowContent[i][j] << " ";
                }
                out << endl;
            }
            return out;
        }

        vector<int>& operator[] (unsigned int indice){
            if(indice >= 0 && indice < rowContent.size()){
                return rowContent[indice];
            }
            return dummyVec;
        }
};

int main(){

    TwoDimensional td (2, 4); // 2^N rows, 2^T columns, in this case 2^2 rows, 2^4 columns
    td[2][3] = 5;
    td.showDimensions() << endl;
    td.showContents();
    cin.ignore();
    cin.get();

    return 0;
}
Alex Edwards 321 Posting Shark

Thanks to you both, I began a Python tutorial this weekend and so far I love it. "Hello World!" lol

Yes, another person who is entertained, and not aggravated, by programming! =)

Always keep that perspective, no matter how hard it is to learn something! You'll find programming very fulfilling! =)

sciwizeh commented: wprds of wisdom +1
Alex Edwards 321 Posting Shark

>Is there a better way?
Yes, design the class hierarchy such that you don't need to know the dynamic type of the object. Perhaps some form of strategy pattern would clean up that selection code.

Would an Adapter be overkill?

I.E.

public class AdaptedA<T extends A> extends A{

      private T myType = null;
      public AdaptedA(T type){
             myType = type;
      }

      T getType(){ return type; }

      void performSpecializedOperation(Object parameters...){
                // your if statements here...
      }
}
public void foo(A object, Object parameters...){

      if(object instanceof AdaptedA){
            ((AdaptedA)object).performSpecializedOperation(parameters);
      }else{
          // basic commands for A objects
      }

}

The only advantage to this is centralizing the code in the Adapter class and not the method that handles A-types.

Hopefully this is reasonable @_@

Alex Edwards 321 Posting Shark

Bah, disregard this post >_<

public <T extends A> void doSomething(T type){

      if(type instanceof [SpecialNeedClass]){
              // typecast only for this type
      }
      // else if(...) // other specialized types
      else{ // if no other specialized type, perform basic A operations
        
      }

}

It would've been a good idea if Incomplete types were allowable in Java, but unfortunately Java isn't the same as C++ @_@

Alex Edwards 321 Posting Shark

The idea is simple enough...

For numbers 2- max, check the numbers between any one of these numbers...

If any number between the chosen number is a potential divisor of the number (and it isn't 1, nor the number itself) then the chosen number is not a prime number.

If no divisor can be found between 1 and the actual number, then it is a prime number.

I'm sure there is a better way of finding prime numbers than that approach. In fact, any time you have to use 2 for loops to solve a linear problem something is definitely wrong...

Alex Edwards 321 Posting Shark

Here's an example of how you can store things in your own collection type.

However, if your assignment REQUIRES you to use something else, that's another story.

In any case, consider the following example code--

public class HangMan{



	public static void main(String... args){

		HangMan hg = new HangMan();
		HangMan.ReverseList<String> myList = hg.new ReverseList<String>();

		myList.add("least");
		myList.add("not");
		myList.add("but");
		myList.add("Last,");

		System.out.println(myList);

		System.out.println(myList.atIndex(2));
		myList.remove(2);
		System.out.println(myList);
		System.out.println(myList.atIndex(2));
	}

	public class ReverseList<T>{

		public class Node<T>{
			Node<T> next = null;
			T data = null;

			Node(T type){ data = type; }
			Node(T type, Node<T> other){ data = type; next = other;}
			T getType() {return data;}
			void setType(T type) {data = type;}
			Node<T> getNext() {return next;}
			void setNext(Node<T> other) {next = other;}
			@Override public String toString() {return (data != null) ? data.toString() : "<null>";}
		}

		Node<T> root = null;

		void add(T data){ root = new Node<T>(data, root); }

		boolean remove(int index){
			boolean successful = false;
			if(index >= 0){
				int count = 0;
				Node<T> previous = lookup(index - 1);
				Node<T> future = lookup(index + 1);

				if(index != 0 && previous != null){
					previous.setNext(future);
					successful = true;
				}else if(index == 0 && root != null){
					root = root.getNext();
					successful = true;
				}
			}

			return successful;
		}

		private Node<T> lookup(int index){
			Node<T> temp = root;
			if(index >= 0){
				int count = 0;

				while(count != index && temp.next != null){
					temp = temp.getNext();
					count++;
				}
			}
			return temp;
		}

		T atIndex(int index){
			Node<T> temp = lookup(index);
			return (temp != null) ? temp.getType() : null;
		}

		@Override public String toString(){
			String …
Alex Edwards 321 Posting Shark

Mooky, how did you go finishing this Hangman project?
If you have a working completed one would u be able to send it to me at SNIPPED. I have an assignment due that very closely resembles your hangman and am in need of help

If you look very carefully, the thread you managed to dig from the grave is about 3 years old... =/

Every time someone revives an ancient old thread, a young kitten dies...

Save the kittens! O_O

Alex Edwards 321 Posting Shark

You could just create your own collection-type, such as a linked list or a tree, to store your information.

Edit: Also I think a StringBuffer is backed by an array for random-access character retrieval.

Alex Edwards 321 Posting Shark

Here's a solution, though it is not efficient at all.

#include <iostream>

using std::cin;
using std::cout;
using std::endl;
using std::ostream;

template< unsigned int max >
inline ostream& primeNumbers(ostream& out = cout){

    for(int i = 2; i <= max; i++){
        bool isPrime = true;
        for(int j = 2; j <= i; j++){
            if( ( (i%j) == 0) && (j != i))
                isPrime = false;

            if((j == i) && (isPrime == true))
                out << i << " ";
        }
    }
    return out;
}

int main(){

    primeNumbers<100>() << endl;
    cin.ignore();
    cin.get();
    return 0;
}
Alex Edwards 321 Posting Shark

Hmm something looks fishy here...

for (int n = 3; n <= 100; n++)
		{
			for (int i = 2; n < i; ++i)
 	                {
                                newn = n % i;
				while(newn > 0)
				{ 
					cout << n << " ";	
				}
			}
		}

In the above chunk of code, it seems as if the n < i statement evaluates to be false so the loop never executes.

n is always 3 <= n <= 100, and i is initialized to 2 each time the nested for loop is evaluated, but n < i will always return false because of the range of n.

You'll have to modify your nested for loop to accommodate for this logic error. I'm no prime-number professional, but I can at least see the boolean error in your code.

Alex Edwards 321 Posting Shark

Just a note...

I can already see some problems...

You're not implementing the <string> header...

On one of your later lines you're using something along the lines of...

cin << value

...and that just wont work.

Also please use proper indentation and code tags, or others may not be so willing to help you.


As for your main problem, what do you need to make an array of? People or Classes? And also, is the information for all of the Classes (or People) inside the file?

Alex Edwards 321 Posting Shark

Anything Java can do, C++ can do (though there may be more instructions).

In fact, C++ can do more than Java....

However when it comes to GUI implementations, C++ loses out unless you count .NET Frameworks and other non-standard libraries that support GUI application development under the C++ language. I also can't imagine how difficult it would be for C++ to implement a non-standard library that supported "Servlet-based" containers @_@


Sorry for rambling... what was your old project like? Do you still have the source code?

Alex Edwards 321 Posting Shark

My computer keeps restarting whenever I do something like view a stream-video or also do something else that is video related, i.e. playing Warcraft 3 FT.

Sure it can perform fine doing either task (for about 5 minutes) but then the computer just shuts off without warning!

Now at first I thought it was a hardware issue, but it's odd... I can leave the computer on for hours on end and it wont automatically shut off. Only if it's doing one of the 2 tasks mentioned above!

The only thing I can think of is that maybe the processor can't handle doing the extra work of video streaming? Is it possible that the Video driver is causing the CPU to heat up and in turn is causing the computer to shut down??

sorry, I don't know too much about hardware so I can only make these assumptions @_@

Any help would be appreciated! =)

-Alex

Alex Edwards 321 Posting Shark

That sounds like you want to build your own operating system :) I would recommend that you always use 'new' (or malloc) to allocate memory for your program. I you go writing stuff in random places in the memory which you think are free for using and something like 'Windows' comes along and writes other stuff in that memory, you would get some really nasty crashes

Building my own Operating System would be the first step. I'll probably end up doing that while I continue on with college.

What I'd really like to do is create my own machine that is specialized to save energy and space and also be more efficient at holding memory. In order to do this I, of course, need to first gain a solid understanding of Computers today and Software Technology.

Thanks to this site, I've gained a much deeper passion for Computers and Software Technology! I'll keep on improving my ability to code then expand my skill-set and eventually build my own machine from scratch =)

Yes there's a lot to do on 'the list' XD

Alex Edwards 321 Posting Shark

"Allocate" and "release" are probably better terms than "create" and "destroy". Somehow the operating system has to give you permission to use memory. Try to use memory that's not yours (i.e. not allocated to your process) and you are going to get an error. So new is a request for memory. It's saying "I need 1000 bytes of memory. Can I please have it and can you tell me what memory to use?" At that point, the operating System will either allow you to use it or it won't. The OS has to give it to you before you can use it. Can you imagine what a mess it would be if you simply picked some memory address and started reading and writing to it? And all the processes just used whatever memory they wanted without anyone checking whether any other process was using it?

"Delete" just means "I'm done with the memory now. You don't have to hold on to it for me anymore." I'm not sure if this addresses your question at all, but figured I'd throw it out there. I'm definitely not the memory management guru here.

Although it doesn't solve the initial problem, it does give me a stronger view on the Operating System and how imperative it is to have one when handling devices and subsystems (File Systems, the Cache, RAM, ROM, Registers, etc).

Though, I don't think I want to solve the problem anymore because I forgot that the OS could - despite …