Murtan 317 Practically a Master Poster

Welllll, you COULD enter CTRL-A to get Monday, CTRL-B for Tuesday... (but I wouldn't recommend it).

I like some form of menu in this case, something like:

What day of the week is it? (1-Sunday, 2-Monday, 3-Tuesday...)

Then you could switch on the character entered and use it to set 'today' so the compare would work.

If you don't mind making it a little confusing for the user (bad form in my opinion, but to each his own) you could prompt for the actual enum value and scanf into an int.

What day of the week is it? (0-Sunday, 1-Monday, 2-Tuesday...)

@RenFromPenn

What do you want the user to type in at your prompt?

Could you 'type up' what you think the interaction should look like, then we could help you get the code to do what you want.

For the first case of mine above it would look like:

Please select the day of the week:
    1 - Sunday
    2 - Monday
    3 - Tuesday
    4 - Wednesday
    5 - Thurdsay
    6 - Friday
    7 - Saturday
What day of the week is it? 7

Hooray, it's the weekend!
Murtan 317 Practically a Master Poster

You're not showing any of the actual compares. The structs to be compared will need to have implemented whatever operator or method is called to do the compares.

Note that the word 'Comparable' in your template definition makes no constraint on the type of things you can put on your list. It is just the name by which you know the class inside the template.

For most of these ordered collection objects, I prefer to give the collection a pointer to a comparison function that will make the actual compare between two objects, rather than an operator or named method call. The primary reason I have is that I might want the collection ordered by different fields at different times.

As an example of multi-sorting, if you had Customer (struct/class) that contained the customer_id, first_name, last_name, address, city, state, zip. You might want the collection ordered by customer_id when relating by that field, ordered by last_name and first_name when building a customer directory, and ordered by zip when producing the mailing labels.

If the collection is ordered using operator <(...) the collection can only have one order...ever.

Murtan 317 Practically a Master Poster

Yes, your change to the deleteData function (to take a reference to the list) would be necessary.

As far as creating an instance of your template list, it would look like: myStdList<Foo> foolist; if declaring a member or a list on the stack. If you wanted the list to come from the heap it would look like: myStdList<Foo> * pfoolist = new myStdList<Foo>(); If you needed to be able to put different kinds of objects on the list, and you had a base class that declared the appropriate interface methods as virtual, you could create a myStdList<BaseClass> myList; and add derived classes to it. The primary problem would be in that anything you access from the list would 'look like' a BaseClass and only have that interface available.

Murtan 317 Practically a Master Poster

I thought that the vector code posted by Freaky_Chris was a great example of the parts of vector that you would be most interested in.

// declaring a vector
std::vector<std::string> genes;
// adding a string (genestring) to the vector
genes.push_back(genestring);
// accessing the second string 
//     (assumes there were at least 2 strings added)
std::cout << genes[1];
Murtan 317 Practically a Master Poster

This is the essential parts of the 'source' for the basic search form extracted from the web page you indicated:

<form action="/search.php#results" method="post">
<strong>Basic Search </strong>
<strong>First Name:</strong><br> <input name="fFIRSTNAME" type="text" size="10" maxlength="25" value="">
<strong>Last Name:</strong><br> <input name="fLASTNAME" type="text" size="10" maxlength="25" value="">
</form>

The <form> tells you that the form data is sent to the server via post, and the <input>'s give the field names 'fFIRSTNAME' and 'fLASTNAME'

You then 'encode' the form data and post it to the server.

There's a pretty good article on how to do that here:

http://www.voidspace.org.uk/python/articles/urllib2.shtml

Murtan 317 Practically a Master Poster

I think I'd use mktime or one of its equivalents, it calculates a time_t from struct * tm Read the notes about the tm_isdst field.

Murtan 317 Practically a Master Poster

I like the vector solution to only read through the file once.

I'm presuming you would have 2 vectors, one for genes and one for cells.

Is is possible that genes or cells might occur more than once in the file?

If they do occur more than once, did you want to put all of the data from all of the ocurrances in the same vector?

As the file looks to be an XML format, can you rely on the tokens being the only thing on the line?

(i.e. will it always be:

<genes>
data
data
data
</genes>

or might you see

<genes>data</genes>

?

Murtan 317 Practically a Master Poster

I didn't have any problems compiling your code with VC++ Express.

There were 3 warnings about converting double to float for yourPos(.1, .2, .3) It seemed to run as expected as well.

Just a couple of other comments:

Member functions do not HAVE to use accessors, even if it is not 'this object'. This compiles and works too:

Point operator +(Point &p) const
        {
            return Point(itsX + p.itsX, itsY + p.itsY, itsZ + p.itsZ);
        }

You should make reference parameters const anytime you don't intend to modify them.

Here's a slightly modified and slightly expanded version of your code:

#include <iostream>
using namespace std;

class Point
{
    private:
        float itsX, itsY, itsZ;
    
    public:
        Point(float x = 0.0, float y = 0.0, float z = 0.0): itsX(x), itsY(y), itsZ(z)
        {}
        float getX() const { return itsX; }
        float getY() const { return itsY; }
        float getZ() const { return itsZ; }

        Point operator + (Point const & p) const
        {
            return Point(itsX + p.itsX, itsY + p.itsY, itsZ + p.itsZ);
        }

        Point & operator = (Point const & p)
        {
            itsX = p.itsX;
            itsY = p.itsX;    //yes, itsX used purposely throughout for testing
            itsZ = p.itsX;
            return *this;
        }
};

ostream & operator <<(ostream & stream, Point const & p)
{
    stream << p.getX() << " " << p.getY() << " " << p.getZ();
    return stream;
}

int main()
{
    Point myPos(1, 2, 3);
    cout << "myPos location:\n" << myPos << endl;
    Point yourPos(.1, .2, …
Murtan 317 Practically a Master Poster

I still remember some of those days...

I started out trying to modify a "starwars" game (shoot the tie fighter) for the Commodore PET. I found that setting the high bit of the display byte would cause the character to be inverted (black on white vs white on black). So I thought hey, I could make the screen 'flash' when the ship blew up. So I wrote it up in BASIC to peek() and poke() all of the screen memory. I was SADLY disappointed in the performance, you could see the code work through the screen.

I'm not sure where I got the idea from now (its been a little while) but I was prompted to try the idea again in machine code. I found a book on 6502 assembler at the local Radio Shack and used it to write the code (and generate the bytes too if I rember right). I ended up writing the routine to XOR the high bit, so you called the routine once to invert the screen and once again to restore it. The performance of the assembly actually required a small delay between the two calls so that it looked like more than a screen flicker. (Much more satisfying.)

@Zach1188:

What does this code do (other than convert to a string and then back)?

GetLocalTime(&st);
    hr << st.wHour;
    mn << st.wMinute;
    
    std::istringstream sh(hr.str());
    sh >> iHr;
    std::istringstream sm(mn.str());
    sm >> iMn;

This code is all just to add one …

Murtan 317 Practically a Master Poster

After a little further searching, I don't see that any of the 'config' values from TFGame.uc (other than the one you are trying to add) are being used in TFMenuConsole anywhere.

Murtan 317 Practically a Master Poster

The if and else need to be 'inside' the case, and the if block and else block need their own set of braces { }. if (test) { // code } else { // more code }

case SMS_Construction:
			if(tfgame.ToggleWarhead == true)
			{
				SMNameArray[0] = "Shield (50/30)";
				SMIndexArray[0] = 1;
				SMNameArray[1] = "Protector (200/30)";
				SMIndexArray[1] = 2;
				SMNameArray[2] = "Portal (200/30)";
				SMIndexArray[2] = 3;
				SMNameArray[3] = "Armory (200/60)";
				SMIndexArray[3] = 4;
				SMNameArray[4] = "Generator (300/60)";
				SMIndexArray[4] = 5;
				SMNameArray[5] = "Outpost (600/90)";
				SMIndexArray[5] = 6;
				SMArraySize=6;
			}
			else
			{
				SMNameArray[0] = "Shield (50/30)";
				SMIndexArray[0] = 1;
				SMNameArray[1] = "Protector (200/30)";
				SMIndexArray[1] = 2;
				SMNameArray[2] = "Portal (200/30)";
				SMIndexArray[2] = 3;
				SMNameArray[3] = "Armory (200/60)";
				SMIndexArray[3] = 4;
				SMNameArray[4] = "Generator (300/60)";
				SMIndexArray[4] = 5;
				SMNameArray[5] = "Outpost (600/90)";
				SMIndexArray[5] = 6;
				SMNameArray[6] = "Warhead (3000/180)";
				SMIndexArray[6] = 7;
				SMArraySize=7;
			}

But this should work too and be a lot smaller:

case SMS_Construction:
			SMNameArray[0] = "Shield (50/30)";
			SMIndexArray[0] = 1;
			SMNameArray[1] = "Protector (200/30)";
			SMIndexArray[1] = 2;
			SMNameArray[2] = "Portal (200/30)";
			SMIndexArray[2] = 3;
			SMNameArray[3] = "Armory (200/60)";
			SMIndexArray[3] = 4;
			SMNameArray[4] = "Generator (300/60)";
			SMIndexArray[4] = 5;
			SMNameArray[5] = "Outpost (600/90)";
			SMIndexArray[5] = 6;
			SMArraySize=6;
			if(tfgame.ToggleWarhead == true)
			{
				SMNameArray[6] = "Warhead (3000/180)";
				SMIndexArray[6] = 7;
				SMArraySize=7;
			}

PS- please use c++ language code tags when posting c++ source
[code=c++] // your code here

[/code]

Murtan 317 Practically a Master Poster

If keeping the anonymous Atoms in a vector is what you have been doing, you were doing it right.

Objects from structs must be named for the compiler (according to the language's rules) at compile time, they cannot be defined at runtime.

But as I said before (and it is worth remembering) what the users see (or think they see) need not have any relationship to how the program stores and/or manipulates the data. If it is convenient, sure make the two similar, but when you run into a conflict, present the user with the 'correct' interface and massage the program to make it work. (Don't force the user to interact with the program in a certain way, just because that's how the data is stored/organized.)

Murtan 317 Practically a Master Poster

You never initialized aantal_getallen
which is the number of records to read/sort/print.

Murtan 317 Practically a Master Poster

And why are you posting in a thread last posted to in October 2007?

Murtan 317 Practically a Master Poster

This sounds a lot like another recent thread where the developer 'needed' to name the variables based on user input.

The name that you use inside the source need not have anything to do with the name the user sees. It would be your responsibility as the developer to map the elements of the array or vector or whatever other data structure you think would best fit your needs to the names the user is using.

Murtan 317 Practically a Master Poster

In the future, when posting c++ code, please use [code=c++] [/code] around your code.

Are you calling this with something like deleteData<Foo>(foolist); where foolist is a StdList containing objects of type Foo?

If so, I think it will work.

If you were working with other templated classes the type can be implied if you write the function that way. For example the following declaration would allow you to just call deleteData(somevector) where somevector is an instance of the std::vector template.

template <class type_name>
int deleteData(std::vector<type_name> myList) { ... }

Another option, should you be so inclined, would be to develop a template class that wraps their StdList to manage and enforce type for the list. Something along the lines of:

template <class type_name>
class MyStdList : public StdList
{
    // skipping a bunch of other methods
    type_name * getHead() {return (type_name *)StdList::getHead();}

    // I don't know if that have an addTail(), but if they did:
    int addTail(type_name * pObj) {return StdList::addTail(pObj);}

    // You could even at this point, add additional methods
    // say...deleteData?
    int deleteData() {
        type_name *element;
        int count = 0;
        while (!isEmpty()) {
            element = getHead();
            delete element;
            count ++;
        }
        return count;
    }
};

The template then 'knows' what type is supposed to be on the list and will 'prevent' you from putting the wrong thing on. If they have functions that take their StdList, you can pass an instance of the template in that place as it is derived from their …

Murtan 317 Practically a Master Poster

The reason it is main4() in my code is that this is the 4th version of the sort in the .py file main() was your version, main2() and main3() were versions of mine that did in another way. main4 is just a name, feel free to change it.

Python doesn't support a 'main'...the only reason your python file calls main is because you put main() at the bottom of the file without indenting it. So to run my code without losing yours, I wrote alternate versions of main (called main2, main3, main4) and called the one I was working on from where you called your main() .pop() always returns (and removes) the last thing on the list (unless you pass it an argument). If you were getting single letters, then the last thing on your list was single letters.

The following is the stream of input and output from an interactive python session: (started by just typing python)


This is what I saw when I typed what you posted:

>>> c=[0]
>>> print c
[0]
>>>

If c was a list, the c = [0] overwites the value.

Initialize a list and print the first item in the list:

>>> c =["Apple", "Banana", "Cherry"]
>>> print c
['Apple', 'Banana', 'Cherry']
>>> print c[0]
Apple

Iterating through the list to print it:

>>> for fruit in c:
...     print fruit
...
Apple
Banana
Cherry

Iterating through the list with indexes:

>>> …
Murtan 317 Practically a Master Poster

I'm kinda waiting on the OP (original poster) to see if they have been able to make the changes and get it to work so they can mark the thread solved or if there is more work to do to get it functional.

Murtan 317 Practically a Master Poster

You could modify it to keep more of the information as it went, but I'm not sure about how to get it to backtrack.

The base algorithm tracks for each target node in the system:

  • Has the node been processed (visited)
  • current least cost to get here
  • parent (or predecessor) on current least cost path

Arranged in a table of sorts. It initializes the table with the costs to get from the starting node to the nodes it can reach directly.

Then it loops, processing the lowest cost unprocessed node in the table until it reaches the destination node at the least cost.

This looks like it works really well, but does not support the requested edge limiting.

If we modified the information we keep as we go to include the length of the path and the previously found, something like this:

  • Has the node been processed (visited)
  • List of Routing Info:
    • edges to here
    • cost to here
    • previous node

We would have all the information required to solve the problem.
But I'm still not sure how to get the algorithm to 'backtrack' and try another route.

The only other method I come up with is an exhaustive search of all paths that meet the edge requirement. We could use something like Dijkstra's 'traveling' to find all possible paths from the start to the destination that meet the edge limit. We could either then price the routes …

Murtan 317 Practically a Master Poster

As I understand it, Python couldn't care less how many spaces / tabs you use other than requiring that all lines within a block must have the same amount of whitespace.

Any statements you have which start a new block (see above in this thread) require that the new block has more whitespace than the statement which introduced it.

That being said, although it would be legal to indent your first block 1 space, your second 8 more, and your third 3 more (etc., randomizing at will) it would make your code much harder to read.

I'm firmly in the 4 spaces camp. I do like the look, but the first selection of 4 was because it was the editor default.

Murtan 317 Practically a Master Poster

After looking at it some more, the idea I proposed (of just refusing to visit or process nodes if they would lead to a too many edges solution) could be 'led astray' with the right structure.

If there was route to the endpoint that was one edge too long, and a way to get to one of the intermediate points at a higer cost, but lower edge count, the algorithm would not ever see that lower edge, but higher cost path.

Thus the solution I proposed is flawed in that it would report a 'no solution' in the case of the example above. (If there were no other routes.)

Murtan 317 Practically a Master Poster

I like the concept. You could even pre-initialize the map in memory with default values before attempting to read the file. If the configuration was in the file it would be overwritten.

I do have a couple of questions though:

Where does the settings.txt file end up?.

In order to not conflict with other programs using the same design (and filename) the storage needs to be program specific (or the name does).

If the file contains user specific data and the computer has multiple users, the storage needs to be user specific or the application needs to take the logged-in user into consideration.

If the file is in the program's directory, it meets the program specific requirement, but you might need admin privileges to run it under some versions of windows.

Murtan 317 Practically a Master Poster

Bladtman242

You're right, you can't go else ... else. Your second test however (if written right as else if (! enhp < 1) or as else if (enhp >= 1) ) is the true inverse of the first condition and the last else would never be executed.

The first else was fine as written. The second else was supposed to be the else for if (num == 1) In the full code, the user is prompted to select 1 for attack again, or 2 to flee.

Murtan 317 Practically a Master Poster

Abstract classes are not instantiateable (you can't make one) for example, if Polygon is abstract, the compiler will not let you call: new Polygon(); A class is normally made abstract by defining one (or more) methods as 'pure virtual'. A pure virtual method is one that is declared (return type, arguments, etc.) but not defined (no function body).

Something like virtual int draw() = 0;

Murtan 317 Practically a Master Poster

So ana and kata are moves in the fourth dimension of the matrix.

You mention giving a cell a reference to all 8 of its neighbors. That sounds like it might be the hardest part of building the data structure. (I'm presuming you mean a link to the nearest cell in that direction).

Just to clarify my understanding (seems like you have it all down), the four indices are used for the following directions: east(-)/west(+), north(+)/south(-), up(+)/down(-), ana(+)/kata(-).

So the 'neighbor' link in the east direction would be to the cell that has the last three index values the same and the next lower value in the first index?

Just curious, what if there are no more cells before the edge of the map? Are you going to use a 'null' pointer, a pointer to a signal value or pointer to an edge node?

For this thread, I think you've been more help to me than I was to you :)

Murtan 317 Practically a Master Poster

What is the '{' on line 1 before the if for?

Where is the '{' after the if on line 1?

Why do you have '{' '}' around the statement on line 3?

What is the '{' on line 5 for?

Line 14 appears to be the else for the if on line 1. The else needs to follow either, the single statement that follows the if, or the block of statements surrounded by '{' '}'. Neither is true so the compiler complains.

(The compiler has no clue which if statement line 14 might belong to, but it does know that it is not following a statement or block that was the 'true part' of an if.)

So, recommended changes:

remove the leading '{' on line 1 (unless it serves a purpose later)

put a '{' on line 2

remove the '{' '}' surrounding line 3

remove the '{' on line 5

add a '}' (preferably on its own line) between lines 13 and 14

Murtan 317 Practically a Master Poster

I like that type of solution better myself, I was just trying to make the regex work as that is what the OP asked for.

Not that we always give them what they ask for :)

Murtan 317 Practically a Master Poster

You didn't note any constraints other than "the array is mostly empty, and how can I make it smaller" so I wasn't concerned with any.

In the case of the dictionary, we would only store the data values that exist, the 'empty' spots would not exist. Testing for whether or not something exists in a dictionary is pretty straightforward but I'm not sure about your read/framerate.

So are you saying that for every frame, you might have to read 128,000 cells?

If so, what defines a 'manageable framerate'? (Is this really a 'I need to generate at least X frames a second' requirement?)

The method I proposed probably doesn't support a 'quick-fetch' of anything, let alone a hypercolumn.

To be honest, I'm not familar with the terms you're using. I supposing a hypermatrix is called that because it exceeds three dimensions?

What is a hypercolumn?

How is it defined in terms of the array dimensions?

(Which index values would remain constant? Which would change?
)

I attempted to google for your projection terms and didn't get any hits there either. Could you give a rough overview of how the projection is developed? (pseudo code is probably better than real code) for my purposes.

I'm trying to better understand what you are doing to see if I have (or can find) a 'better' answer.

Murtan 317 Practically a Master Poster

You could use a dictionary where the key was the composite index, something like key = "%d_%d_%d_%d" % (w,x,y,z) or key="W%dX%dY%dZ%d" % (w,x,y,z) . I think the dictionary would manage the collection fairly well.

Murtan 317 Practically a Master Poster

I agreed earlier that the construct was legal. But then code obfuscation contests produce legal code, but I wouldn't accept them as a deliverables either.

My point is that although the syntax is perfectly legal and permissable, it is less maintainable. I would be less likely to notice that you neglected to release the memory (if I didn't complain about how you stored the allocation in the first place).

There is no real cost to using the Type * ptr = new Type other than having to type -> rather than . . But I would argue for longer more verbose variable names as well, so I'm not totally against a little typing.

Some of this may be biased from my background. I've been working for over 15 years in control software systems where the software runs 24x7, preferably for months at a time and we can't really afford to waste any of the system resources.

Given enough time, even a little leak can cause problems. So we spend a little extra time when there are pointers involved to make sure that if they were allocated the ownership (and deallocation responsibilities) are well defined and followed.

If you made a habit of taking arbitrary pointers and assigning them to references, you would have to spend the extra time looking at references as well.

So in a well defined case (like your ProxyA example) where I can clearly see the allocation and the deallocation, I …

Murtan 317 Practically a Master Poster

Ok...I will do this once, feel free to re-format afterwards, but here is your code. I put each brace '{' or '}' on its own line and then begged my editor to try to make it look better.

(I made no other changes, even though it needed them.)

#include <iostream>
#include <string>
using namespace std;
int main (void)
{
    int num, random_integer, hp= 100, enhp= 50;
    while (hp >=1 and enhp >=1)
    {
        srand((unsigned)time(0));
        for(int index=5; index<10; index++)
        {
            random_integer = (rand()%10)+1;
            hp = hp-random_integer;
            if (hp>=1) //remember, multiline if statements require brackets to function
            {
                cout<<"\nThe enemy does "<<random_integer<<" damage, leaving you with "<<hp<<" health.";
                cout<<"\n1)Attack!\n 2)I've had enough- run away!";
                cin>>num;
            }
            else
            {
                cout<<"You have died, better luck next time,";
                system("Pause");
                return 0;
            }
            {
                if(num ==1)
                {
                    srand((unsigned)time(0));
                    for(int index=10; index<20; index++)
                    {
                        random_integer = (rand()%10)+1;
                    }
                    enhp = enhp-random_integer;
                    {
                        if(enhp< 1)               //Victory condition. Breaks loop after enemy death
                        {
                            cout<<"The masked man falls to the ground, defeated.";
                            break;
                        }
                    }
                    cout<<"You have done "<<random_integer<<" damage." ;
                }
                else
                {
                    cout<<"You have fled"; break;
                }
            }
        }
    }
}
}
cout<<"Terrified, you run through the streets. Where is you father? If anybody'll know what to do, it'll be him.";
system("PAUSE");
return 0;
}

As noted by the previous poster, you're still calling srand() from multiple locations and from within a loop.

I would put one call to srand() between line 6 and line 7 and then get rid of the rest.

Murtan 317 Practically a Master Poster

Ok so its a form of hiding the full implementation of A from the users of ProxyA which provides a subset of the full implementation without having to re-write any code because it uses A to do the work.

Because ProxyA only has a reference (or pointer) to an A, you don't have to have the full A headers in the ProxyA header file (which the users of ProxyA will have to include) you only have to have them in the ProxyA source file. I can see that as a useful abstraction, and in the context you presented it the reference holding the allocation would be safe.

You mentioned that the members of ProxyA don't have to keep checking if the pointer is NULL because you use a reference. The only protection you have is that the constructor will fail if you can't get memory allocated. If you added your own test to the constructor, you could get the same safety with a pointer, but you do have to do the extra work.

The problem I've always encountered with this type of proxy was that it either the features proxied were limited, or the proxy would have to re-declare items from the class being proxied. An example might be an enum value used for a paramter to one of the methods of the A class. Either ProxyA must presume (or be able to determine for itself) what the enum parameter should be, or the enum has to …

Murtan 317 Practically a Master Poster

I will agree that the allocation will not leak if the ProxyA doesn't get lost, but in that context, why allocate it at all?

It could just be a member of the proxy.

class ProxyA {
public:
    ProxyA();
    virtual ~ProxyA();
    virtual void doit();
    // ... other interface members
private:
    A a;
};

Then you never have to allocate or deallocate it explicitly.

Murtan 317 Practically a Master Poster

void doesn't return, but void * or in this case void *** does.

A char * * * is a pointer to a pointer to a pointer to char.

Its a bit of an odd construct, I don't recall using triple pointers much.

I would agree that you should avoid exit when possible, but in this case, they wanted the program to halt if allocation failed. That is surely what exit() does. I can't really argue their use in this context, feel free to describe how you might prefer to handle an "I can't allocate enough memory" problem MosaicFuneral.

Ok on to making an attempt to understand the code:

Re-posting code with [code=c] so we get line numbers:

void ***array3(long d1, long d2, long d3, long size)
{
   char ***a;
   long i,j;

   a = (char ***) my_malloc(d1*sizeof(char *));
   a[0] = (char **) my_malloc(d1*d2*sizeof(char *));
   a[0][0] = (char *) my_malloc(d1*d2*d3*size);
   for (i=1;i<d1;i++) {
      a[i] = a[i-1] + d2;
      a[i][0] = a[i-1][0] + d2*d3*size;
   }
   for (i=0;i<d1;i++)
      for (j=1;j<d2;j++)
	 a[i][j] = a[i][j-1] + d3*size;
   return (void ***) a;
}

Line 6 allocates (in a) an array of d1 pointers.

Line 7 allocates (in a[0]) enough space to hold an array of d2 pointers for each of the d1 pointers allocated on line 6.

Line 8 allocated (in a[0][0]) enough space to hold all of the data. There are size bytes for each of the d3 data items in each of the d2 pointers …

Murtan 317 Practically a Master Poster

dougy83 you could make that assignment to hold the allocation, but to me it looks like a memory leak waiting to happen and in a professional setting I would fail your code review for it.

There are also data structures that lend themselves to pointers, for example linked lists.

As another example I can remember a buffer that we implemented between a producer and a consumer. The producer tended to produce data in bursts and we couldn't make the producer wait until the consumer cleared out enough of the buffer. We ended up growing the buffer when it ran out of space. (The allocation of a new buffer and copying the data with memcpy was pretty quick.) The class that managed the buffer had to use a pointer to reference the buffer and could not have used a reference.

Murtan 317 Practically a Master Poster

I came up with a couple of regexes, depending on whether you want cogger to the end of file, or just cogger to the next agent (or end of file)

import re

data = """User-Agent: Googlebot
#Disallow: /
Disallow: /comments
Disallow: /user
Disallow: /poll
Disallow: /print
Disallow: /search

User-Agent: Cogger
#Disallow: /
Disallow: /comments
Disallow: /user
Disallow: /poll
Disallow: /print
Disallow: /search

# Alexa Archver, allow them
User-Agent: ia_archive
Disallow: /comments
Disallow: /user
Disallow: /poll
Disallow: /print
Disallow: /search
"""

print "-- Greedy match --"
mm = re.search("User-Agent: Cogger[ \t]*\n(.*)", data, re.DOTALL)
if mm:
    lines = mm.group(1).split('\n')
    for line in lines:
        print line

# output
# -- Greedy match --
# #Disallow: /
# Disallow: /comments
# Disallow: /user
# Disallow: /poll
# Disallow: /print
# Disallow: /search
#
# # Alexa Archver, allow them
# User-Agent: ia_archive
# Disallow: /comments
# Disallow: /user
# Disallow: /poll
# Disallow: /print
# Disallow: /search
#


print "-- Not so greedy --"
mm = re.search("User-Agent: Cogger[ \t]*\n(.*?)(User-Agent|$)", data, re.DOTALL)
if mm:
    lines = mm.group(1).split('\n')
    for line in lines:
        print line

# output
# -- Not so greedy --
# #Disallow: /
# Disallow: /comments
# Disallow: /user
# Disallow: /poll
# Disallow: /print
# Disallow: /search
# 
# # Alexa Archver, allow them
#

Note that both of them seem to have extra at the end.
And you'll probably have to deal with the comments (I'm presuming that lines that start with # are comments.)

Murtan 317 Practically a Master Poster

Your code as you posted it is basically correct.

The include for some should be #include "some.h" the version you used will not search the current directory the quote version will search there first.

The function prototype in some.h should match the function signature. Your some.h has void some() but your some.cpp has int some()

Murtan 317 Practically a Master Poster

somnathsarode if you are going to post code, especially in response to a thread, please use the appropriate code tags.

For this forum:
[code=c] /* your code goes here */

[/code]

Your response followed the original poster saying "Thanks ... did just what I wanted." Almost seems like the thread was answered doesn't it.

Murtan 317 Practically a Master Poster

Comments on the original code (that's all I have to look at):

You're really only supposed to call srand() once per run you don't have to call it everytime you want a random number.

In the original code, the 'I want to quit' option prints "You have fled" but it is still inside the for loop so it keeps fighting.

The outer while loop that we spent the time talking about is actually never tested. When the for loop terminates, the main() returns before the while gets a chance to be tested.

If your code has changed significantly, please re-post it.

Please use language specific code tags:
[code=c++] //your code here

[/code]

Murtan 317 Practically a Master Poster

You have been given several suggestions. I haven't seen anything that you've tried, all I've seen are comments that it isn't working -- and I followed those up with what was wrong and I thought I told you how to fix it.

Post the code as it now exists and please confirm whether you want a string with the two characters in it ("23"), or the numeric value of the number formed by the two characters (23). If you want to perform a numeric comparison (say to see if the value they entered was < 30) then you need the numeric value.

Please enclose your code in code tags with a language specifier:
[code=c] /* Your code here */

[/code]

PS- It may have felt like 2 days, but your first post was 13 hours ago.

Murtan 317 Practically a Master Poster

I was trying to get you to explain what it was you thought you needed. If you don't know what you need, how will you know when you find it.

Murtan 317 Practically a Master Poster

So its not really a shortest path, its a 'cheapest' path, but with an edge limit.

Something along the line of the travel agent telling you that you can save $20 by connecting through 5 cities -- you'd rather spend the $20 and save the stops.

I haven't looked at the A* algorithm in detail and I don't recall Bellman-Ford. Logically, it would seem to be fairly straightforward to either short-circuit the search to fail a path when it exceeds the specified length, or to 'modify the cost' of edges beyond the limit to make them appear cost prohibitive. Though if the algorithms are doing other work to minimize the amount of work to be done I guess it could be harder to 'make it fit'.

So the given data for the problem is:

  1. The list of nodes
  2. The edges (connections between nodes) and their costs
  3. The maximum number of edges (N)
  4. The starting node
  5. The ending node

Is it possible that there may be a 'no solution'? (If N was sufficiently low, there might be no path that has fewer than N edges.)

I found a couple of links to an algorithm that looks like you could modify to not only track the 'cost' but also the number of edges consumed to get there and just 'not visit' (don't look for more paths from) nodes that it already takes N edges to reach:

Dijkstra Shortest Path Algorithm or

Murtan 317 Practically a Master Poster

The 'syntax' question you were ask would be easy to answer if you had 2 strings instead of 2 characters.

In C, you make your own strings if you're taking input one character at a time.

If you wrote:

char dd[3];
dd[0] = getinp();
dd[1] = getinp();
dd[2] = '\0';

Now dd is a real C string. If you wanted to assign it to another string (of sufficient size or bad things happen) you could strcpy(otherstring, dd); But your problem description implied that you don't really need the string, you want the number that it would represent (which is why my previous posts look like they did.)

Murtan 317 Practically a Master Poster

Your original program declared aa as an array of characters:

char dd[1], aa[2];

In your most recent post, you treated aa as an integer:

aa = dd[0] + dd[1]; // aa will then have 23
if (aa > 30)

So I did too. It is not permitted to assign to the array.

Change your declaration to:

char dd[2];
int aa;
Murtan 317 Practically a Master Poster

Are you saying that you want an algorithm that will return longer paths if the shortest path has too many edges?

Is the longer path likely to have fewer edges?

Murtan 317 Practically a Master Poster

Not to be picky, but #define NUMBERS is a pre-processor directive and doesn't get scope.

(But it should have been outside the function anyway.)

Aia commented: Correct +12
Murtan 317 Practically a Master Poster

If dd[0] and dd[1] contain the character they entered, the character is NOT the numeric value. (For example in ASCII '0' is 48)

So if the example is dd[0] = '2' and dd[1] = '3' then aa = dd[0] + dd[1]; would give aa the value 50 + 51 or 101.

If you want the numeric value I usually do something like (dd[0] - '0') which in our case would be 2.

So if we did that as we went, we could write

aa = (dd[0] - '0') + (dd[1] - '0')

There, now aa is 2 + 3 which makes aa 5. (wait, didn't you say it should be 23? maybe I missed something.)

I guess I could have done:

aa = 10 * (dd[0] - '0') + (dd[1] - '0')

That would be 23.

You could probably even do it without the array of characters (unless you needed them for something else):

aa = (getinp() - '0');
aa = 10 * aa + (getinp() - '0');
Murtan 317 Practically a Master Poster

I think it would depend a on how you search the subtables.

From your description, I'm presuming that the data in the subtables are ordered and that the subtables are in order as well.

You described the search to find the correct subtable: sequential search through the highest value in the subtable until you find one higher than what you're looking for.

You didn't describe the search through the subtables, but for the sake of argument I will presume that it is also a sequential search through the subtable from smallest to largest.

So the most optimally found value (2 compares) is the lowest value in the collection.

The worst case (i + j) would be the highest value in the collection.

Everything else is somewhere in between.

Is that what you were trying to ask?
So if the search algorithim is a sequential search across the highest key in the subtable (until you find one higher than the value you're looking for).

Murtan 317 Practically a Master Poster

That sounds like basic Geometry or Physics, but let's play pretend.

Pretend you're writing a function to calculate what you want. Write a prototype for the function. (What arguments will it take, what will it return?)

Murtan 317 Practically a Master Poster

I think I understand your data structure from your description.

I think I understand how you search it.

I think I can agree with your premise for the worst case search. I think the math for your average case should be i/2 + j/2.

However, I don't think I understand your last question. You seem to be asking something about a 'best case' but I don't understand what you are asking for.