raptr_dflo 48 Posting Pro

Thanks shinnoon, we were typing past each other at the same time, sorry for the confusion.

raptr_dflo 48 Posting Pro

OK, let's scrap that last, the attached assignment document provides all that. The question is actually: what should you store in your binary tree?

Restating the problem: for each -English- word (or phrase) found on an input line, insert the corresponding -Latin- word (from the front of the line) into a BST, sorted by English word. If the English word is already in the tree, the Latin word should be appended to a linked list of Latin equivalents.

So you need to revise (a) the definition of a tree_node, to include not only an English-word string, but also a pointer to a linked-list of Latin-word strings, and (b) the insert() method so that it can take a single English word (or phrase) and a single Latin word, and perform the necessary operations. Note that you now also should define a list_node type and a LinkedList class, so that the BST can make use of them.

Once you have that much done, you can implement the part about clearing out the tree and its linked-lists at the end of each Unit.

raptr_dflo 48 Posting Pro

I'm not sure what you're doing with your words struct or why you need a vector<> of them. Or why your only reference to the bst, once you declare it, is to insert an empty (by default) string into it, and then print it back out.

What exactly is the format of the lines in your input? Which word (or words, or whetever string) from each line needs to be sorted? What should the output look like? If you can explain that clearly, you might just find that you now know how to write the code to do it! But if not, we're still here to help.

raptr_dflo 48 Posting Pro

This is for your programming course. The way to get good at coding is to do it. Relax! It's not hard. You've been given the name of the function, and how it will be invoked. The next step is to write the function-prototype which will go up at the top of your program: it takes three arguments, in the correct order (as indicated by the call to it) -- what are the types of each? And it has to return something. What type should it return? Can you do that much?

Then you put the function definition at the bottom: using Taywin's sample as a guide for how to write a function, in general, now have your function do what it needs to do -- the "filling" has also been given to you, between the lines in the first chunk of code marked "These statements compute the monthly payment" ... can you see how the only difference between the first program and the second is that those lines have been replaced with a function call? They still have to go somewhere -- in the function-body. And then don't forget to make sure your function returns the computed value (which should be of the expected type). Assuming you've done the prototype, can you now do this part as well?

raptr_dflo 48 Posting Pro

Also, don't forget the prototype at the top. Taywin's example would look like:

/***** Function prototype goes here ******/
double callMyFunc(int v1, double v2);

Note that the argument names aren't strictly needed in the prototype, so double callMyFunc(int, double); is OK, I just find it much more self-documenting if sensible names are included at that point, so the reader can tell immediately what the -purpose- of each argument is, not just the type.

raptr_dflo 48 Posting Pro

It looks like you're now inputting the flight-path angle from the user after you've read only the first pair of values from the data file. Unless that's what you intended....

Simplify your thinking: the first thing you need to is read all of the data into the arrays. So do that first:

...
ifstream fin("tunnel.dat");
if (fin.fail())
{
    cerr << "Error opening input file." << endl;
    exit(1);
}
 
//Read and input data from file.
for (int k=0; k<17; k++)
{
    fin >> angle[k] >> clift[k];
}
 
//Close file stream.
fin.close();

Once you have that done, then move on to the next step, perhaps asking the user what flight-angle he/she wants to test.

Also, your finterp() code keeps re-calculating f_b, for all N intervals, regardless of whether you matched a given known data-point, returning only the (incorrect) value for the last element. If you can assume that your x[k] are in increasing order, then you need to first determine which interval is the correct one, and then perform the linear interpolation on that interval. Also, since you have N data points, you have only N-1 intervals over which to search, so adjust your for-loop accordingly. Finally, getting back to your initial "inf" problem, what happens if your x-values aren't strictly increasing? If x[k] == x[k+1] for some value of k, you'll have a divide-by-zero error, which will likely cause a result of "inf". Or it may simply have been a weird error resulting from your looping or computations.

raptr_dflo 48 Posting Pro

Since you already have menu code written, it's easy to put it into a function that does (most of) that for you:

