rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

Think out the algorithm first. You want to remove the lowest and highest values, so first read all values into an array, determining the high/low values as you go and adding up the number of items read. When you are done, iterate through the array, adding up all but the high/low numbers and divide the resulting value by the number read (-2) to get your olympic average. From what I can see, you aren't doing that...

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

... But do you think it would be possible to use openAL or FMOD EX to load into a buffer in which I can edit the samples?

Sorry, but although I am a proficient C++ programming, audio systems (other than as a musician/user) is not my domain, so I really can't answer that. The main thing about audio processing is that it is an A/D (analog/digital) signal processing problem for the most part - not an area of expertise that I am comfortable with. My work has been mostly with distributed networked systems and discrete machine controls. I understand the theory of audio (and analog) processing pretty well, but I am not a practitioner in that area. Sorry that I can't be more helpful to you.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

This is NOT simple stuff! First, C++ is NOT a scripting language. It is a fairly low-level system programming language with a lot of nuances - the devil being in the details. Second, audio programming like what you say you want to do, is not a simple proposition. My advice? Download the source to an open source audio processing program, such as Audacity, and study the code. From that, you can learn a great deal that will help you achieve your goal, which is in my mind, laudable (if not audible - sic!). Good luck! :-) Anyway, here is a link to Audacity: http://audacity.sourceforge.net/?lang=en

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

One of the primary purposes of homework assignments is to get the student to think for themselves, and develop problem-solving skills. When you get into the workplace, you won't have the luxury of asking others to do your work for you... Ok, I lied. There are plenty of manipulative people who do exactly that (they are called managers), but they get no respect from those who do the real work.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

What do you mean? The term "flag" can have many meanings, so your question is just too general to answer without writing a thesis on the term... :-(

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

When you post C++ code like this, also post the class header. Without it, we are flying blind, so to speak. Also, explain what your Heap class is supposed to be doing - what it's purpose is, as clearly as possible. If we know your intention, we can better advise you.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

I think the OP is into it and has good initiative. I just know from personal experience that jumping into Windows programming can take a lot longer than one originally intended.

@rubberman I think your suggestion of a ready made is a good one. If any of them are open source, that's an even better opportunity for the OP.

I didn't look to see if any were (probably some). I just looked enough to see that there were a large number of seemingly reasonable prospects. It would be easy enough to refine the search to open source candidates to start from.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

You might also want to google the web for an already-built flash card application if you aren't into programming it yourself. This google query, "flashcard application download", results in a large number of what seem to be relevant hits.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

Absolutely. If you are going to use it anywhere at all, even in other parts of your code, you need to do that, otherwise it will just get repeated (probably incorrectly) all over the place. A header file is saying "These are the interfaces to useful stuff. If you use them, here are the calling conventions.".

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

Please provide full definition (.h file) for the BinaryTree<T> class.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

Have you made the operator >> a friend of the Matrix class? If you don't, it can't get access to the internal parts of Matrix, assuming they are (properly) private or protected. Also, have you determined that the format of the input data is compatible/parseable with the method by which you are reading it?

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

You have made a start on defining the problem. Work it out in pseudo-code (describe in plain language the data and processes you need to transform that data to get the results you need), and analyze that until you are clear on what you want to do. At that point, you are ready to start coding - creating classes to model the data, and their behavior to reflect the data transformations you have determined are necessary to solve your problem.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

Please don't ask us to solve your homework problems. :-( We will help you find a path that will work for you, but you need to try to solve the problem first, and then ask for comments or corrections.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

I didn't understand the most of that link, but kudos on a huge rant.

That wasn't a rant! That was a "discussion"! :-) :lol:

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

@rubberman, I certainly meant no disrespect and I have no problem with mixed C/C++ programming (especially when done by professionals). I just like to point out to those who are learning (the OP) the pure C++ techniques and functions because I think that in the long run it's better to get used to STL style programming as early as possible, but that's just my (not so) humble opinion. On a final note, I hope, for your sake, that you are not suffering from the C-hacker syndrome, you know that the first step to recovery is admission (a few red flags from your post: "C-style functional programming is just cleaner", "a lot (I think) easier to use", "using what makes the most sense to me", etc. these are not rational nor objective arguments, no offense, but they do sound an awful lot like they come from a C-hacker).

No offence taken Mike. Most of my colleagues would tell you that I am as hard-core a C++ engineer as there is. But as an engineer (I am a director of an IEEE network) I prefer to use the best/most appropriate tool for the job at hand. In any case, everyone uses those tools they are most comfortable with, and a lot of this stuff, algorithmic templates and such, are pretty recent in development. Not to say that they aren't good tools, or that one should discourage their use (I sure won't do that) if one isn't that familiar with them. …

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

