Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need help with C Programming assignment
#23
Russt Wrote:strcmp()

Also, for the permutation code, be careful with strings that have duplicate letters. permutation("aaaaab", "abbbbb") returns true with your code, I think.

The way I first thought of was DS's method; set up an array of size 26. It'd be something like this:

Code:
int count[26];

for (i = 0; string1[i] != '\0'; i++)
{
  int ch = string1[i] - 'a';
  count[ch]++;
}

for (i = 0; string2[i] != '\0'; i++)
{
  int ch = string2[i] - 'a';
  count[ch]--;
}

for (i = 0; i < 26; i++)
{
  if (count[i] != 0)
    return false;
}

return true;

The basic idea is to keep a tally of how many of each letter there are. For example, count[0] is how many a's there are, count[25] is how many z's there are. First it goes through string1 and tallies up each letter, then it goes through string2 and crosses off each letter. If they are permutations of each other, these should cancel out exactly, so everything in count[] should be 0. Then all you have to do is loop through count[] and look for something that isn't 0, because if there is, you know they're not permutations.

But make sure that count[] is initialized at 0, or you get arbitrary values everywhere and messes up. I think
Code:
int count[26] = {0}
will do the trick.

thanks, an i guess i knew to a degree that aaaab and bbbba would show up correct, i just couldnt think of a way around it and realized that that error probably wouldnt have shown up much, due to how few situations it would arise in, and considering i now have 10 hours to spend thanksgiving with family, get a working substring and main (though substring isnt technically necessary) and submit the project.
Reply


Messages In This Thread
Need help with C Programming assignment - by Fiel - 2009-11-23, 09:18 PM
Need help with C Programming assignment - by Fiel - 2009-11-23, 09:22 PM
Need help with C Programming assignment - by Fiel - 2009-11-25, 08:13 AM
Need help with C Programming assignment - by Fiel - 2009-11-25, 11:51 AM
Need help with C Programming assignment - by Sivrat - 2009-11-26, 02:41 PM

Forum Jump:


Users browsing this thread: 1 Guest(s)