Sign in to follow this  

Total newbie

Recommended Posts

Hi, I have been learning C++ for 3 days now, so I am still very noob. I have started to work through a book by Michael Dawson, "Beginning C++ Game Programming". There is one bit of code I cant understand any help would be very welcome! So this is part of a word game where the program randomly picks a word and then rearranges it, for the user to figure out. This is the part where it rearranges the word it picked, wich i do not understand... :( please help! string jumble = theWord; //the word is the picked word int length = jumble.size(); //jumble is the rearranged version for (int i = 0; i < length; ++i) { int index1 = (rand() % length); int index2 = (rand() % length); char temp = jumble[index1]; jumble[index1] = jumble[index2]; jumble[index2] = temp; }

Share this post

Link to post
Share on other sites

make a copy of the word, call it 'jumble'
count the letters in 'jumble', call it 'length'
repeat the following 'length' times
get a random number from 0 to 'length', call it 'index1'
get a random number from 0 to 'length', call it 'index2'

swap the letter at position 'index1' in jumble with the letter at 'index2' in jumble

I'm guessing that the bit that confused you was the '%' sign?
"%" is the modulo operator. The % operator goes hand-in-hand with the / operator (division). It returns the remainder of the division of the left/right values.
e.g. 24 divided by 10 is equal to 2 and 4 remainder, or in code:
24 / 10 == 2
24 % 10 == 4

So back to your code, "rand() % length" gives us a random number from 0 to length, because "rand()" gives us a random number from 0 to [really big number], then you divide it by 'length' and find the remainder, which is guarenteed to always be bigger or equal to 0 and smaller than 'length'.

N.B. This is only true for integer math though (i.e. when you're using variables of type 'int' or similar). The % operator cannot be used for floating-point math.
24.0f / 10.0f == 2.4f

To find the remainder of a floating-point division, you'd have to do it yourself:
float div = 24.0f / 10.0f;//2.4f
float mod = (div - int(div)) * 10.0f; //4.0f

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this