Windows does not support POSIX threads (pthreads), if I correctly remember my multi-thread assignments at the unversity.

The "standard" Windows API's don't support POSIX threads and most other POSIX API's, but they are available for VC++, and I have used them extensively in the past for cross-platform development. Unfortunately, the biggest problem is that VC++ is not particularly standards compliant. For ANSI/ISO C++ standards compliance, the GNU compiler suite is still amongst the best. There are proprietary compilers from Intel and others that are as good, or possibly better, but they are quite costly and don't run on all available platforms, unlike GNU.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

@rubberman: Even better, using the C++ function for sorting: std::sort from #include <algorithm>.

I thought about mentioning that, std::sort as well, but the advantage with qsort() is that it also works for C programs, and for a simple array that was the case here, a lot (I think) easier to use, and understand. Anyway, it is a good point for pure C++ programs. Myself, starting with early C++ compilers (pre std-c++ days without templates and such) in the late 80's and early 90's, is that I tend to do more mixed-mode programming, using what makes the most sense to me, illustrating my intention in the code, and is the simplest and easiest to understand (sticking to the KISS principal). I love classes and generics (template classes), but there are times when C-style functional programming is just cleaner. Nothing but my (not so) humble opinion, and others may well disagree with me there, but I can still respect that.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

What system and compiler are you using? On Linux/Unix, there is a man page that gives details. Also, are you using pthreads (POSIX threads), or other threading API's?

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

Myself, I'd just quicksort it with qsort() and be done with it. Unless you are supposed to implement a sorting routine for a class exercise, it almost never pays to implement something for which there is really good standard functions for.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

I am running Scientific Linux 6 (a clone of RHEL 6) for the past several months, after 3 years running CentOS 5 (close of RHEL 5). I've been happy with both, and both have some minor issues, stability not being one of those issues. Mostly they deal with changes in the desktop managers (KDE and Gnome). I run Windows in a virtual machine (using VirtualBox) which does support Windows 7, so if you want to run Win7 under Linux, you can easily enough. As for known problems with Win7 SP1, I don't know since as I mentioned before I don't run Win7. I have a couple of clients that run Win7, and they much prefer it to Vista, but that's not saying much.

peter_budo commented: Read carefully before replying -3
rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

Ok.

1. Write the code to an external .cpp file.
2. Use the system("TCXX progname.cpp") function, where "TCXX" is the name of the Turbo C++ compiler. Assuming it succeeds in compiling, go to #3.
3. Use the system() command to execute the program as in system("progname arglist") where arglist is the list of arguments to pass to the program.

This is just a general road map. Remember, the Devil's in the details... :-)

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster
rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

Well, C and C++ are infix expression languages, so you need to read the postfix input, convert it to an evaluation tree, and then process the tree. I've done this before (about 25 years ago), but it isn't particularly simple. A good text on the subject is Donald Knuth's seminal book, "The Art of Computer Programming, Volume 1, Fundamental Algorithms". He goes into this in detail. If you are a serious computer programming student, his 3 (now 4 or 5 - he just released another volume or two after 40 something years) volume set is something that should have a prominent place on your book shelf. I've had my set for 30 years now, and I still refer to it from time to time.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

