Rashakil Fol 978 Super Senior Demiposter Team Colleague

With Python questions, you definitely need to use CODE tags.

Rashakil Fol 978 Super Senior Demiposter Team Colleague

What is a terrorist country, and how do you kill it?

Rashakil Fol 978 Super Senior Demiposter Team Colleague

It allows you to not crash while fixing your algorithm ;)

You've got a point there :)

Rashakil Fol 978 Super Senior Demiposter Team Colleague

It's a procedural language and it has few datatypes -- just integers, floating point numbers, and sequences. No mention of struct-like objects or records. My calculator has a more sophisticated programming language.

I don't think it's very good. Maybe it runs faster than Perl and friends but that's because it's incredibly simple. Or simple-minded. I'd pick Ruby over it any day.

Rashakil Fol 978 Super Senior Demiposter Team Colleague

Also note that it's safer to memset these strings before doing anything with them,
ie:

char prog[200];
char mir[200];
memset( prog, '\0', sizeof( prog ) );
memset( mir, '\0', sizeof( mir) );

This is not safer. It is only helpful when an algorithm is broken or if the algorithm deliberately relies on zeroed space. This just covers up the real problem of a broken algorithm.

Rashakil Fol 978 Super Senior Demiposter Team Colleague

You should use #include <iostream>, not #include <iostream.h>.

You should use int main(), not void main(void).

Judging by your style of code, it seems that for whatever reason, you're not using the standard library. (You could use the std::sort function.) In that case, you'll want to write a subroutine that, when given a pointer to an array of integers and the length of the array, rearranges the elements in ascending order.

How would you do that, you say? Well, how would you put a deck of cards in ascending order? There are many ways.

I'm sure you'll soon get some people posting their own functions or giving code for using the already-existing std::sort function (which you could just look up anyway), but since you seem to be learning, it's much better to figure it out yourself.

I already gave you a hint: how would you go about systematically sorting a deck of cards?

Rashakil Fol 978 Super Senior Demiposter Team Colleague

You won't be confused by learning Java and C++ at the same time; it's like trying to learn to drive while you happen to be in culinary school.

Except that in the case of Java and C++, much of the knowledge maps over. After you learn a few programming languages, it's real easy to learn others.

But all this should not matter. Computer science has as much to do with programming as astronomy does with the operation of telescopes. The programming language they use is mostly irrelevant.

Rashakil Fol 978 Super Senior Demiposter Team Colleague

Telling you the answer would basically be doing the whole assignment for you. You need to think harder. You're using printf?...

Rashakil Fol 978 Super Senior Demiposter Team Colleague

The pack.at(0) behavior is of standard library vectors, not arrays.

Rashakil Fol 978 Super Senior Demiposter Team Colleague

Search on CPAN.

It sounds to me like you're going to need some program running on the client machines, unless you plan on poking through a Windows security hole.

Rashakil Fol 978 Super Senior Demiposter Team Colleague

Initialize arrays like this:

int some_primes[9] = {2, 3, 5, 7, 11, 13, 17, 19, 23};
Rashakil Fol 978 Super Senior Demiposter Team Colleague

Why are you so impatient?

Make an array of integers of length 256. Maybe named 'nums'. Use the character as the index; to get the number for 'x', you'd write nums. You'll need to initialize the values of the array of course.

And pray that your characters are eight bits. This method does not scale too well for larger character sizes. If your characters are nine bits wide, you'll need an array of integers of length 512. If 16 bits wide, 65536. So stick with 256 and just check to make sure your character is less than 256.

Rashakil Fol 978 Super Senior Demiposter Team Colleague

You could better explain what you mean by, "linux script."

Rashakil Fol 978 Super Senior Demiposter Team Colleague

You need to be more detailed. In general, you can execute executables with backticks. E.g.

`dir /p`

There isn't just some "command" in the Perl language that does what you want, though.

Rashakil Fol 978 Super Senior Demiposter Team Colleague