// THIS IS NEW CODE (function definition, and open-brace)
void printMenu()
{
// END OF NEW CODE

// THIS IS YOUR CODE (indented)
    cout << "'A' Find if the sum of the two integers entered is even or odd.\n";
    cout << "'B' Finds if the number entered is prime.\n";
    cout << "'C' Finds the sum between two integers.\n";
    cout << "'D' Asks for a year and tells if it is a leap year.\n";
    cout << "'E' Displays the menu.\n";
    cout << "'Q' Quits the program.\n";
// END OF YOUR CODE

// THIS IS NEW CODE (close-brace)
}
// END OF NEW CODE

Feel free to remove the comments, those are just there so you can see what parts are "the function" vs. what you already wrote. I omitted the cin >> ... line because (a) that's not part of printing the menu (it's getting the user's choice, after the menu), and (b) the function is defined void meaning it can't return a value (such as the user's choice). For the first reason, I also omitted the prompt for the user to make one of the choices; it's a bit more of a personal thing, but I see that as being part of getting the user's input, not part of printing the options -- but you can go either way on that.

Then later, instead of the …

raptr_dflo 48 Posting Pro

While compiler error messages are a bit terse, they generally tell you where the compiler found a problem. In this case:

test.cxx:236:24: error: no match for 'operator==' in 'stdRec[mid] == stdIDInput'

says that the error was found at line 236, and possibly column 24. You need to compare the ID member of your record against the input value, the same as you've done in your binary-search code:

if (stdRec[mid].studentID == stdIDInput)

Also, sometimes the error is actually above the specified line (such as a missing ; at the end of the previous line of code, or a missing " or } some other terminator for a pair of enclosing symbols), the line in the error message is merely where the compiler couldn't figure out what to do next.

raptr_dflo 48 Posting Pro

Or simply call print2(h, h); from print(), so that you don't skip the first node....

raptr_dflo 48 Posting Pro

I may be wrong, but I believe "protected" members of a base class are inherited by subclasses, while "private" members are indeed private to the base class, and are -not- inherited (or at least are not accessible) in subclasses.

raptr_dflo 48 Posting Pro

I can guarantee it won't compile, so yeah, pretty wrong. I already told you that your professor typo'd the opening curly-brace as a closing one, and his notation of Reader (1)" etc., isn't valid C, C++ or any other language I can clearly recall, it's presumably "pseudocode" designed to illustrate the basic functionality of each object, rather than to be a valid implementation in any specific language.

If you don't understand the basic concept of a C++ class (or C struct, or Pascal whatever-it-was-called-in-Pascal) as a data type, which you can then create individual instances of -- in this case, say, a Reader which incorporates whatever internal data and functionality which defines how a Reader should behave, and then separately 5 reader-instances -- then I really don't think there's a better alternative than backing up, getting yourself an introductory-level programming text, and starting from the beginning. It will take you a little while to catch back up to what you're trying to do now, but it will ultimately be far less time-consuming and frustrating than trying to understand all of it in one go, with deadlines flying past.

I'm really sorry that you "placed out of" an introductory C++ programming class which you clearly needed to take before this one, but it's as much your fault for thinking you didn't need it as it is the school's fault for allowing it.

I could keep telling you what you need to do at each step, but unfortunately, you're …

raptr_dflo 48 Posting Pro

So how would I start this in c++?

By starting it.

class Reader {
    // reader-stuff goes here
};

class Writer {
    // writer-stuff goes here
};

int main(int argc, char *argv[])
{
    vec<Reader> readers(5);
    vec<Writer> writers(3);

    // code to demonstrate whatever the assignment asks you to demonstrate
}
raptr_dflo 48 Posting Pro

The count of items in your array is not dependent on the type, plus, you should be keeping track of how many items you've read in (so use "length - 1" rather than "NUMRECS" -- you might allocate more records than you actually fill, you don't want to search the empty ones).

As far as outputting your record, you already have code that does that at lines 75 and 96 of your original posting back on "Page 1" of this thread:

cout << setw(12) << stdRec[i].studentID
     << setw(21) << stdRec[i].studentName
     << setw(13) << stdRec[i].courseCode
     << setw(5) << stdRec[i].creditPoint << endl;

just replacing [i] with [mid] .

Don't forget, binary search through your stdRec array will only work if it's already sorted in increasing order of studentID string. Options include:
+ keep your list sorted at all times
+ make sure your list gets sorted before searching
+ go back to a straight linear search through your potentially-unsorted list

Unless your assignment specifically indicates otherwise -- or if you've covered sorting in your course, then presumably you should know to incorporate that concept in your work -- any of the above should be acceptable.

raptr_dflo 48 Posting Pro

Take a look at libcurl. There are probably other options as well, but this one is well understood by enough people that you can probably get input from multiple sources here.

The basic premise is to write a program which, as far as the website is concerned, acts like a browser: make a request for the contents of the web-page, go back and ask for any resources you need (e.g. included javascript sources), and so on until you have all the information you need. Somewhere in there you'll be able to determine what is being sent back to the server when the user clicks whatever you're interested in, and you can send that same message yourself. You can also present the same (or similar) browser view to your user, if that's relevant, using a GUI toolkit of your choice (including something as advanced as Qt Webkit, which provides full web-browser fucntionality) or you can automate the entire process if all you want to do is simulate having a user click on something, but don't actually need to involve your user at all.

Since you would presumably be doing something other than image-processing / character-recognition, consider ending this thread and starting a new one with your own code once you've got something started.

raptr_dflo 48 Posting Pro

Yes it can be done. No, it probably isn't worth the effort to do image-based character recognition. You'd be better off trying to scrape the source of the web-page and find the current value of the timer display string in it. It would be more computationally efficient, and less error-prone. Also, instead of then clicking on something in the web page, you could just generate the same HTTP POST request back to the server that would be generated by performing the click.

raptr_dflo 48 Posting Pro

Oh, and there's more to do for the case of bouncing near a corner of the screen, you need to determine which wall you hit first, and bounce off that one, then immediately check against the other one, because you may need to bounce your new point to a -new- new point! :)

raptr_dflo 48 Posting Pro

On collisions, gotcha, sorry for the confusion.

I won't go into detail here, but there are very fundamental issues in signal processing (specifically taking discrete samples of a continuous function) which require that your dot not be moving too fast relative to your pixel-density and your frame rate -- the same issue is what makes wagon-wheels look they're going backwards in old films -- look up "Nyquist" on wikipedia if you want to understand more).

