I have a program where I'm supposed to have someone input a word and I have the program leave the first and last letters stay while everything else becomes randomized.

I pretty much have the program working, but I don't know how to ignore the first letter.

This is all I have:

char word[256];

void scramble()
{
for(int i = 1; i < strlen(word)-1; i++)
{
int x = rand() % (strlen(word)-1);
int y = (rand() * 10) % (strlen(word)-1);

if(x == y)
{ i--; continue; }

char temp = word[x];
word[x] = word[y];
word[y] = temp;
}

Any help is appreciated!

Word is "abcdefghij".

Valid indexes are 0 through 9, inclusive. You want to pick two indexes and swap the letters.

int index1 = /* random number */
int index2 = /* random number */

// swap
char temp = word[index1];
word[index1] = word[index2];
word[index2] = temp;

First and last letters should be left unchanged. Hence, make sure index1 and index2 cannot equal 0 or 9. Go through your code and make sure that that is impossible.

Word is "abcdefghij".

Valid indexes are 0 through 9, inclusive. You want to pick two indexes and swap the letters.

int index1 = /* random number */
int index2 = /* random number */

// swap
char temp = word[index1];
word[index1] = word[index2];
word[index2] = temp;

First and last letters should be left unchanged. Hence, make sure index1 and index2 cannot equal 0 or 9. Go through your code and make sure that that is impossible.

I don't understand what goes into index1 and index2...

I don't understand what goes into index1 and index2...

Any random number between 1 and the length of the word minus 2, inclusive. If the word has length 10, then any number between 1 and 8 inclusive. You might want to make sure that index1 and index2 aren't equal too. No harm if they are, but it would just be swapping two letters for themselves. Pointless.

So go back to your original lines 7 and 8 and modify them slightly so x and y can't be less than 1 and can't be greater than strlen(word) minus 2.

This article has been dead for over six months. Start a new discussion instead.