I see mike_2000_17 and I are saying just about the same thing, in different words... :-)

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

Well, that should work. I think your comment about sortScores() being hinky (the correct technical term) is probably correct. However, it would be better just to treat scores as an array. Ie,

double avg(double *scores, int numScores)
{
	double total = 0.0;
	double average;
	sortScores(scores, numScores);
 
	for(int count = 0; count < numScores; count++)
	{
		total += scores[count];
	}
        average = total / numScores;
 
	return average;
}
rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

What is it that you are trying to do? The question has a number of answers, dependent upon your goals.

1. If you want to take C++ code, compile it, and access/run it inside an already running code that is one thing.
2. If you want to take C++ code, compile it, and run it separately, that is something else entirely.

In the case of #1, that is very difficult (not necessarily impossible). In the case of #2, that is not difficult. Let us know more of what you are trying to do, and maybe we can point you in the right direction. "Give a person a fish, and they will eat for a day. Teach a person to fish, and they will never go hungry."

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

Ok. Now it is becoming clear! You have a project to determine prime numbers up to 64-bits in size. That is clearer. Start with a sieve of eratosthenes to build a reasonable size array of about 10,000 elements. On todays computers that's a few nano seconds. Then you develop a recursive function that does a binary search of the potential answer domain, after all a number can only be factored by another number 1/2 its size or less. Determination of a prime is basically looking for numbers that have no factors greater than 1. Since this is probably a school problem, I won't go into it further except to say that I wrote such a program/function originally over 25 years ago which ran on an old IBM PC (Compaq Plus, actually), which was a 4.77MHz processor with only 512KB of RAM, and it could determine if a 64-bit number was prime in less time than it took to get my finger off of the Enter key. :-) In any case, with a base sieve of 10,000 elements you can find the answer with 5 or less searches (recursive function calls). FWIW, if you build a sieve array of 1,000,000 entries, then your recursion depth is 3 or less. I'm not sure if that would be faster or not, but I suspect not. My analysis 25 years ago was that 10,000 entries was a good trade-off of space vs. time.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

Please clarify what you mean. Are you talking about numeric data of 2^64, or data set sizes up to 2^64 bytes? If the first, you either need to use 64-bit data types (assuming these are unsigned integer values), which in modern C/C++ is an "unsigned long long" data type; however, even that can only represent a number up to 2^64 - 1 in size, and you can't do any addition or multiplication with it without overflowing the variable. If that is what you want, then you need a specialized numeric library that can manage unbounded values... In the second case (data set size), that is simply impractical - 2^64 bytes is something like (I think) 16 exabyes, which would be about 16 million 1TB discs... So I don't think that's what you mean either.

So, let's go back to the most likely scenario (trying to read your mind) - you want to perform calculations on numbers up to 2^64 (more or less). Use unsigned long long variables. Modern compilers and systems can deal with that just fine. If you need to do floating point calculations, some compilers also handle a long double type, which is 128 bits and can handle very large calculations. A regular double type is only 64-bits which when you factor in the exponent part, can't handle numbers up to 2^64.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

My advice is to throw the book away. Programming should start with basic data types (integers, floating point, characters, arrays, pointers), and then move into basic control structures (if/else, for/next, do/while), then functions. Each domain builds upon the one learned before, expanding your ability to use those concepts as you learn the next. Just my professional opinion.

Anyway, ranting aside, the answer to your problem, as far as I can see from a quick look at your code, is that you don't assign the output from daily_sales() to any of the variables that you are adding up for the weekly total... doh! Actually, I think you are trying to do that by passing the Tot_Value_DayN into the daily_sales() function; however, to do that, you need to pass it as a reference parameter. IE, the last parameter Tot_value in the daily_sales() function should be a float&, not a simple float type. IE,

