#C - 99 75 67 63 bytes
C - 99 75 67 63 bytes
g(char*s){int i=0,j=*s;while(s[i])j^=s[++i];return j^9?i:g(s);}
Ungolfed:
int g(char *s){
int i = 0,
j = s[0]; // first char of s
while(s[i] != '\0'){
j ^= s[++i]; // j = j XOR [next char]
}
if(j != 9){ // g^o^o^g^l^e = 9
return i;
} else {
g(s); // infinite recursion
}
}
Using it:
g("bing") // 4
g("duckduckgo") // 10
g("google") // segmentation fault
Will return the length if g XOR o XOR o XOR g XOR l XOR e
isn't 9
, else it will infinite recurse causing a stack overflow.
How it works
I used a (very) crappy hashing algorithm (a XOR b XOR c ...
) to get a single number from the first six chars of the string. Collision likelyhood is very high, but if we assume the string has to be the name of an actual search engine, then the collision likelyhood is fairly low.
So, first we have i
, which iterates through the string until s[i]
is NUL
(0), and while counting the length of the string, the selected char is XOR'd onto j
, which is initialized to the first char in s. For "google", the result of this operation is 9.
The main thing this takes advantage of is the way pointers work in C. A pointer is actually a large number that denotes an address in memory, &var
will return a pointer to var
, while *var
will dereference a pointer (grab the value at that address). Thus, *s
is equivalent to s[0]
. I think this is where most beginners get lost, confused and frustrated when it comes to C, like when you try to send a struct *
to a function that takes struct *
by sending &struct_ptr
, which would be a memory address to a memory address, effectively making the compiler give an error such as function expects 'struct *' but got 'struct **'
.