As long as you control the speed of your dot, and it isn't huge compared to the amount of space it's supposed to be moving around in, then the exact details you use to detect collisions and update its position and direction aren't hugely important. A really good basic algorithm can handle an arbitrary velocity (speed and direction, again, as long as it isn't going -too- fast) for the dot as long as the objects are nicely aligned rectangles. You can actually draw it out on graph paper.

The starting position of the dot is at (px,py), and it has a velocity of (vx,vy). Regardless of the immediate frame-rate, the next position will be at (px + dt*vx, py + dt*vy), where dt is the amount of time that has passed since the last frame (initialize to zero for the first frame). If the new position corresponds to a collision with a wall (or other object), you need to know which wall (or which side of the object) you collided with, so …

raptr_dflo 48 Posting Pro

OK, I read the sample "code" from your instructor, and it looks like p() is intended to "lock" a resource, and v() is intended to "release" a resource. In this case the resources are (a) a single shared "mutex" object, which makes sure that only one object (a reader or a writer) can operate while it holds the mutex, and all others requesting to lock it will be blocked until whoever holds the lock releases it again; and (b) a "wrt" object which will be held by any writer (locking out any other writers), or by the first reader that requests it (released by the last active reader). The "wrt" isn't strictly a "mutex" since those are typically locked and released by the same object/process.

If you understand the logic presented by your course, coding up the Reader and Writer classes should be as simple as writing the functions/methods p() and v().

The "work" performed by a writer would go at line 4 above (between the calls to p() and v()), and for a reader at lines 15 or 28.

raptr_dflo 48 Posting Pro

As far as the command-line, the only argument your program looks for is the "count", and it doesn't check whether the argument is actually -on- the command-line. That might be where the "Unable to start program" error comes from -- if there's no command-line argument, argc will be 1, and argv will be an array with one element: ["yourProgramName.exe"], attempting to access argv[1] will probably result in an error.

As far as a file, you either need to "pipe" the contents of the file into your program (so you can use cin):

linux$ cat input_file.txt | myProgramName
windows> type input_file.txt | myProgramName.exe