Many operating systems' source code are freely available. They certainly are not written in HTML, though...

Rashakil Fol 978 Super Senior Demiposter Team Colleague

Here's how to understand the problem:

Run through your code, step by step, on paper. What did you want to happen? Why is it not happening?

Right now, it looks like your program is trying to calculate the value of pi/4.

Will ( num_darts != 0 ) evaluate to true the first time?

Rashakil Fol 978 Super Senior Demiposter Team Colleague

In response to Narue's fib2:

If we're going to have a static, fixed-length, read-only array, then heck,

unsigned long fib3 ( unsigned long i )
{
  static unsigned long save[45] = {0, 1, 1, 2, 3, 5, 8, 13, 21,
 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181,
 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418,
 317811, 514229, 832040, 1346269, 2178309, 3524578,
 5702887, 9227465, 14930352, 24157817, 39088169,
 63245986, 102334155, 165580141, 267914296, 433494437,
 701408733};

  return save[i];
}
Rashakil Fol 978 Super Senior Demiposter Team Colleague

You're dividing your interest rate by 100.0 twice.

Rashakil Fol 978 Super Senior Demiposter Team Colleague

somthing like this:

#include <iostream>

int main ()
{
    char c[6] = "45678";
    int num[5];
    for (int i = 0; i < 5; i++)
    {
        char temp = c[i];
        num[i] = atoi(&temp);
        std::cout << num[i] << std::endl;
    }
    system("pause");
}

This code is downright dangerous. Suppose I add one line that seems not to affect the outcome:

#include <iostream>

int main ()
{
    char c[6] = "45678";
    int num[5];
    for (int i = 0; i < 5; i++)
    {
        char temp = c[i];
        char khan = '9';
        num[i] = atoi(&temp);
        std::cout << num[i] << std::endl;
    }
}

On my system, I get 49 59 69 79 89 with this code. Why?

This happens because temp is just a single character. You don't know what goes after it. When you pass a pointer of temp to atoi, atoi will expect a pointer to an _array_ of characters. It will read numbers until it gets a nondigit -- a character that is not in the range '0' .. '9'.

When you ran your code, you got lucky. The position in memory next to wherever temp was stored did not have an ASCII digit.

With my code example, you might get different output, since the result is affected by where your compiler puts everything.

Since khan may get stored right next to temp in memory, atoi might think it's the next character in the string, and so it reads 49, 59, and so on.

If you want …

Rashakil Fol 978 Super Senior Demiposter Team Colleague

Wouldn't that trap high at 1 and low at 0? Perhaps 1, 1 are what you meant as starting vars.

Did you actually think through a few iterations of the loop?

Rashakil Fol 978 Super Senior Demiposter Team Colleague

Maybe something simpler...

long fib_num(long n)
{
	long low(0), high(1);

	while (n--) {
		high += low;
		low = high - low;
	}

	return low;
}
Rashakil Fol 978 Super Senior Demiposter Team Colleague

Your fibonacci function runs in exponential time.

Let me put it this way:

Suppose that it takes 1 microsecond to compute fib_num(0) and fib_num(1).

Then, in computing fib_num(2), you'll call fib_num(0), which takes 1 microsecond (mms, I'll abbreviate), and fib_num(1), which also takes 1 mms. This means that fib_num(2) will take at least 2 mms.

Then, to compute fib_num(3), you will call fib_num(2), which takes at least 2 mms, and then fib_num(1), which takes 1 mms. So fib_num(3) takes at least 3 mms.

Continuing this pattern, fib_num(4) would take at least 5 mms, fib_num(5) would take 3 + 5 = 8 mms, and fib_num(6) would take 5 + 8 = 13 mms, at least.

This is actually the fibonacci pattern of growth in runtime. And the fibonacci pattern grows exponentially. You'll find that for large values of n (like 100), the time it takes to compute f(n) is about 1.618 times the amount of time it takes to compute f(n - 1). If fib_num(6) takes 13 microseconds, then fib_num(100) would take at least 1.618 to the 94th power times 13 microseconds. And 1.618**94 * 13 equals 5.74e20. This amount of microseconds is equal to 5.74e14 seconds. Which is about 18 million years. You might as well get up for some coffee.