float daily_sales(int day_number,int item , float quantity1, float quantity2,float quantity3, float quantity4, float quantity5,float value1,float value2, float value3,float value4,float value5, float val1, float val2,float val3, float val4, float val5, float& Tot_value);

Hope this helps.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

Template<> is pointing you in the right direction. Model the problem as classes of objects (Shuttle, Station, Passenger), define their behaviors and interactions (Shuttle arriving at station, Passenger entering shuttle, ...). Build up some finite state machines to model behavior. See where threads make the most sense. My guess is that each Shuttle, not the stations, should be threaded. The stations should have a mutex that an arriving shuttle (thread) locks, so two shuttles cannot enter the station at the same time. Have you started UML modeling yet? If so, that is how I model these sort of complex scenarios, and I have built some REALLY big systems with very few bugs as a result. I usually spend about 80% of a project's time on design and modeling, and 20% (or less) on coding. Once the model is clear and solid, coding is usually a snap. It keeps one from wandering down dead-end alleys. :-)

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

I don't know if this is available on Windows, but on Linux/Unix/Posix systems there is are two functions statvfs() and fstatvfs() that fill a structure that includes the size of blocks on the device and the number of free blocks. All you need to do to find available space is multiply one (f_bsize) by the other (f_bfree). Thats about as simple as you can get, at least on *ix systems. FWIW, I know that Windows does have Posix API's, so they might have these functions, but knowing Microsoft, they also have their own version. Sorry that my MSDN library isn't installed on my system right now, so I can't look it up.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

A learning disability does not mean unintelligent. The question isn't "shifty", and I can understand your frustration. Unfortunately, there is no simple answer. I personally don't use Windows drawing API's because most of the work I do has to run on many different operating systems (Unix, Linux, QNX, Windows, mobile devices), so I generally use a good platform-neutral graphical API, such as Qt or Wx. Have you looked at these? When you install the Qt development kit (SDK in common parlance), you also get a very nice tutorial that shows you how to do a lot of that stuff.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

The obvious point of this exercise is to learn recursion, which is when a function calls itself, terminating when some barrier is reached. A symbol for this is the great worm Ouroboros who encircles the Earth, eating his tail. An interesting article about this is here: http://en.wikipedia.org/wiki/Ouroboros. The process potentially never ends... :-) Here is an example:

void recurse_until( int stop_when )
{
    if (stop_when > 0)
    {
        recurse_until( stop_when - 1 );
    }
    return;
}

So, recurse_until() will keep calling itself until stop_when (the barrier) == 0, then then entire thing pops back to the original caller. This is, coincidentally enough (back to Ouroboros) called tail recursion.

If you do something like this, and each call where the barrier is > 0 you output a '*' before you call recurse_until() again, and a '$' after the call, you will get the results you want, with a single call from main() to recurse_until(), using the input number for the initial barrier value.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

Also note the constructor for the Person class, that the member variables are initialized inside the body of the constructor. This is very much beginner practice/mistake, and "not good", the reasons for which I shall not get into here (long-winded lecture material). However, each constructor has an initialization block between the end of the argument list and the beginning of the constructor body, which is where member variables are properly initialized. So, the correct way would be:

Person(string name1, int age1)
      : name(name1), age(age1)
    {
    }
rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

Look at the functional blocks first, those are candidates for refactoring into separate functions. For example, the sort block:

// sorting
    for (int c=0; c<size-1; c++) {
        for (int d=0; d<size-1-c; d++) {
            if (n[d] > n[d+1]) { // swapping
                double temp;
                temp = n[d];
                n[d] = n[d+1];
                n[d+1] = temp;
            }
        }
    }

can be turned into a function very easily - let's call it sort_doubles():

void sort_doubles( double n[], size_t size )
{
    // sorting
    for (size_t c=0; c<size-1; c++) {
        for (size_t d=0; d<size-1-c; d++) {
            if (n[d] > n[d+1]) { // swapping
                double temp;
                temp = n[d];
                n[d] = n[d+1];
                n[d+1] = temp;
            }
        }
    }
}