or modify your program to hardcode the filename (or prompt the user to enter it) and then open a new file-object:

string filename("input_file.txt");
ifstream infile(filename.c_str());
...
c = infile.get();

As far as using the count variable, go back to your code and read out loud what it does. It should be evident that, while you haven't exhausted the input, you're generating a new random number (between 0 and 25, inclusive), count times in a row, and not using any of them, and then reading three characters and outputting the third. Since this is presumably not what you mean to be doing, say out loud (and write down on paper) what you -do- want to do, and then write code that matches what you've written. I'll get you started:

Get the number, count, of null-characters to skip each time (zero -> output all characters).
While …
raptr_dflo 48 Posting Pro

Depends on what the p() and v() functions are supposed to do, it's been a while since I had to study the theory of resource contention with producers and consumers.

At the very minimum the "}" near the starts of "functions" need to be switched to "{", and the readers and writers shouldn't really be functions anyway, they should be instances of a Reader class and a Writer class, respectively, and the program can call the doMyThing (or whatever you want to call it) method for each instance in the order necessary to demonstrate the conditions specified in the assignment.

C++ isn't frightening. Not knowing what you're doing can be, but as a previous responder wondered, how did you manage to get to a relatively high-level computer science course with such limited programming knowledge? Should you be in a lower-level course? Or did you get through the lower-level courses mostly on luck and maybe getting others to do your programming for you? No offense intended, I'm just curious why you're in this predicament, understanding it might help us help you.

raptr_dflo 48 Posting Pro

Nope, we don't "make it for you" here on DaniWeb. You don't learn anything that way, and the point is to help you learn to be a programmer. I know you're new here, and thanks for the apology, but try it yourself. How many spaces do you need to start with? Then how many '*' do you need to print? Then how many more spaces? Etc.

raptr_dflo 48 Posting Pro

Here's something to start:

class Object {
public:
    // "normally" these would be private or protected, and accessed or modified through methods, but it's fine for now
    int int_val;
    std::string  str_val;
    Object2 some_other_kind_of_obj;
public:
    void print(void);
}

void Object::print(void) {
    cout << "int_val = " << int_val << endl;
    cout << "str_val = " << '"' << str_val << '"' << endl;
    cout << "obj = {" << some_other_kind_of_obj << "}" << endl;
}

Note that Object2 would have to overload the << operator for this to work, but if you stick to simple pre-defined types for your various members, then it should work just fine as-is. We can get fancier later.

raptr_dflo 48 Posting Pro

If you haven't already figured it out, &regItem produces the same pointer (address of the regItem object in [virtual] memory) each time you use it, so you may be filling your list with identical pointers, whose values then will be whatever you most recently assigned into regItem.

Instead you should dynamically allocate regItems as you need them, and dereference them to input the data (and output whatever you need to output):

RegItemSpecificType *regItem = new RegItemSpecificType;
file >> *regItem;
alist.insert(regItem);
...
cout >> *alist_iter >> endl;
raptr_dflo 48 Posting Pro

Why are you looping over the number-of-trains, inside your loop to input Trains structs, at line 65? And without an opening "{" (and closing "}" some time later), the only line that will be looped-over is the prompt for the first intermediate station name.

I suspect that in adding the additonal struct, you may have misinterpreted the assignment. If there is only one track, then the station-names need to be provided in only one place. And the only values that need to be maintained on a per-train basis are the arrival and departure times from the origin, intermediate stations, and destination.

If you think about what information you need to maintain, then the data structures to help you organize that information may be more obvious, along with the coding necessary to input and display the information.

raptr_dflo 48 Posting Pro

Hi Stevo,

I haven't read the accompanying .doc, but I assume since your create() method initializes all values to zero, then the add_*() methods are intended to add to your stores of raw materials, while your make_pizza() method should take the type of pizza to be made and the number of that type of pizza, and use that information to add to the number of that type of pizza in your class, and subtract from the amount of raw materials, based on how much of each ingredient is needed to make each type of pizza.

For example, if a cheese pizza is of type 'c' and requires one pound of flour and one pound of cheese, then a call to make_pizza('c', 5) should increase the number of cheese pizzas by 5, and decrease the amount of flour and cheese available by 5 pounds each -- assuming there's enough flour and cheese to make that many pizzas, otherwise your assignment probably tells you what to do: print an error message, and possibly make as many of the pizzas as you can with what you have available.