Even if you ran this program on a computer that was 10000 times faster (the times mentioned above are kind of slow by today's standards), it would still take at least 1819 …

Rashakil Fol 978 Super Senior Demiposter Team Colleague

I hope you noticed my other comment.

'std' is a namespace, not a class. When using headers with names like <vector> instead of <vector.h>, you need to use it. You can put 'using namespace std;' in your program to avoid having to write 'std' everywhere. You could also write 'using std::vector;' to throw out the requirement that std:: be used in front of 'vector'. I think the latter method, of importing names one by one, is better, because later, the standard library might be expanded, and you don't want names of new standard library objects to collide with ones you're using. (That's what happens with wanton disuse of the namespaces).

Rashakil Fol 978 Super Senior Demiposter Team Colleague
std::vector<std::vector<int> >

Kaza, your problem from before might have been that you didn't have a space between these two right angle brackets. You need a space. Without a space, the angle brackets get interpreted as a '>>' operator.

Rashakil Fol 978 Super Senior Demiposter Team Colleague

From what I've read on Wikipedia, it looks like you want the magnitude and the argument of a complex number. Suppose the real part is stored in re and the imaginary part is stored in im (both doubles, presumably). Then

double amplitude = sqrt( re * re + im * im);
    double phase = atan2( re, im);

Amplitude is the absolute value in the sense that it is the distance of the complex number from the origin.

What book is this?

Rashakil Fol 978 Super Senior Demiposter Team Colleague

I never see you assign to the your node structure's next pointer. Thus, you are using uninitialized pointers. That's your problem.

Rashakil Fol 978 Super Senior Demiposter Team Colleague

On the contrary, you do have problems with the structure of your program. Is it immediately obvious how your program flows? Not to the people who didn't code it. That means there's a problem.

Rashakil Fol 978 Super Senior Demiposter Team Colleague

Your main problem is program design. If you designed the structure of your programs better (using subroutines, no gotos), your problems with pointers (and everything else) would diminish. The main reason that you can't maintain this program is that you have designed it for unmaintainability.

Rashakil Fol 978 Super Senior Demiposter Team Colleague

If you want help, post the entire script, and use CODE tags.

Rashakil Fol 978 Super Senior Demiposter Team Colleague

Will I receive college credit for doing this work?

How about you do it yourself and then come here when you have problems.

Rashakil Fol 978 Super Senior Demiposter Team Colleague
std::string Hex(int num)
{
    std::string  s1;
    char sign[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
....

You could also write

char sign[] = "0123456789abcdef";

which might be a bit more manageable.

Rashakil Fol 978 Super Senior Demiposter Team Colleague

Suggestion 1: Put your code in code tags.

Why are you breaking when the remainder is 1?

I think you want rem = divisor % 16 to appear before divisor = divisor / 16.

Your while condition should be: while (divisor != 0)

Also, you forgot the cases where your remainder is less than 10, in terms of setting hex1.

Overall, I'd say your algorithm is perplunked, and you need to do some more thinking.

Rashakil Fol 978 Super Senior Demiposter Team Colleague

The average is 76.4666.

desidude, since your sum and count are modified after the while loop, only the last value of your numbers gets added to sum, and count gets incremented once, from zero to one. And 77 is your last value.

Rashakil Fol 978 Super Senior Demiposter Team Colleague

i would also appeciate a smaller version of this progrm.

Then use subroutines.

Rashakil Fol 978 Super Senior Demiposter Team Colleague

To swap Perl scalars without writing a third variable:

($x, $y) = ($y, $x);

If you want to swap Perl arrays, well, you'd be better off having used array references and swapping those like above.

Rashakil Fol 978 Super Senior Demiposter Team Colleague

How about:

int lookup(double salary)
{
   if ( salary < 300 )
   {
      return 0;
   }
   if ( salary < 1000 )
   {
      return ((int) salary) / 100 - 2;
   }
   return 8; /* 1000 or more */
}

[edit]Moments after posting, I couldn't shake the feeling that someone saw this and was planning to post a binary-tree version of the lookup. ::wierd::

Nah, that would be too inefficient :-D

Rashakil Fol 978 Super Senior Demiposter Team Colleague

Your main function is ended with a closing brace before your array line.

Rashakil Fol 978 Super Senior Demiposter Team Colleague

You have a semicolon in the line

while (iexit == 1);

This is equivalent to the following:

while (iexit == 1) {}

So you have an infinite loop that does nothing.

Rashakil Fol 978 Super Senior Demiposter Team Colleague

You probably want to pass by reference.

Rashakil Fol 978 Super Senior Demiposter Team Colleague

I guess the real question is speed - whether iterators or array [] type access is faster..

Dereferencing an iterator is faster because a uses one addition operation. But comparing two iterators is slower than checking if an integer is zero. If compiled dumbly, the iterator solution should be slightly faster, but it would not be a very measurable difference.

With compiler optimizations in play, the end result is up for grabs. Trying to solve this problem as efficiently as possible is rarely worth the programmer's time -- there are some more tricks that you could pull, but most comparisons will have unequal lengths or will be decided unequal very early in the loop -- only the equal strings run all the way through.

Rashakil Fol 978 Super Senior Demiposter Team Colleague

Here's a version that uses STL iterators. Reverse iterators make the while loop rather elegant. You can also decrement to backup on a regular iterator, but this version uses a reverse iterator instead.

bool are_mirrored(const string &name, const string &name2)
{

	if (name.size() != name2.size()) {
		return false;
	}

	string::const_iterator p = name.begin();
	string::const_reverse_iterator r = name2.rbegin();

	string::const_iterator e = name.end();

	while (p != e) {
		if (*p++ != *r++) {
			return false;
		}
	}

	return true;
}

Because r is a reverse_iterator, it starts at the last character and faces in the opposite direction. It perceives the string backwards.

Rashakil Fol 978 Super Senior Demiposter Team Colleague

>Also, size is four characters while length is six.
I find that hard to believe, since length() returns size(). Perhaps you're thinking of capacity(), in which case your suggestion is incorrect because the result of capacity() is largely implementation-dependent.

Four characters as in s-i-z-e. It's easier to code with shorter names.

Rashakil Fol 978 Super Senior Demiposter Team Colleague

>main()
This is correct:

int main ( void )

int main() is also acceptable, at least with C99.

>}// end of main.
This is where the undefined behavior is. You say you're going to return int, but you don't return anything.

Note that he didn't actually say he was going to return int ;-)
With the C99 standard, if main has no return statement, then return 0 is assumed. Portability to older compilers is of course desirable though.

Rashakil Fol 978 Super Senior Demiposter Team Colleague

Here's an ever so minor nitpick.
Now it's nothing much when strings are short, but if such a function were used on something bigger and/or in a large loop, there is quite a bit of waste there. Let's say name is 1000 chars long: let's loop through 1000 chars to the end to find the length. Then later let's loop through 1000 chars to the end again to again find the length. A minor change would be to save the value and only calculate it once.

This inefficiency is not actually the case. The standard library string class usually stores three pointers: One to the beginning of the string's array of characters, one to the end of the string's array, and one to the end of the string. (The string might not use all of its allocated space.) Some implementations might store one pointer and two size_t integers -- but either way, the size() function is guaranteed to be a constant-time operation.

The standard library's size() member function could look something similar to this (never mind that it really gets implemented in the basic_string class):

string::size_type string::size() const
{
    return end_ - beg_;
}

And that would get inlined by a compiler -- making it one extra subtraction operation instead of one thousand-something operations. Only the C library's strlen function has to loop through the string, because C-style strings are simply pointers to arrays of characters that have a zero somewhere at the end.

And note …

Rashakil Fol 978 Super Senior Demiposter Team Colleague

Use GET for a location if you want somebody to be able to revisit the page. For example, search engines use GET.

Troy commented: Good point, Rashakil Fol +1
Rashakil Fol 978 Super Senior Demiposter Team Colleague

Can you tell me why you prefer to use .size instead of .length?

All or almost all other standard library containers use size() exclusively. length() was left in the string class for backwards compatibility with something, according to my current unknowledgeable theory. Also, size is four characters while length is six.

Don't completly understand why you prefer to use this, but, I'll google to see what string::size_type just is :?:

Usually I'll just use size_t (which is an integer type large enough to contain the length of any old array). Using string::size_type just makes for more portable code (but this would have to be some bizarre, Star Trek-like pseudocomputer.) You don't have to use it, and size_t will always work. (The only situation where I imagine using string::size_type could ever actually matter is one where strings are for some reason stored in a different memory space than other objects.)

int is generally fine, too, on 32-bit systems, as long as strings are smaller than 2 million-something characters long.

string::size_type i = name.size()-1;

Has to be -1, otherwise your comparing '\n' ;)

There's no '\n' character in the string. i starts after the end of the string because --i returns the decremented value of i, meaning that the first comparison uses the last character and first character of the respective strings. (Whereas i-- would return the original value of i.)

Unless there's a bug. I have not compiled and run.

Rashakil Fol 978 Super Senior Demiposter Team Colleague
if (name[i] != 0 name[j])

Is this right?

I might write it like this:

#include <iostream>
#include <string>

using namespace std;

bool are_mirrored(const string &name, const string &name2);

int main()
{
	string name = "Johan", name2 = "nahoJ";

	bool c = are_mirrored(name, name2);

	if (c) {
		cout << "True!" << endl;
	} else {
		cout << "False!" << endl;
	}

	cout << "Press any key to continue!\n";
	cin.get();

	return 0;
}

bool are_mirrored(const string &name, const string &name2)
{

	if (name.size() != name2.size()) {
		return false;
	}

	string::size_type i = name.size();
	string::size_type j = 0;

	while (i) {
		if (name[--i] != name2[j++]) {
			return false;
		}
	}

	return true;
}

Generally, readability improves when every control structure uses braces and when operators have spaces on them. Also, string::size_type is an integer type that is guaranteed to be larger than any stored string. (It's just an unsigned long int on most systems, though: nothing terribly exciting.)

Also, it's a good idea to only use for loops of the form

for (int i = m; i < n; ++i)

or of the form

for (int i = n; i > m; --i)

Or maybe even:

for (string::iterator i = s.begin(); i != s.end(); ++i)

When you are not looping a single variable through a range of numbers, I consider it better form to use a while loop. You might find this to be the case also.

Rashakil Fol 978 Super Senior Demiposter Team Colleague

In the more general case, you could look at this problem as popping one stack and pushing another stack. (The stacks containing decimal digits.):

#include <string>
std::string rev_digits(unsigned long n) {
    std::string ret;
    while (n) {
        ret.push_back('0' + (n % 10));
        n /= 10;
    }
    return ret;
}

or if you want to return an integer with reversed digits:

/* If n is 10 digits and its units last digit is 4
or greater, there may be problems. (i.e. if the reversed
form is greater than the 32nd power of 2) */
unsigned long rev_digits(unsigned long n) {
    unsigned long ret = 0;
    while (n) {
        ret *= 10;
        ret += n % 10;
        n /= 10;
    }
    return ret;
}
Rashakil Fol 978 Super Senior Demiposter Team Colleague

Oh man, what was I thinking?

Never mind then. :o

(It's not a question of whether C can compile to C++; C++ simply can't be compiled as C! ;-) )

Rashakil Fol 978 Super Senior Demiposter Team Colleague

You'll have to use the former method -- C++ programs don't know anything about their variable's names at run time.