Notice that I changed the loop variables c and d to size_t instead of int. That is because array indexes are size_t types. Also, the array parameter passed to the function is by default by reference in C++, so sorting the array in the function, results in the passed array getting sorted - they are one and the same. So, that block of code in your code for sorting the array is now replaced with this single line:

sort_doubles(n, size);

Note that you should also change the type of size from const unsigned short to either a size_t or const size_t. Making it const really doesn't do anything for you in this case. That would be more useful for global or external variables, but unnecessary here.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

Mike makes excellent points. And he took a good deal of his valuable time to point these details out. I'm usually a bit more parsimonious in my advice! :-) Anyway, most of what he says is spot on.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

It depends upon what you want to do. As shown, it is pretty meaningless.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

School work? Please don't ask us to do it for you! There are a lot of resources to research this on the web. Remember, Google is your friend! I did a quick search, and found the answer to your question in about 5 seconds...

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

Not enough information, which is why you have been down-voted. There are a lot of "standard books" that I wouldn't use to wipe... you get my meaning. Even f() is, in today's standards, an invalid construct since the lack of a return type defaults to an integer, and there is no return value in the function. So, this is totally bogus and I have said enough. P.S. I teach advanced C and C++ programming to software engineers.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

What does yum say are the package name/versions of the kernel, kernel-headers, and kernel-devel? Also, you need to boot into runlevel 3 (text mode) with the new kernel to install the nVidia drivers for it.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

Yes, there has been a lot of chatter on the boards (linuxforums.com for example) about this. My solution was similar, but different - I removed the nouveau driver altogether, along with any other installed nvidia pieces, switched to runlevel 3, installed the proprietary nvidia driver, and rebooted. Still, a real PITA, for sure! The nouveau driver is still not ready for prime time. Sometimes it gets worse. On my RHEL 6 workstation (actually running Scientific Linux 6), the kernel had nouveau parts built into it, not as modules, and nVidia won't install with it that way, so I had to get the kernel source, modify the configuration, rebuild, reinstall the kernel and modules, reboot into runlevel 3, and then install the nVidia driver... Fortunately, there were other changes I needed to make to the kernel, so it was a wash, time-wise, but for normal users? Gag!

Anyway, thanks for the post. I'm going to make a copy and post it elsewhere when this comes up, if you don't mind.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

Better:

struct Segment
{
  int start, end, value;
};

class Set
{
private:
  vector<Segment*> segments;
public:
  Set() {}
  virtual ~Set() {
    for (size_t i = 0; i < segments.size(); ++i) {
      delete segments.at(i);
    }
  }
  vector<Segment*>& getSegments() {
    return segments;
  }
  const vector<Segment*>& getSegments() const {
    return segments;
  }
  // accessor functions...
};
 
class Collection
{
private:
  vector<Set*> sets;
public:
  Collection() { }
  ~Collection() {
    for (size_t i = 0; i < sets.size(); ++i) {
      delete sets.at(i);
    }
  }
  void push_back(Set* set) {
    sets.push_back(set);
  }
  // other accessor functions...
};
 
int main()
{
  Collection collection;
  // open file, read file
  Set* set = new Set;
  while (!f.eof()) {
    Segment* segment = new Segment();
    set->push_back(segment);
    // fill segment
    // instantiate set using "new" as needed, and fill it with segments
    collection.push_back(set);
  }
 
  // do other stuff
 
  return 0;
}

Memory management in C++ is no different that C by default, BUT IT COULD BE A LOT EASIER! There are techniques, such as using smart pointers and reference counters to hold your Segments and such, so you don't have to destroy them manually. I do this all the time, and as a result, have nearly zero delete statements in my code, and no memory leaks. I also have to deal with very large data sets, for statistical analysis of stocks and options, or performance and failure analysis of large computer networks, for example. My wife also does a lot of C++ coding, but she has data sets that dwarf the mind! …

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