Your "confusion" stems mostly from panic. You've had difficulty understanding the material presented, and have waited until your assignments are overdue and exams are imminent to seek help.

I'm happy to tutor you a bit offline, but more people can learn from your progress (and other more-advanced programmers can contribute input) if you routinely post your current code and specific questions …

raptr_dflo 48 Posting Pro

The definition of the IEEE double-precision format is eight bytes (MSB to LSB):

seee eeee   eeee emmm   mmmm mmmm   ...   mmmm mmmm

where s is a sign bit (1 is negative, 0 is positive), e is a 12-bit signed integer exponent (ranging from -2048 to 2047), and m is the remaining 51 bits, the fractional mantissa following an implicit "1.", so that the final value is

(1 - 2*s) * 1.m * (2^(e-2048))

Some values are necessarily reserved to indicate overflow, underflow, +/- infinity, and the always hilarious magical NaN constant (which has a tendency to flourish in unchecked linear algebra code :) ).

But the bottom line is, including the leading 1, you can store only 52 significant binary digits, and at ~10 bits to represent a trio of decimal digits, that comes to a little over 15 decimal digits that can be meaningfully represented in the decimal +- N.NNNNN * 10^e notation.

If you need more precision than a double provides, then you will need to use (or create, if you're bored) a higher-precision math library. I believe there are options for arbitrary precision (at the cost of storage and computation). Wikipedia provides a large list of options, maybe something will fit your needs (if other than idle curiosity).

Enjoy!

raptr_dflo 48 Posting Pro

The best way to really -learn- a programming language is (as thines01 said) to think of something you want to program, and then program it. The exercises at the end of each chapter of a book may seem lame, but they're designed to reinforce the concepts introduced in that chapter. Do them! If they're too boring, at least try to do a couple of the hardest-sounding ones before proceeding to the next chapter. And you can probably skip the exercises from the first couple of chapters entirely, and just refer back to the relevant sections as needed when you start a more interesting exercise later on.

A warning, however: from participating in the DaniWeb forums for a few months now, I'd say a recurring problem is relative beginners embarking on seriously hard projects -- a fully-generalized equation-solver comes to mind: one poster wanted the user to be able to enter things like "5 + n * 2 = 9" (with whitespace optional except where needed to avoid ambiguity, possibly including parentheses, and so on), and have his program correctly determine which symbols were operators, which were constants and which were variables, and then solve for a variable in terms of the constants (and other variables, if any). It doesn't sound so impossible until you think of it in terms of writing an interpreter for a relatively simple "computer-language" of mathematical expressions. I haven't had much need for writing my own computer-languages in the past 25+ years of academic and …

raptr_dflo 48 Posting Pro

Where is cin declared and initialized?

std::cin is an instance of istream, and is declared and initialized in the included <iostream> header.

raptr_dflo 48 Posting Pro

Welcome dkXIII,

First of all, when posting code, please put [ CODE ] tags around it. Simply select the code you've pasted into your message, and click the [ CODE ] icon/button at the top of the editor. And read the "Read Me: Read This Before Posting A Question" sticky-thread at the top of the forum.

Now then, you get count from the command-line, what is that value supposed to represent? A count of what? Maybe it should be named something more informative....

You assign c a random value (which you never use), and declare a char variable b (which you also never use). And it looks like you've messed up the nesting of your for() and do-while() loops (though that might have been a copy-and-paste error, if your code has already compiled).

Slow down and think about each step of your program. Make sure it does things in a logical progression. Start with big "things", and then break each "thing" into smaller "things", and repeat, until each "thing" corresponds to a relatively simple line of code. :)

raptr_dflo 48 Posting Pro

Awesome! Please mark your thread as "solved" for us. Happy coding!

raptr_dflo 48 Posting Pro

Another thought on IsHappy(), while your code works fine (for r), the approach is brute-force, and becomes increasingly ugly for larger strings. What if you wanted to know if an 8-digit number is happy? What about text (say a "word") of near-arbitrary length? (Hint: have you learned about arrays yet?)

