Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Could you post your exact code here, please? I have a suspicion why it isn't working, but it is hard to say without seeing what is actually running.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Sounds like a good exercise. What do you have so far?

folabidowu commented: i have done something got confused along the line. am new in C++ +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

can anyone help me to create a program that alows me to make a regular conversation with the computer?

If anyone can, they should contact the Turing Award committee immediately...

Seriously, this isn't anything even remotely trivial. Even a program like an ELIZA-class chatterbot is a sizable project, if you mean to have give it a significant 'phrasebook'. One that can accept a large number of varied inputs, such as Apple's Siri, is something that would take years for both programming and preparing the phrasebook. Even then, it is only a simulation of a real conversation, and tripping it up isn't difficult.

Creating a real, responsively conversational program would probably require solving the hard AI problem - that is to say, it would actually have to be a self-aware, sentient program - which is an ongoing research topic and may not even be possible.

rubberman commented: Great! I missed the chatterbot link... :-) +12
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

As an aside, it should be mentioned that cross-posting to multiple forums is generally frowned upon, as it leads to repetition of effort, and also clutters up the fora. If you feel the need to cross-post at all - and you almost certainly shouldn't unless you are certain that it will make a difference - you should at least give a link to the other fora you've posted to.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

If I may comment (even if it is a bit late), I would add a recommendation to apply named constants more extensively than you have. You have a number of places where you are using magic numbers which are used repeatedly. It is good to get into the habit of saving any numeric constants in a variable (Python doesn't have constants per se) rather than having to figure out why that particular value was needed at a given point later on.

I've also noticed that you use the rate() function to set the speed of the clock. This isn't the correct function to use; it only affects the frame rate, not the speed at which the loop runs. I would recommend using sleep() instead, as it is more likely to be accurate to a second (it still won't be perfectly accurate, but it will be closer), and it also avoids busy waiting.

Finally, You presumably want to have the starting values for angle and angle2 (which really should have better names) to the value for the 12 O'Clock position, which would be 2π radians. Again, making this a named constant would make sense, as you'll use it in multiple cases. Similarly, you will want to advance the second and minute hands by 1/60th of the circle each time you move them, and the hour hand by 1/24th.

Here are the constants I recommend using for this. I would actually recommend making a class ClockArrow, as a …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

What sort of problem are you having, or trying to solve? We will need more information before we can give a sensible answer.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

duskoKoscica: I think you will find this post helpful in clarifying why you should avoid having function implementations in header files.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

dusts off my boilerplate reply once more

First off, we don't do other people's homework for them. Second, we don't do other people's homework for them. And third, we don't do other people's homework for them. Sensing a pattern here yet?

No one here will simply hand you a solution on a silver platter. If you show us what you've done, what you've tried to do, and what problems you've had with it, then we'll be happy to help. If you have specific questions, we can answer them, or at least point you in the right direction. If you have a program with a bug you can't swat on your own, we'll be glad to assist, so long as you pay attention to the forum rules and post sensible questions in an intelligent manner that we have some reasonable hope of answering.

But just cutting and pasting an assignment into a message, without even prefacing it with something like, "I have this homework problem that I can't solve...", is likely to get you booted from the message boards here and elsewhere - if you're lucky. What happens to you if you are unlucky is... well... let's just say that this guy probably won't be trying that again, on that forum or this one.

And if you think you won't get caught by your professor... think again.

We take this issue seriously here. Very seriously. Asking us to do homework for …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

There are two problems I can see in the code, the main one being that you are multiplying the odd numbers rather than adding them. You also have an extra pair of brackets around the body of the main() method, which isn't a syntax error, but does confuse things somewhat. Proper indentation would make correcting that simpler.

public class OddLoop { 


    public static void main(String[] args) { 
        {   // note the extra bracket 
            int total = 1; 

            for (int i = 3; i <= 15; i += 2) { 

                total = total * i; 

            } 
            System.out.println("The sum of the odd integers is:" + total); 
        }   // note the extra close bracket
    } 
} 

Here's the code as I've corrected it:

public class OddLoop { 

    public static void main(String[] args) {  
        int total = 0; 

        for (int i = 3; i <= 15; i += 2) { 
            total += i;
        } 
        System.out.println("The sum of the odd integers is:" + total); 
    } 
} 

As for the logic for the average, the main thing you need that you don't have now is the number of odd integers which you are summing. This can be solved by adding another integer variable, count, which counts the number of loops performed. You then simply divided total by count to get the average.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Ah, I had been of the impression that gotoxy() was a console mode function; I didn't think it would work for text in a graphics mode application (which the particular coordinates mentioned implied). If I was wrong in that, I apologize.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, please do not hijack threads from years gone by, even if they are related to your question. In the future, you would do better to start a new thread for your subject.

Second, Turbo C++ has no direct support for modern fonts as far as I know, and the bitmap fonts it did support are poorly documented. this thread discusses the difficulties you are facing trying to use <graphics.h> for text.

Keep in mind, you are using a DOS mode compiler that is now 25 years old. It is no longer even usable under Windowd Vista/7/8, without special emulation. If you can, I would strongly recommend using a different compiler and IDE, such as Code::Blocks.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

No, I mean that the real target of the crack is the part which is always vunlerable: the human being invloved in entering and using the data.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Actually, what crackers 'hack' is mostly other people's impatience, ignorance and willingness to go along with percieved 'experts' and 'authority figures'. It's called Social Engineering and it is the majority of how crackers circumvent both software and systems. Even software cracks such as program security exploits mostly depends on being able to identify and exploit the weaknesses of the programmers and users, rather than of the code itself.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, I trust that this is indeed urgent for you, but you should be aware that it isn't necessarily going to get us moving faster. The forum moves at its own pace; you might get an answer right away, or the next day, or next week, or never. I wouldn't pin my hopes on us too strongly, is all I'm saying.

That having been said, I will reply to your request with another question, or rather several questions. Please bear with me, as there are a lot of variables at play with what you trying to do.

First off, what image format are you working with? Is it a raw bitmap, or a compressed format? Is it a file that you are loading into memory, or an image already in memory that you need to manipulate? Do you need a library that can load and save the image to the necessary format?

Second, is the goal the procedure, or the program? That is to say, do you need the titling, or are you writing a program that happens to need to support titling? Could you use an existing program for what you are doing, such as GIMP, or does this have to be a new program (or part of a new program) that you are expected to write?

Third, where is the image to be output to: the local display console, a printer, a web page, or some other kind of display? Do you already have any program …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Actually, the stdafx header is specific to Windows, and to Visual Studio in particular. Most other C++ compilers are only going to have the Standard C++ libraries, plus whatever system libraries are used on that OS. Since MacOS X has FreeBSD as it's kernel, XCode should provide most if not all the Unix libraries available to it.

OTOH, if you are looking for an IDE that provides drag-and-drop visual design tools, I'm not sure what you would be looking at. I'm not very familiar with XCode, personally, so I don't know what it comes with, or what extensions are available for it. However, I know that there are versions of Eclipse and NetBeans for the Mac, and while both of those are aimed mainly at Java, both have C++ support as well.

For a basic IDE and compiler, I would try Code::Blocks with GCC. It isn't as full featured, but it is fairly easy to use, and has plenty of support.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I would further recommend re-writing the side() function by removing the user interaction, so that the function is responsible solely for computing the desired result:

def pythagorean(first, second):
    ''' pythagorean(float, float) - 
    Function to compute the length of a side of a triangle
    from the lengths of the other two sides.'''
    return math.sqrt((first**2) - (second**2))

# ... later ...

result = pythagorean(3, 4)  # result will equal 5 

The reason for this threefold. First, it simplifies the function, so that it is clearer what it is meant to do. Second, it generalizes the function, making it easier to use in different places for different purposes. Third, it is generally a good idea to separate the code that performs the actual computation from the user interaction, so that it is easier to change either or both of them without interfering with the other; mixing two different operations generally makes for code that is difficult to maintain. Separating the code this way is just a good way of avoiding future issues.

Note also that I added a simple docstring comment to the function. This makes it so that pydoc (the Python documentation tool) can extract the docstring and generate user documentation for the function automatically.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

ArashVenus: There really isn't any exact replacement for getch(), for the same reason why there wasn't a standard equivalent of getch() to begin with: because 'raw' or unbuffered console I/O isn't portable across different operating systems. The C standard library, and the C++ iostream classes, work exclusively with stream I/O, which does not allow for unbuffered keyboard input. As far as the stream I/O functions are concerned, it is irrelevant whether the input comes from a console, a file, a pipe, or a network socket. While this is a useful abstraction, it makes writing screen manipulation routines harder. The closest equivalent to the conio functions that is even remotely portable would be Curses or its variants, and even then it is mostly aimed at Unix-like systems.

That having been said, the most common use for getch() was to pause the console at the end of the program, so that the window doesn't close. This isn't needed in more recent IDEs like Code::Blocks or the current version of Visual Studio, as they automatically pause the console window when the program is done.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, let's start with a few issues in your code. First off, main() should always be declared as type int in C++; there are some exceptions to this, but as a rule, void main() is simply incorrect.

Second, you seem to be using an older style of C++ header; with modern C++ (that is, after 1998), the standard library headers should not end with an .h, as they do in C, and C libraries should be pre-pended with a c. Thus, you should have the follow directives instead:

#include <iostream>
#include <fstream>
#include <cstdio>
#include <string>

Note that I removed the reference to <conio.h>; this is not a standard header, but one specific to the older DOS versions of Turbo C++, and should never be used in any new code for any reason. Since you don't seem to actually use it, except to capture the screen, it is safe to simply eliminate this.

I'm guessing that you are using Turbo C++, correct? If you have any choice in the matter, don't. It is now more than 25 years old, and is tied to functions of the DOS operating system which modern Windows systems no longer support (especially with Vista and later). By using Turbo C++, you are shooting yourself in the foot. I know that some schools have standardized on Turbo C++, but I will tell you this right now: you are learning a version of C++ that is nearly 15 years out of date. Get

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Well, yes, though this sort of project is really a great deal more complex than is likely to be easily resolved in a single post, or even an entire thread of posts. This thread on Dev Shed is probably still a suitable starting place, especially the second post in it, even if some of the links are stale; you might also want to see the Compiler Development Wiki as well, though that is frequently offline. Finally, you may want to look at some existing compiler projects, such as my own Suntiger Algol compiler (it is written in Python, rather than C++, and the desing is a bit unusual, but it should be clear enough to give some idea of how it works).

Can you tell us what you already know about, say, leixcal analysis, and show us what (if anything) you've done so far?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The line between 'helping you finish a project' and 'helping you cheat' is a fine one, at times. However, in this case the Daniweb rules are pretty straightforward:

Do provide evidence of having done some work yourself if posting questions from school or work assignments

So: Show us what you have done so far, and tell us what you are having difficulty with, and we will assist you. We will not, and cannot, provide you a solution without you showing some effort on your part.

BTW, you should know that the Travelling Salesman Problem is a classic one, with many variations, and is provably NP-complete (meaning that all the known general solutions require non-deterministic polynomial time; any solution in less than exponential time would effectively be a proof that NP = P, which is an open question to date and thought by many to be undecidable). Just so you know.

aroshkhan commented: haha great (Y) +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Wasn't resursive algorithms non-efficient ?
I mean if you look at recursive fibonacci's runtime you'll see Its not efficient at all O(N^2) !

It depends greatly on the particular algorithm. While recursion is generally less efficient due to overhead issues (which can be obviated in some instances by tail-call optimization, and by memoization for functional programs), most recursive algorithms are not inherently less efficient than iterative equivalents. The fibonacci algorithm is a specific case where, yes, the naive tree-recursive form is grossly inefficient compared to the naive iterative algorithm, but this isn't going to hold for all recursive algorithms.

OTOH, as mike_2000_17 points out, iteration is in general a better 'fit' to the conventional random-access sequential machine model. Even in languages like Scheme, where recursion is the natural means of repetition, it is common to use iterative algorithms (even if they are implemented by means of recursion) for anything requiring efficiency.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

novice C++ programmers are often given little if any experience with recursion

I tend to think otherwise, "students" of programming and computer science often know far too much about recursion, and tend to over-use it a lot.

Really? Perhaps things are different at your university, but most of the recent IT graduates I've spoken with in the US don't even know what recursion is, and have never used it at all. Certainly many of my colleagues from other countries - India and Pakistan especially - are completely unfamiliar with it, even after years in the industry.

Then again, most IT programs I've encountered are more like trade school courses than real university programs, with a nearly exclusive emphasis on writing code in a specific language (usually either C++ - often pre-standard - or Java from circa 2000) and a smattering of algorithmics and maybe some 'software engineering' (invariably based on 'waterfall' design concepts from before 1990). Many have never written a program more than 250 lines, it seems, and few have had any collaboration experience; on the job training is often more thorough than their formal education. I can only think things must be different at McGill, if what you say is true. It's good to know some places actually teach, rather than 'train'.

Perhaps I am over-emphasizing this, but I don't think by much. If anything, it's worse than that. The number of times I've seen professor give 'fill in the blanks' projects, where they …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The problem with this implementation is that it requires busy-waiting, something which presents a problem on multi-tasking systems. A proper sleep() function, one which passes control to the system scheduler and allows other processes to run, would not be portable between Windows and the various Unix-like systems.

Moreover, while in practice time_t is almost invariably defined as an integral value holding the seconds since 00:00 1 Jan 1970, the key word here is almost. Officially, there is no fixed meaning of the time_t values; the standard does not require it to match that definition, even if all Unix and Unix-like systems (and most systems that emulate them in the C/C++ libraries, like Windows) actually use it this way.

So why doesn't the standard define time_t's meaning? Simple: the C language (and hence C++) was always intended to be portable to all systems, even minimal ones which don't have things like real-time clocks, or ones whose operating system does not expose compatible time management operations. The C language and libraries have amways been based on the principle of requiring the least possible system support, as the language was, and remains, primarily aimed at system programming, and specifically for implementing operating systems.

While C++ could have extended or replaced the C functions with a more complete DateTime class or classes, to date they haven't done so, largely because C++ generally tries to maintain the C approach of minimal system requirements. While it does not maintain the strict minimalism of C - exceptions …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

In most modern languages, there are two fundamental approaches to repeating an action: either iteration, in which an action is placed inside a special-purpose structure which causes the action to be repeated, or recursion, in which a general-purpose function calls itself (or another function which in turn calls the earlier function). Which is to be used depends on the nature of the problem at hand, and to a great degree, the language being used. Some languages, especially Lisp and the various functional languages, strongly favor recursion; but most other languages, including C++, focus almost entirely on iteration.

As a result, novice C++ programmers are often given little if any experience with recursion, which tends to lead to it being overlooked even for problems where it is well suited. Also, recursive design takes a very different view of what it means to repeat something, and the approach can seem alien to programmers more familir with iteration. Finally, because it is based on function calls, recursion generally takes more memory and time than the equivalent iteration, and while there are ways for a compiler to optimize away this overhead for some types of recursion (specifically tail calls, where the recursive call is the last step in the function), few C++ compilers do any tail call optimization. As a result, recursion is poorly understood by many C++ programmers.

This is unfortunate, as in some ways recursion is the simpler of the two approaches to looping. It does not require any additional language constructs …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The strcmp() function compares the ASCII values of the characters one by one. If all the characters match, it returns zero; otherwise, if the first differing character in the first string has a lower ASCII encoding than the compared character in the second string, it returns a negative, wheras if the first string's character is higher, it returns positive.

Mind you, it's important to keep the difference between C-strings and string objects in mind, as they are quite different things. The fact is that C-strings are something of a second-class type in C, which carries over to C++; they are as much a convention as they are an actual type, because it is up to the functions which operate on them to do things like check the size of the string, ensure that there is a zero-delimiter at the end of the string, and so forth. The C++ string class and objects are quite different, being fully qualified objects in the language with a large amount of functionality built into them. They are more opaque than C-strings, but more flexible, and for most purposes, easier to work with. While it is farily easy to convert C-strings to strings (using the string c'tor) and back (using the .c_str() method), they are not at all the same thing.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I'm afraid we'll need more information about the problem you are having in order to give you any advice. Is this your own code, or was it provided by your instructor? Have you tried compiling and running it, and what was the result?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Ah, thank you for the correction.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Actually, Deceptikon, this is one place where C and C++ part ways; the C++ standard does require and int return value, and always has, whereas the older C standard recommends but does not enforce it.

IIUC, the C11 has changed this to require an int return as well, even on systems where it isn't needed (presumably, the compiler simply discards it, in those cases). Can anyone confirm or deny this?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, there does seem to be some confusion here, and we may be able to guide you somewhat.

First off, the assignment doesn't actually involve Notepad, or any other text editor for that matter, except perhaps for when you first create the file to be searched through. A text file isn't strictly something in Notepad; rather, it is a generic file format, with data stored as ASCII (or possibly UTF-8) text, and can be accessed from several different programs - including the one you'll be writing.

Now, you say you've only been studying Python for two days; if that is so, it seems odd to have a project involving file handling so soon. Is this for a course, or self-study, or something you are doing for a job? What have you learned so far? Are you working jsut from the Python interpreter prompt, or writing programs separate from it? If the latter, what editor or IDE are you using (e.g., IDLE, Dr Python, Eric, PyCharm, PyPe)? How are you running your programs? What version of Python (2.x or 3.x) are you using?

Have you learned how to write a for: loop? A while: loop? Do you know how to define a function? Do you know how to read from and write to a file? Do you know any of the basic string handling methods (.join(), split, etc.)? Do you know how to compare two strings?

These are all things which are going to come up in you project, and we …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Then you should have asked the question in a new thread, rather than raising a long dead one back up.

As for the answer to your question, the original C++ compiler was written in C, and most C++ compilers today are written in either C or C++. I gather, however, that your real question is, 'how did they write the first compilers without a compiler to use?' The answer is, they used assembly language and an assembler. But how was the first assembler written? Simple: it was written in assembly language, and then hand-assembled into some representation of machine code (in octal or hex or what-have-you).

However, that would have been a long time ago; by the mid-1960s, high-level languages were dominating the field, though machine code and assembly came into use again briefly when the first personal computers came on the scene circa 1974. Today, when a new model of CPU is made, the software for it is first written on some existing system, then cross-compiled to the new system. It is exceedly rare for anyone to do any machiine-code programming today.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The simplest solution is to convert the first token (that is, the first contiguous series of characters) of each line to an integer, and sort by the integers. Given this approach, it would then make more sense to use an STL map(), which automatically sorts itself according to a predicate passed as an optional template parameter, rather than sorting the list after the fact. Since the default sorting uses the less comparison, you may not even need the predicate.

std::map<int, std::string> sorted_strings = std::map<int, std::string>(); 

while (getline(in, line)) 
{
    std::stringstream ss;
    ss << in;
    int key;
    ss >> key;
    sorted_strings[key] = in;
}
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, first off, thank you for posting a message with a title other than 'C++ Code'. That is a first step, so credit where credit is due.

OTOH, reposting the same question in three different threads in two different fora is not a good thing. Please try to stick to a single thread in the future. Please show some patience, as it can take a while for us to respond.

On the gripping hand, simply posting your assignment without any explanation, and without showing us what you've done to solve it yourself, is extremely rude. It also violates one of the rules of Daniweb:

Do provide evidence of having done some work yourself if posting questions from school or work assignments

In other words, Show Us The Code. We aren't going to solve this problem for you; we will help you solve it, but you need to demonstrate that you've put some effort into learning this yourself.

Finally, weren't you the one who just posted a question about implementing the Fibonacci function? This project is significantly more difficult. How did you jump from that to this?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, you should never declare main() as void in C or C++; in C, int main() is the only portable form of the function, and in C++ (and the most recent C standard) it is actually required to return int.

Now, with that nitpick out of the way, I have to say that what you're doing doesn't make much sense. Let's break it down piece by piece:

You declare FUNC() to have file scope, and than put a wrapper around it (CALL_FUNC()) with top-level scope. Why? WHat is the wrapper protecting?

You then call CALL_FUNC() in two different source files, but without any function prototypes to make the function definition visible to the calling functions.

Finally, you have an empty main(). What is that intended to accomplish?

Can you explain, in words (not code) what your intention is? Is there a reason for Var1 and FUNC() to be declared static, and if so, what is it?

Finally, I would recommend reading this post for further Illumination fnord on the subject of header files, function prototypes, and so forth.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I am currently working on a new language design in the Lisp family, which I am calling 'Thelema'. It is intended to be a multi-paradigm language which is related loosely to Scheme and, to a lesser extent, Common Lisp, but with modern concepts such as package management, support for object oriented design, and an extensive library system.

The current design sketch can be found on its Github repo, where I am (slowly) working on codifying the design and eventually impementing it.

Note that I am not soliciting collaborators (though I wouldn't turn one down out of hand, either). I am hoping to get some eyes on the language design and opinions about it, in the hope that I can find places where it isn't clear or where I have ideas which are unlikely to work. At this point, it is still quite some way away from implementation, though I would like to begin working on a sub-set compiler in the new year.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Could you please explain your goal in this a little? We need more context to be able to give a meaningful answer.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

What is happening here is that you are defining the function at the point where you want to be calling it, but you never actually call it. You do refer to the function, on line 14 of the code above, but that is not a function call; without parameters, it simply returns a reference to the function itself. In order to call the function, you need to have an argument list, where to values to be passed to the function are in parentheses, like this:

convert_Fahr2Cel(degree)

This is true even of functions that don't take parameters; those would need an empty argument list, like so: foo(). Without the argument list, you are returning the function, not the function's value.

You have a number of other errors in the code as it is, as well. First off, you generally want to separate the function from where it is being called; the usual practice is to put the functions before the running code, and then have the actual code in a test to make sure that the source file is the one that should be running, like so:

if __name == '__main__':
    # your running code here

What this is doing is checking that this file is being used as a program, and not a module (a source file that is called from another program). Don't worry too much about it yet, it will make sense later when you learn about modules, just know that it is a …

ddanbe commented: Nice. +15
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Ah, I see what you are getting at now. Yes, the DFA does read in the '(' character, which it recongnizes as not being a possible part of an indentifier, so (in most designs like this) it pushes the parenthesis back into the input stream, and changes state to the 'finished' state.

Now, I am talking about this as if the DFA were actually coded as an explicit state machine, but this isn't necessarily the case; there are a few approaches to implementing the lexer's DFA, some explict and some implict. Since you mention 'yytext', I assume you are using LEX or one of its descendants (e.g., flex), so you would be talking about an explicit DFA as opposed to an ad-hoc approach. Still, the lexical analyzer generator does a lot of these things automatically, and so may be obscuring things you are trying to grasp. You may want to look at the StateMachine and CharBuffer classes in my Suntiger Algol project as a comparison, since that uses an explicit DFA that actually is defined in terms of transitions. The code is n Python, but even if you don't kow the language it should be fairly clear.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I would start by writing a data file or database that holds the questions. Each question would have an identifier (a primary key), a difficulty level, a subject, a question, a set of four answers, and a marker indicating which answer is the correct one. I would then write a class or set of functions which can read the questions from the database, order them by difficulty, and select one from each difficulty level at random. Then, assuming that you are playing the current version of the game rather than the 'classic' Regis version, you would want a shuffle function to randomize the order and value of the questions below the 9th difficulty level.

Note that all of this is the part that takes place behind the scenes of the game. It is better to write and test these parts separately from the user interface, to keep the design modular.

At this point you should be able to test how these fit together with a simple text version of the game. Once you have it to the point where you are able to play the game as a text game, replace the text interface with the PyGame interface. At that point, I expect you'll be back here looking for more advice :)

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

There is no need for look-ahead in this case; rather, once the analyzer begins a token that could be an identifier, it continues collecting the token's characters until it finds one that isn't a possible character in an ientifier token (e.g., a whitespace, or some symbol that isn't used in identifiers such as a plus or an ampersand), and once it has the whole token string, it then checks to see if it is a keyword.

With your typical lexical analyzer, the analyzer is written as a Deterministic Finite Automaton, a conceptual 'device' which 'recognizes' a regular language by reading in the symbols of the language one at a time and changing its own state based on the symbols. Each state has a finite number of possible transitions, each of which represents a possible valid input in the regular language of the language. In the case of a lexical analyzer, the 'language' it recognizes is the formal specification of the tokens that the overall language is comprised of.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The main things that jump out at me are:

  • line 4: there is an extra '(' at the end of the line. This was probably a typing error.
  • line 7: you dropped the colon at the end of the line
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

A few pieces of advice:

  • Never use certain letters for variable names, especially l (lowercase 'L') and O (uppercase 'o'). They are too easily misread as the numbers 1 and 0, especially when scanning the code quickly.
  • Using a for: loop and then breaking down the values of the loop into separate conditions (the so-called 'for-case' or 'for-if' anti-pattern) makes no sense; you are better off either finding a way to consolidate the conditions, or else eliminate the loop.
  • When getting the mininmum or maximum of a list, the easiest (if not necessarily the most efficent) way to find the value in question is to sort a copy of the list. In the case of a multi-dimensional list, merge the lists into a single copy first, then sort.

Taking this last piece of advice into account, the solution should be trivial:

t = [[1.0, 2.0, 3.0, 4.0, 5.0],
     [6.0, 7.0, 8.0, 9.0, 0.0],
     [1.1, 2.2, 3.3, 0.1, 0.3]]

def minmax(table, row):
    table[row].sort()
    return table[row][0], table[row][-1]

min, max = minmax(t, 1)

print(min)
print(max)
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The problem here lies in the order you are doing things, and I suspect in a conceptual error that is fairly common among new programmers. When you are declaring and initializing the variable userInput, the values of c1 and c2 have not yet been set, so the values passed to the c'tor aren't valid; it will set real and imag to whatever garbage is in those values. Changing the values of c1 and c2 after the fact won't change this; there is no connection between those variables and the instance variables in the ComplexNumber object once you've created it.

One thing you have to remember is that all variable passing in C is really pass by value; even 'pass by reference' is really just passing the value of the reference or pointer, and has no special compiler support. Once you pass a value to a function - including a constructor - the function is working from a copy of the values passed. If this were not the case, there would be no way to pass a literal, or the result of an expression, without resorting to some complex Pass by Name system involving thunks, which is contrary to how C++ works.

The practical upshot of this is that you will want to move the declaration of userInput to past where the user input is read.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The istream and ostream classes work with chars, rather than wchar_ts, and won't interpret wide chars correctly. However, changing them to work with wchar_t would break a large amount of existing code, so they have to be retained for backwards compatibility. Naturally, the standards commitee wanted to provide a portable solution to this, and to this end, the standard now defines wistream and wostream classes, and mirror objects for the standard input and output: wcin and wcout. To work with wide chars, you will want to use those instead of cin and cout.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Another approach that occurred to me would be to use tuples for the runs:

[(1,4), (2, 2), 3, 4, 5, (3, 3), 11, 12]

def decompress(comptext):
    plaintext = list()
    for c in comptext:
        if isinstance(c, int):
            plaintext.append(c)
        elif isinstance(c, tuple):
            for n in range(c[1]):
                plaintext.append(c[0])
        else:
            pass # TODO: handle the invalid/error case
    return plaintext
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Assuming your goal is Run-Length Encoding, you need to have some way of marking the places where you've applied the encoding, preferably with some character that would never appear in the data stream, or else one that is rarely used. Assuming that your data is always going to be integers, you could choose an arbitrary non-numeric character, such as '\' (backslash, an escape char used in several such encodings). Thus, you would actually encode it something like this:

[1,1,1,1,2,2,3,4,5,3,3,3,11,12]
['\', 1, 4, 2, 2, 3, 5, '\', 3, 3, 11, 12]

Note that with this scheme, you would want to avoid encoding runs of less than three.

Alternately, given the type of data encoded, you could just use the character representations of the numbers themselves, which would save some space and make it feasible to encode all the runs, though this would require additional processing in decoding:

['1',4,'2',2,3,4,5,'3',3,11,12]
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Just to make what pyTony and Vegaseat said perfectly clear: we won't do your homework for you. To quote the DaniWeb Community Rules:

Do provide evidence of having done some work yourself if posting questions from school or work assignments

We are here to help you become a competent programmer, not to hand you an underserved passing grade. Show us what you've done so far, and we'll help you fix it. Ask questions, we'll try to answer them. But just posting the your assignment without so much as an introduction? That's not going to earn anything but our contempt.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

static POD variables are initialized just like all other global POD variables. I posted assembly code to prove it.

In the case you give, where the static variable is initialized to a fixed value, the compiler is indeed initializing the variable at the start of the process; however, given that this is a reasonable optimization which can be shown to have no effect on program behavior, it is possible that the compiler generated the code in this manner for the sake of efficiency rather than strict compliance. The assembly output for the code given by Mike_2000_17, where the static variable is being initialized to a value passed at run time, would be more relevant for this matter. A modified version of that code would make the behavior clearer:

#include <cstdio>

int get_first_value(int value) {
  static int x = value;
  return x;
};

int main() {
  int n;
  printf("Enter a value to test: ");
  scanf("%d", &n);
  printf("%d\n", get_first_value(n));
  printf("%d\n", get_first_value(69));
};

Here, the initializing value will not be known at compile time at all; it would not be possible to have an initialization at the start of the process. And indeed, the program run comes out as follows:

$ ./testd.exe
Enter a value to test: 23
23
23

While I do not have a copy of VS on the system I am on right now, I do have GCC, and the (unoptimized) assembly output for this program comes out as:

    .file   "testd.cpp"
.lcomm …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

If you don't mind me asking, is there a particular reason why you do not want to use an iteration? Is this a class assignment, or just curiosity on your own part?

Also, I assume that this is not a class implementing the standard Java List interface, so we would need more information about the list class you are using. Could you post the code for the class, please?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

AD: I don't believe that Mike_200_17 is disagreeing with you about where static variables are kept, but rather about when and how they are initialized. He is saying that, unlike a globabl variable, which is initialized at the time the process running the program begins, static variables are initialized on the first pass through the function they are local to. The fact that they are global memory doesn't change the fact that the scope of the variable is local to the function, nor does it mean that initialization has to be done at the start of the process. These are the two distinguishing features of function-level static variables, really.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

i have the windows.h include, but the 'L' where is declared?
or i must declare it?

The prepend L is a feature of the C language itself, and is implemented inside the compiler; there is no definition for it. If you think it through, this has to be the case, because the compiler has to be able to interpret the string literal's glyphs as text characters.