segunda-feira, março 05, 2007

Yet another C experiment

My weekend flew in between trains and a weeding. Got home with an incremented flue and a huge head ache. Fortunately a few ours Zombie[ing] where enough to get me back on track.

Thought I'd share this with ya just because I'm amazed at how much mental effort can be in three lines of code . The exercise was:

/* write the function any(s1,s2), which return the first location in the string s1 where any character from the string s2 occurs, or -1 if s1 contains no characters from s2. (The standard library function strpbrk does the same job but returns a pointer to the location)*/

now what most students would write should be something like
int any(char[] s1, char s2[]) {
for(i=0; s1[i]!='\0'; ++i)
for(int j=0; s2[j]!='\0';++j)
if(s1[i]==s2[j])
return i;

return -1;
}

direct reasoning:
go through firstString, if any char in string 2 == current char in string 1 ,return this index.
If no index is found return -1.

and that's what I wrote at frist. Two hours later at 3 am I had 3 lines of code less.

int any(char s1[], char s2[]){
int i, j;

for(i=j=0; s1[i]!='\0' && s1[i-1]!=s2[j]; ++i)
for(j=0; s1[i]!=s2[j] && s2[j]!='\0'; ++j)
;

return s1[i-1]==s2[j] ? i-1 : -1;
}

indirect resoning:
go trough first string only while there are chars in the firstSTring and the last one in frist string is different from the current in second string. This is important because the second cicle interropts if it finds an equal char in the second string and when it returns to test s1, it must stop all cicles.

Finally if last index was an equal char, return it. Else return -1; meaning no equal chars where found.


Deception comes with a much simpler code from standard library... as expected
you can find it together with your sources at:
~/glibc-build/sysdeps/generic/strpbrk.c

strpbrk (s, accept)
const char *s;
const char *accept;
{
while (*s != '\0')
{
const char *a = accept;
while (*a != '\0')
if (*a++ == *s)
return (char *) s;
++s;
}

return NULL;
}


This code uses pointers. In fact originally, as stated before: it returns one!
Pointers are the next curve on my so green C path. I'm hopping to be able to explain this one this afternoon. hihihi
It's been fun so far. Let's hope practice makes perfect. ;)

Better than Valium... try it out.

1 comentário :

PMarques disse...

Olá! eu adorava CONSEGUIR comentar o teu post, mas...sinto-me totalmente impotente!! Não percebo NADA! :-(