raptr_dflo 48 Posting Pro

Your code tests only the first number for happiness. Consider putting your happy-determining code in a function called IsHappy(), which you can separately call for r and q (assigning the values to bool variables r_happy and q_happy, respectively).

You can't have any 0 digits because you specifically disallow them in your tests of num1 through num4. If you want to allow them, fix your comparisons so that 0 is a valid value. Also if you check ahead of time that q and r are >= 0, then you don't have to check whether each digit is negative. N % 10 will always be in the range [0,9] for non-negative N. For fun, just tested negative values of N. My C++ compiler (g++ for MinGW) gives -523 % 10 = -3, while ActivePython 2.6.4 gives -523 % 10 = 7. :)

raptr_dflo 48 Posting Pro

Following up to mzimmers,

... or your WrongSize() function is mis-named. While it might function completely correctly, it isn't very readable to have WrongSize() return true when the data is the RightSize and false when it's not.

In addition, your logic at lines 33-34 is incorrect. You need a different comparison(s) of answers[count] to determine that the answers are invalid, and you want to output that message only once (not for each invalid character encountered). Since the assignment calls for functional decomposition, consider writing functions called ValidAnswers() and NumberOfCorrectAnswers(). You'll find the program almost writes itself, if you think about the logical breakdown of steps, and in what order to perform those steps.

Cheers, and welcome to DaniWeb!

raptr_dflo 48 Posting Pro

Please use the [ CODE ] icon-button at the top of the editor to format both your code and your triangles, so we can better see what it is you're doing so far, and what you're trying to accomplish.

As far as making 2 triangles at once, think about what has to happen on each line, since you clearly can't back up (without using a much more advanced SDK like "curses").

And as far as using while() rather than for(), can you modify your existing code to make a single triangle using while() loops instead of for() loops? They are completely interchangeable. Since the for() loop syntax is effectively: for ( initialization ; test ; adjustment ) { do stuff; } where would you put each of those four italicized pieces relative to a while() loop?

raptr_dflo 48 Posting Pro