Hi,

I've started developing for Androind [ditched Symbian but that's a whole diferent styory], and I'm not what you'd call a naturall Java developer [much prefer c++]. Eclipse seems to run rediculously slowly on windows 7 (64bit), and running a dual boot system with Linux [on which it seems to run a lot faster] is out of the qustion as it destabalises my machine. I don't have the cash to invest in a dedicated Linux machine at the moment so that's out of the question, and I need windows for music production.

My question is does this have anything to do with the fact that I'm having to develop in 32bit Java on a 64bit system. Can I run Eclipse useing 64bit Java, and develop the app in 43bit Java for Android?

Thanx

[P.S. Sorry about the spelling, I'm dislexic and I've just switched back to IE and it dosen't have aspell checking]

As to the specific reason why Eclipse seems to run slow on your Win7 system, I can't say, but I do know that there is a LOT of unnecessary cruft running on most Win7 systems I have seen (clients - I won't touch it myself with a 10' poll). The first thing to look at is the virus scanner. Most Windows AV tools dynamically scan EVERY bit of stuff that goes into memory, with the resulting serious hit on performance. So, go to the security center and turn off on-access scanning and then see if it runs …

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

I take it you are going to hold onto the string pointed to by p? Wny not make a copy of the source string as in a C++ string class object? In case you didn't know, I believe the string class uses a copy-on-write memory management algorithm, so if you don't modify the string, all you are getting is a pointer to the original - no actual allocation or copying done. There is rarely a reason to use C-style string pointers in C++. If you need to modify the contents of a string, pass it around by reference. If you only want to access or copy it, pass it around by const reference. Properly written, C++ is much more secure and in fact more efficient than all but the most carefully crafted C code. I've been a professional software engineer for 30 years, cut my teeth on C, and 20 years ago switch to C++ for major (10M loc) system development. Most of the stuff I've done since then couldn't be done in C, at least in the time frames I had to do it in. I still use C for kernel module and device driver development, but it's like going to the WC back in the 17th century - it's dark, dirty, nasty, and unsanitary! :-) FWIW, in that major system of 10M loc, we had ZERO deletes and no memory leaks because we "encouraged" our engineers to use our garbage-collecting smart pointers. Not having to worry about scoping …

mike_2000_17 commented: "6-Sigma failure rates were too high! " Holy macaronies!! +2
rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

To clear a terminal or console on any Unix/Linux system or other system with an ANSI, xterm, or DEC VT-100-compatible terminal, you can output a ^L (control-L) hex 0x0C (form-feed character) to stdout and that should do it. BTW, the system command to clear the screen on Linux systems is "clear", not "cls". Anyway, there isn't a simple one-line function that will do this on all systems, unfortunately!

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

Ok. This is pretty snappy and using unsigned long long (64bit) values, you can get a fibonacci number up to about 100. On my system, there is no apparent delay from input to output of any number. In any case, for a 32bit integer (unsigned), fib(47) is as high as you can go before you wrap around. Not sure of the exact number, but I think a 64bit value gets you to about 100 or so. It definitely wraps shortly after that.

#include <stdlib.h>
#include <iostream>

using namespace std;

unsigned long long fib2(unsigned long long n)
{
    if (n == 0) return 0;
    if (n == 1) return 1;
    if (n == 2) return 1;
    return (fib2(n-1) + fib2(n-2));
}

unsigned long long fib( unsigned long long n )
{
   unsigned long long array[n];

   if (n <= 10) return fib2(n);

   // Build up array of 10 elements to work from
   for (unsigned long long i = 0; i < 10; i++)
   {
      array[i] = fib2(i);
   }

   // Populate the rest of the array by using the previously computed values.
   for (unsigned long long i = 10; i < n; i++)
   {
      array[i] = array[i-1] + array[i-2];
   }

   // Now return final value for N
   return array[n-1] + array[n-2];
}

int main( int argc, const char* argv[] )
{
    for (int i = 1; i < argc; i++)
    {
       cout << "fib(" << argv[i] << ") = " << dec << fib(strtoul(argv[i], 0, 10)) << endl;
    }
    return 0;
}
rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

yeah, its 1 1.
But now the problem is the long. This would work only till n = 46.
What if I wand fib (100)? Any suggestions?
Regards

A recursive fib routine will crash and burn before you get to very big numbers. This is one of those situations where if your compiler can't do adequate optimization you are going to have to unroll it by hand. The algorithm is naturally recursive, and building an optimized version that is not means you will probably have to resort to the evil "goto" statement, and a lot of insidious cruft that you will NEVER want to look at again after it is working!

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

It was slow, but it worked. Many many years ago I wrote a fibonacci generator using try/throw/catch exceptions in C++ as a test of the exception handling of various compilers of the time (about 20 years ago - a lot of them were buggy). I'd post it here, but the code is hiding on a floppy somewhere in my code library and my last computer with a floppy drive is in storage... :-( Oh, well. Anyway, it can be done, but not effectively for very large numbers! I think we stopped at 13 or so. Enough to test the compiler, but not so much as to overflow the stack.

In other history, I used fibonacci sequences in an index fund balancing program I wrote for a major investment fund back in 1984-85 in San Francisco. They had to rebalance the funds to track whatever indexes they were tied to every day, and this was for over $10B on the S&P500, Russel2000, etc. We were actually able to do that with PC's (with 8087 coprocessors), sucking down the close-of-day prices from the market data feeds, building up the model portfolios, and generating buy/sell orders for the open of the next day.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

So, putting my babbling aside, here is some simple pseudo-code for a substring search (not using the strstr() function) - and I am going to assume that the orderedArrayListType class has an array index operator - makes things a lot easier. :-)