A readability point about your code so far:
You are allowed to use variables longer than 1 or 2 characters. From "The Tao of Programming" (a small comedic book, not immediately at hand, so I can't cite the author, and am quoting from memory), "Though your program be but three lines long, it will eventually need to be maintained." I would recommend variable names like p_digit, p_digit_val, p_remaining_val, (and same for q), bulls and cows.

As far as making sure the inputs are "happy numbers", think about what the statement requires. Can you think of a way to keep track of which digits you've seen so far? If you had a variable called times_digit_has_been_seen (though you can shorten it a bit), what type would make that variable? How would you give it a value (or values)? How would you check it later to determine whether the input number is ok?

While we're on the subject of error-checking user input (which is ALWAYS a good idea), what happens if the user enters a short number like 17? What happens if they enter a long number like 32768?

Doing great!

raptr_dflo 48 Posting Pro

Yes, for P2 you need to input two values, P and Q. And since they're going to be 4-digit numbers (regardless of how you choose to represent them in your program), I think a for() loop is the more-readable way to program the solution.

int digit;
for (digit = 0; digit < 4; digit++) {
   ...
}
raptr_dflo 48 Posting Pro

Hi inner circle, welcome to DaniWeb.

I don't know who Dr. Azalov is, your course instructor perhaps? What part would he disapprove of? Or did you mean the general "asking for help online" part? I'm not going to do your assignment for you, nor (with any luck) is anyone else on this forum. We're here to help you build and improve your programming skills, and lend some pointers and insight on more obscure aspects if we can.

If your course instructor has specifically said you should work out your assignments on your own, then it's up to you to do so. It's not my job to know who's in which class, and what their various restrictions might be. But since I'm still not going to hand over a completed working program, I don't believe it should be a problem.

Now if you need help, you should follow the same procedures as everyone else. Start writing your program, and get as far as you can on your own, then post your code here with specific questions on the parts you can't get working. And read "Read Me: Read This Before Posting A Question" (the clearly-marked sticky-post at the top of the forum).

raptr_dflo 48 Posting Pro

And in getRecords(), you're passing a pointer to a struct, so you need to use the -> operator to access its methods, e.g:

acc->balance = 1000;

Or you can pass the struct "by reference", in which case you need to change your parameter declaration (in the prototype and the implementation of the method):

int FileHandler :: getRecords(struct status &acc)

(notice the '&' instead of the '*'). And then you can continue to use the .-operator as you are now.

raptr_dflo 48 Posting Pro

Hi TheFearful,

Nothing to be afraid of here, except maybe frogboy's sarcasm. :)

In the first problem, since you don't actually need to perform any math on the input numbers, they don't need to be integers. You could play the same game, called "happy words" on 4-letter words: "HEAD" is a happy word, "FOOT" is not. Yes you need a loop, and iterating over the character positions in a string is much more obvious than extracting decimal digits from an integer. Does that help?

What is your question regarding the second problem? Actually, I know what the question is already, I can read minds: "why does my estimate suck?" The problem is you've collapsed the need for two loops into one. Simplify your logic by creating a function called estimateCubeRoot() which takes your "a" as an argument and returns your computed estimate of a^(1/3). That function needs a loop inside it which keeps revising the estimate until the difference between successive values is small enough. Then you still need a loop in your main() which provides successive values of a, and prints a, the estimated cube-root returned from your function, and the value computed by the pow() function.

Keep it simple, make functions that do simple logically-grouped things, call those functions when you need them to perform their tasks. This is the first part of "modular programming". In C++, the next part is to create groupings of functions and data into "classes". And related functions into …

raptr_dflo 48 Posting Pro

You've got the basic idea of binary search: it's the optimal strategy for the "I'm thinking of a number between 1 and 100, try to figure it out" game. You start with 50, and the other person tells you higher or lower. If he says lower, you guess 25 next, otherwise 75, always keeping track of the new range of values, approximately half the size of the previous range (thus the term "binary", dividing the search space into two equal segments).

Now, it only works if your data is sorted (like the numbers 1 to 100)!

But even strings (representing integers) can be correctly sorted, if they're guaranteed to be a constant length. Otherwise you end up with problems like "1000" comes before "123", the same way that "celebration" comes before "cent".

To do a binary search, you start with the start-of-range index at the beginning of your array, and the end-of-range index at the end of your array. Compute the index half way in between, and see if that element is the correct one. If so, you're done. Otherwise, if the record you're looking for should be before that, then the half-way index (minus one, no point looking at it again) becomes the new end-of-range. Or if the record you're looking for should be after that, then the half-way index (plus one, this time) becomes the new start-of-range. Don't forget to handle the case where the record you're looking for isn't in the set at all. …

raptr_dflo 48 Posting Pro

Hi Nimerion,
Your original problem was:

The problem is that I don't know how to take the elements and convert them into an integer.

I assume you have a text-file with a bunch of integers in it. Is the problem that you don't know how to read the strings out of the text-file? Or that you don't know how to convert each string into an integer so you can easily compare and sort them? Or am I -also- not understanding the details of the problem.

It is reasonably clear that English isn't your primary language. Unfortunately it -is- the primary language used for communicating on this forum. Telling any of us (let alone Narue, with over 11000 posts in this forum since 2004) that we don't understand you ... that isn't helping. Obviously we don't understand you. But that doesn't make us or you stupid. Instead, try again to clarify what you're talking about. Maybe with a small example of the file or files in question. And definitely post the code you've written so far, along with specific questions about how to fix errors or implement additional features.

Also, don't forget to enclose your code in [ CODE ] tags. Select it all with the mouse, and click the [ CODE ] icon at the top of the editor. See how all that does is put "[ CODE ]" in front of your code, and "[ /CODE ]" after it (without the embedded spaces). You could just …

raptr_dflo 48 Posting Pro

There's still the possibility of needing a fuzzy-match. There is no guarantee that your browser's renderer displays the source image pixel-by-pixel perfectly each time.

If it did, it would be sufficient to do something like:

int checkImgI = -1, checkImgJ = -1;
for (int i = 0; i < screenHeight - checkImgHeight; i++)
    for (int j = 0;  j < screenWidth - checkImgWidth; j++)
        if (ImageStartsAt(checkImg, i, j)) {
            checkImgI = i;
            checkImgJ = j;
            break;
        }

where ImageStartsAt() then iterates over each pixel in checkImg and checks whether the underlying pixel in the screen is the same.

If the pixels aren't necessarily equal, you'll need to modify ImageStartsAt() to return some kind of "difference" metric, and assume if you find a sufficiently small difference, then you've probably found some version of the image.

If the browser is allowed to scale the image, based on some kind of user preference and the way the embedding web-page is written (such as on the iPhone, for example, where you can interactively zoom a web-page), you're going to have increasingly bigger problems.

Good luck!

raptr_dflo 48 Posting Pro

At line 11, you assign q->next equal to p->next, but p isn't defined. I suspect that what this function is -supposed- to do is append the len new nodes to the end of the list, so you need to initialize p by stepping through the list, starting at ptr, until p->next is NULL.

raptr_dflo 48 Posting Pro

First of all, don't do this:

for (int i = 0; i < num; i++)
    degreeTable[i]=NULL;

You've already allocated degreeTable to be an array of F_HeapNode instances, meaning that degreeTable is a F_HeapNode instance rather than a pointer to something. If you want an array of pointers, then specify

F_HeapNode ** degreeTable = new F_HeapNode* [num];

but you're better off in C++-land using one of the STL container classes, such as

vector<F_HeapNode> degreeTable(num);

which pre-allocates and fills degreeTable with num default instances of F_HeapNode.

If you are maintaining instances rather than pointers-to-instances (they are distinct in C++, as compared to Java where everything is really a pointer -- or else nothing is, depending on who you ask), then in order to assign a new instance into your container, you need to overload an assignment operator for your class:

F_HeapNode & F_HeapNode::operator=(const F_HeapNode &other)
{
    member1 = other.member1;
    ...
    // any other initialization that makes this instance a copy of the one you're assigning from
    return *this;
}

Then whether you use an array or a std::vector, the assignment above should still work. cplusplus.com is a great reference, including code snippets for almost everything you'd want to do.

raptr_dflo 48 Posting Pro

Excellent. So what's next?
(and welcome to DaniWeb!)

raptr_dflo 48 Posting Pro

How have you drawn your basic face? With code, on the computer? With charcoal on paper?

What does it mean to "merge the template with a real human face"?

Once you can more clearly state what your program needs to do, it will be more clear how to start writing it.

raptr_dflo 48 Posting Pro

Welcome mikkey91!

Strings and arrays will both work. Learning how to decide up-front which way to go is something you learn only with plenty of experience. For now, pick whatever you're comfortable with, and figure out how to implement what you need. If you have time, go back and implement it a different way also, just for the experience.

This encryption topic shows up in the DaniWeb forums every couple of months, so it's clearly a favorite assignment. If you go back through this C++ forum, you'll definitely find related threads. Especially if you mention Vigenere, like I just did, you'll probably find relevant threads listed on the right-hand side of the web-page. ;)

As far as how to start, just think through what the program has to do, and in what order, then add details a little at a time. Start with asking the user for the encryption key, and printing that back out. Then use it to encrypt a hard-coded string and print out the original and encrypted strings to verify that it has done the encryption correctly. And so on. In no time you'll have the entire assignment completed. Good luck and post back (including your code so far) if you have more questions!

raptr_dflo 48 Posting Pro

The algorithm is already divide-and-conquer recursive, so O(nlogn) in execution time. (And technically yes, O(logn) in execution stack-size to handle the recursion, but that's still fairly trivial.)

Never mind, I took another look and realized what you're talking about. The OP picked a worst-case reverse-ordering, so it keeps partitioning all N-1 elements besides the partition-element into a single partition, and that does end up being O(n^2). Sorry!

raptr_dflo 48 Posting Pro

Always good to address the first error first. Since I don't see anything obvious wrong at line 14 of filemgr.h, try removing the international character-set comment above it, and see if that fixes the one problem.

The rest of the errors are very likely a result of the problems around lines 14-15.

We've already discussed the warning from profiler.h, you can get rid of it easily enough, but it's also probably safe to ignore unless you expect those counter variables to get -very- far apart.

If so, there may be a way to tell Visual Studio what language(s) to accept in source-code files.

raptr_dflo 48 Posting Pro

Awesome! Please mark your thread as "solved". :)