S = subset (possibly)
L = list

current member of L is called cl
current member of S is called cs

// Outer loop
found = false
for cl = 0, while not found and cl < L.length(), cl = cl + 1
    // Check if S matches L at current position in L
    // Set placeholder true or false depending upon whether S.length() + cl
    // is past the end of L. If so, then we are done.
    // If the logic tests false, then the inner loop will be skipped and
    // we are done.
    maybe_found = (L.length() >= cl + S.length())
    for cs = 0, while maybe_found and cs < S.length(), cs = cs + 1
        if L[cl + cs] != S[cs]
            cl = cl + cs        // Need to adjust cl for number of elements in S we tested
            maybe_found = false
        end if
    end for
    found = maybe_found         // If maybe_found is still set, we are done.
end for
return found

Anyway, my point is that is is a generic search algorithm that can be adapted easily to your problem.

rubberman 1,355 Nearly a Posting Virtuoso Featured Poster

This is just another name for substring search. Again what I keep saying to you programming newbies - understand clearly first what your task is and then write out what you need to do in plain language pseudo-code each step that you need to take to accomplish your task. Design first, code last.

Example: I had to develop a rule processing engine where customers could edit some specifications in the database, and it would adapt our compiled software (C++ code) to their site requirements. I first wrote out as clearly as I could what we needed to do. Then I designed UML models until I had a perfectly clear picture in my mind how the system was structured and how the data flows and transformations (including generating complex SQL query code) had to work. That took several months of intense work (mostly brain work). Coding and testing took two weeks. I got a patent for the work... In any case, complex manufacturing process changes could be done with editing less than a half dozen rules stored in the database. My program would read those rules, modify our classes internal structures as necessary, generate the appropriate (and optimized) SQL code to do things like route a lot (semiconductor wafers in this case) to the best next piece of equipment in the fab based upon the lot's process plan, the available equipment, recipes loaded in the equipment, maintenance plans for the equipment, priority of the lot, and a zillion other factors …