158
\$\begingroup\$

We all know that if you google the word "google" it will break the internet.

Your task is to create a function that accepts one string and returns its length, in the fewest possible Unicode characters.

However, if the given string is google (lowercase), it will cause an error.

For example, g('bing') will return 4 but g('google') will cause an error.

Please provide an example of usage, and the error if possible.

\$\endgroup\$
  • 122
    \$\begingroup\$ I googled google, and Google found Google on Google. Myth Busted. \$\endgroup\$ – Geobits Sep 28 '15 at 16:32
  • 86
    \$\begingroup\$ @Geobits That is simply a test to see if I will google Google, which I will not. :D \$\endgroup\$ – rybo111 Sep 28 '15 at 16:33
  • 7
    \$\begingroup\$ Does the function need to be case sensitive? Should it throw given 'gOOgle'? \$\endgroup\$ – AXMIM Sep 30 '15 at 22:07
  • 2
    \$\begingroup\$ When I type google into google (the search bar on chrome), a message came up asking if I wanted to go to google. (Now that it is a tld, this makes sense i.e. com.google works). I clicked it and got a dns lookup error. Internet:broken! \$\endgroup\$ – Craig Oct 1 '15 at 4:18
  • 4
    \$\begingroup\$ I'm voting to reopen this. I have seen no questions about what constitutes an error for this challenge and it already has 154 answers so I don't think it's fair to change the spec. This may not be an example of a good question but it's clear enough. If an answer really comes down to whether or not a certain output is an error it probably just won't get as many upvotes, anyway. \$\endgroup\$ – Poke Aug 1 '18 at 19:52

146 Answers 146

2
\$\begingroup\$

TI 89 BASIC, 34 bytes

I did this in TI 89 for fun. There has got to be a more optimized method, but this is the best I could come up with for the moment.

f(x)
getNum(x/"google")&""0+dim(x)

Basically abuses the fact that a string divided by itself becomes 1.

0 is necessary to remove the string from the calculation otherwise you would return ("fun" + 3) which i don't think is compliant to the rules.

\$\endgroup\$
  • \$\begingroup\$ Alright, wasn't sure if I could post multiple answers to a solution @lirtosiast , thanks! \$\endgroup\$ – STDQ Mar 26 '16 at 20:20
2
\$\begingroup\$

Hoon, 32 bytes

|*
a/*
?<
=(a "google")
(lent a)

Uses a wet gate to avoid having to specify a/tape instead of a/*, assert that a doesn't equal "google" or panic, return the length of the tape.

> %.  "abc"
  |*
  a/*
  ?<
  =(a "google")
  (lent a)
3
> %.  "google"
  |*
  a/*
  ?<
  =(a "google")
  (lent a)
ford: build failed ~[/g/~dirdet-lasmes-digwyc-ribrux--rispyx-bitrus-bidmut-winsud/use/dojo/~dirdet-lasmes-digwyc-ribrux--rispyx-bitrus-bidmut-winsud/inn/hand /g/~dirdet-lasmes-digwyc-ribrux--rispyx-bitrus-bidmut-winsud/use/hood/~dirdet-lasmes-digwyc-ribrux--rispyx-bitrus-bidmut-winsud/out/dojo/drum/phat/~dirdet-lasmes-digwyc-ribrux--rispyx-bitrus-bidmut-winsud/dojo /d //term/1]
\$\endgroup\$
  • \$\begingroup\$ Um... is that supposed to link to urbit? \$\endgroup\$ – Destructible Lemon Nov 20 '16 at 9:55
  • \$\begingroup\$ @DestructibleWatermelon Yup. Urbit provides the compiler/interpreter for the Hoon language. \$\endgroup\$ – RenderSettings Nov 21 '16 at 4:00
2
\$\begingroup\$

Tellurium, 13 bytes

This language is newer than the question, so non-competing I guess.

i?google|d]L^

This program gets input using i, and checks if the input is "google". If it is, it tries dividing "google" by zero (d) well, that doesn't work (duh) so it throws an error.

If the input isn't google, it outputs the length of the selected cell's value (which is the input) using L^.

\$\endgroup\$
2
\$\begingroup\$

AWK, 44 bytes

func f(x){return x=="google"?f(x):length(x)}

Example usages:

awk 'func f(x){return x=="google"?f(x):length(x)}{print f($0)}' <<< "non-google string"
awk 'func f(x){return x=="google"?f(x):length(x)}{print f($0)}' <<< "google"

Print: 17 and Segmentation fault (core dumped) respectively. The second one may cause your computer to run out of memory before it segfaults if you don't have oodles of RAM.

I find Segmentation fault errors to be a bit more broken than divide by zero since they don't even say where the problem is.

Something that looks more interesting would be:

func f(x){if(x=="google"){printf x;return f(x)}return length(x)}`

This would print googlegooglegooglegoogle.... wrapping around the screen until it finally produces the seg. fault, but it's not as 'golfy'

NB. Yeah, I'm a bit late to the party, but nobody had an AWK answer yet. :)

\$\endgroup\$
  • 1
    \$\begingroup\$ +1 for "Segmentation fault (core dumped)" -- my favourite error message \$\endgroup\$ – cat Mar 25 '16 at 15:46
  • \$\begingroup\$ It's my favorite message, too... if I'm not the one that has to debug it. :p \$\endgroup\$ – Robert Benson Mar 25 '16 at 16:04
  • 1
    \$\begingroup\$ On my 64-bit Ubuntu 16.04 with GAWK 4.1.3, the second one doesn't segfault but just eats all my memory until one of three things happens. A) the oom-killer kills it and says Killed, B) my window manager crashes or C) my computer overheats and switches off. Thus, I am adding a note to your answer that this answer may be harmful on machines which have a big stack. \$\endgroup\$ – cat Jun 28 '16 at 13:34
  • 1
    \$\begingroup\$ Aha! That's funny. It is not that your machine has so little memory space that AWK gives up and segfaults immediately, it's that you have so much memory that AWK doesn't cause the kernel to kill it but instead tries to address so much memory that its virtual machine eventually segfaults. I only have a paltry 6 GB of RAM :P \$\endgroup\$ – cat Jun 28 '16 at 16:32
  • 1
    \$\begingroup\$ It's not wrong at all, I think recursing forever and possibly forcing a shutdown is a perfectly acceptable error \$\endgroup\$ – cat Jun 28 '16 at 16:52
2
\$\begingroup\$

PowerShell, 36 35 Bytes

param($a)$a.length/($a-cne'google')

This blatantly abuses PowerShell's dynamic casting and uses xnor's trick for dividing by zero. In PowerShell, this is a terminating error and halts execution tossing a most excellently-verbose error (the error, at 242 characters, is over 6.5x the size of the function itself)

Attempted to divide by zero.
At line:1 char:11
+ param($a);$a.length/($a-cne'google')
+           ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], RuntimeException
    + FullyQualifiedErrorId : RuntimeException

Saved a byte thanks to ConnorLSW

\$\endgroup\$
  • \$\begingroup\$ you can use param($a)$a.length/($a-cne'google') to skip using the the !, saving one byte. \$\endgroup\$ – colsw Nov 29 '16 at 10:57
  • \$\begingroup\$ @ConnorLSW Indeed. Thanks. \$\endgroup\$ – AdmBorkBork Nov 29 '16 at 15:54
2
\$\begingroup\$

PHP, 48 bytes

eval((google==$s=$argv[1])."echo strlen(\$s);");

php -r '<code>' google -->

Parse error: syntax error, unexpected 'echo' (T_ECHO) [...] in eval()'d code on line 1


54 bytes for a function:

function g($s){eval((google==$s).'echo strlen($s);');}
\$\endgroup\$
2
\$\begingroup\$

JavaScript, 25 bytes

p=>p=='google'?_:p.length
\$\endgroup\$
  • \$\begingroup\$ “However, if the given string is google (lowercase), it will cause an error.” – Will this? \$\endgroup\$ – manatwork Nov 29 '16 at 15:15
  • \$\begingroup\$ Now it matches the challenge's requirement. Sadly the generic expectation is the solutions to be either full programs or functions. In both cases the input and output has to be handle either explicitly by the code or implicitly by the interpreter. So you can not assume your code will find data in some global variable. \$\endgroup\$ – manatwork Nov 29 '16 at 15:38
  • \$\begingroup\$ You can make this valid in one of two ways: 1. Make it into a full program with input and output: g=prompt();if(g!='google')alert(g.length);else throw 0 2. Make it into a function: function(g){if(g!='google')return g.length;else throw 0} \$\endgroup\$ – ETHproductions Nov 29 '16 at 16:44
  • \$\begingroup\$ Also, you don't have to explicitly throw an error; calling some undefined variable, such as _, will do the trick. \$\endgroup\$ – ETHproductions Nov 29 '16 at 16:44
2
\$\begingroup\$

PHP, 56 bytes

function google($i){echo strlen($i)/(__FUNCTION__!=$i);}

Yes, it's a bit long, but I feel this is really in the spirit of the question. You really mustn't google google when google is the actual function's name.

The constant __FUNCTION__ holds the name of the function, which in this case is google. The rest of the functiondisplays the length of the input $i divided by 1 if $i is not google, or by 0 if it is. The latter throws an error.

Try it at Repl.it!

\$\endgroup\$
2
\$\begingroup\$

Pyth - 15 bytes

?qz"google"'0lz

My favorite part of this is how I error. I use the ' function which takes a string, but pass 0, which is not a string.

\$\endgroup\$
1
\$\begingroup\$

CoffeeScript, 36 bytes

f=(x)->throw 0if'google'==x;x.length
\$\endgroup\$
1
\$\begingroup\$

Emacs Lisp, 43 bytes

(lambda(s)(if(equal s"google")*(length s)))

Throws the error (void-variable *) for any string that equals google.

\$\endgroup\$
  • \$\begingroup\$ @FryAmTheEggman I'm sorry, I just wrote the explanation wrong, the code is correct. \$\endgroup\$ – nanny Sep 28 '15 at 18:55
1
\$\begingroup\$

STATA, 44 bytes

pr de a
if"google"==`0' f
di length(`0')
end

prints "unrecognized command: f" when input is "google"

\$\endgroup\$
1
\$\begingroup\$

Perl5, 48 bytes

sub google{map{eval,-7+length}qq~&{"::$_[0]"}~}

google("google") and google will google("google").

Try it:

perl -e 'sub google{map{eval,-7+length}qq~&{"::$_[0]"}~} print google @ARGV' google

47 bytes

The following is one char shorter, but more fiddly on the command line:

sub google{map{eval,-6+length}qq~&{"'$_[0]"}~}
\$\endgroup\$
1
\$\begingroup\$

F#, 33 Characters

function"google"->0/0|s->s.Length

When "google" is provided as input, it produces a DevideByZeroException.

Usage:

let g = function"google"->0/0|s->s.Length

g "bing"   // 4
g "google" // DivideByZeroException
\$\endgroup\$
1
\$\begingroup\$

Java 1.8, 33 bytes

(s)->s.length()/(s=="google"?0:1)

Explanation

The lambda takes a String named s, finds the length, and if it isn't "google", divides it by one, otherwise dividing it by zero and causing an Exception.

Usage

Note that java.util.function.Function has to be imported.

Function<String, Integer> f = (s)->s.length()/(s=="google"?0:1); //Assign function to variable
    //Note that java type inferencing automatically handles the String type

System.out.println(f.apply("elgoog")); //Prints 6
System.out.println(f.apply("google")); //ArithmeticException: Divide by zero
\$\endgroup\$
  • \$\begingroup\$ As far as I know, required imports need to be counted in the score, so your full code would be the import and the function. \$\endgroup\$ – Alex A. Sep 29 '15 at 15:53
  • \$\begingroup\$ @AlexA. The thing with Java is that lambdas are weird- the question only asked for a function, and the lambda is a function. However, Java needs to squeeze the function into a functional interface with the same method signature (accepts string, returns int), and the Java.util.function.Function interface fits the bill. However, the full function is provided. (Also see codegolf.stackexchange.com/a/58981/41505) \$\endgroup\$ – Daniel M. Sep 29 '15 at 16:31
  • \$\begingroup\$ You are going to have to change == to .equals unless I'm missing something with java 8 \$\endgroup\$ – jlars62 Oct 2 '15 at 16:55
  • \$\begingroup\$ It worked for me using the provided implementation. It may be a subtle difference between String objects and literals, but it works for me \$\endgroup\$ – Daniel M. Oct 2 '15 at 17:08
1
\$\begingroup\$

Lua, 47 bytes

print(assert(arg[1]~="google")and arg[1]:len())

Throws "assertion failed" if it's "google"

\$\endgroup\$
1
\$\begingroup\$

golflua, 25 characters

\g(s)?s=="google"e""$~#s$

Sample run:

bash-4.3$ golflua -e '\g(s)?s=="google"e""$~#s$ w(g("google"))'
golflua: (command line):1: 
stack traceback:
        [C]: in function 'e'
        (command line):1: in function 'g'
        (command line):1: in main chunk
        [C]: in ?

bash-4.3$ golflua -e '\g(s)?s=="google"e""$~#s$ w(g("yahoo"))'
5
\$\endgroup\$
1
\$\begingroup\$

PHP, 41 bytes

Because the division by zero is overused in the already existing answers, I tried to come up with something else (sacrificing 3 bytes):

<?=strlen($x=$argv[1])+log($x!="google");

It's not a function (the task explicitly asks to write a function) but it can be invoked from the command line in a functional manner:

$ echo '<?=strlen($x=$argv[1])+log($x!="google");' | php -- bing
4

$ echo '<?=strlen($x=$argv[1])+log($x!="google");' | php -- google
-INF

It doesn't produce an error when the argument is google but it doesn't display the length of the string google either. However it displays -INF (i.e. minus infinity) and this value can be considered an error for a function that returns a length (which, by definition, is a count, i.e. a non-negative number).

A 38 bytes PHP solution using division by zero:

<?=strlen($x=$argv[1])/($x!="google");

It can be invoked in the same way as above. When the argument is google it displays a PHP warning.

\$\endgroup\$
  • 1
    \$\begingroup\$ You get a +1 from me for the division-by-zero, clever! But a -1 for not making it a function as the topic states :) \$\endgroup\$ – Martijn Sep 29 '15 at 12:53
  • 1
    \$\begingroup\$ -2 bytes: The quotation marks are unnecessary. \$\endgroup\$ – Titus Nov 29 '16 at 15:48
1
\$\begingroup\$

Clojure - 41 40 bytes

(defn g[s](if(= s"google")(g)(count s)))

Attempts to call itself with zero arguments for the input "google".

> (g "bing")
4
> (g "google")
clojure.lang.ArityException: Wrong number of args (0) passed to: sandbox10419$g
\$\endgroup\$
1
\$\begingroup\$

Swift, 71 Bytes

Short but lame:

print({assert($0 != "google");return $0.characters.count}(readLine()!))

Longer (75) but not lame:

print({{0/$0}($0.hash&-0x20f4f91ecf8d43)^$0.characters.count}(readLine()!))

The second one doesn't use any String literal. Works by subtracting the hash value of the input string by the "google" hashValue. Then it divides 0 by this value, resulting in a runtime error when it's 0 (0/0 = undef.) but in all other cases the result is 0 (0/x = 0). This result gets XOR'd by the character count in the String.

\$\endgroup\$
1
\$\begingroup\$

Hassium, 52 Bytes

func g(s){if(s=="google")throw("");return s.length;}

Run and see expanded here

\$\endgroup\$
  • 1
    \$\begingroup\$ func g(s)return(s == "google")?throw():s.length; is a bit shorter. \$\endgroup\$ – Dennis Oct 1 '15 at 5:42
  • \$\begingroup\$ @Dennis Actually, it is 32 bits shorter. \$\endgroup\$ – Ismael Miguel Oct 5 '15 at 2:17
1
\$\begingroup\$

Haskell, 24 characters

g n|n/="google"=length n

"Unexhaustive patterns" if you pass it "google".

\$\endgroup\$
1
\$\begingroup\$

C - 72 characters

g(char*s){char*p=s;for(;*p=="google"[p-s];p++);for(;*p;p++);return p-s;}

output:

g("test")    # 4
g("googles") # 7
g("google")  # Segmentation fault (core dumped)

This solution is pretty straightforward, no tricky bit manipulation (but also no library functions): match the string google in the first loop, and if there are still characters left continue to the end of the string. Return the difference between the pointers as the length.

The bug: given the string "google" the first loop does not terminate, causing it to overrun and dereference memory locations until it segfaults.

It also has a bonus bug: if you feed it the string "google\0" it succeeds but returns the wrong length.

\$\endgroup\$
1
\$\begingroup\$

JS, 48 bytes

An improvement over Beta Decay's JS:

function f(g){g=="google"?g.s.s:alert(g.length)}

The original for reference:

function f(g){if(g=="google")throw 1;alert(g.length)}
\$\endgroup\$
1
\$\begingroup\$

Burlesque, 25 bytes

J"google"!={L[}j{vvg_}jie

Code can be run at Anarchy Golf checker. Click 'use form' choose 'burlesque', copy/paste code into the form, and input goes under it. Run.

\$\endgroup\$
  • \$\begingroup\$ You can shorten {L[} to qL[. q is a syntax prefix as a shortcut for Blocks that only contain one value. \$\endgroup\$ – mroman Nov 15 '18 at 12:36
1
\$\begingroup\$

XPath 2.0 (if you treat an XPath expression as a function with the context item as its argument):

Simple solution:

if (.='google') then error() else string-length()

If you treat returning an empty sequence as an error, then

string-length(.[.!='google'])
\$\endgroup\$
1
\$\begingroup\$

bash, 55 51 34 bytes

Thanks @manatwork!

[ "$1" != google ]&&echo ${#1}||0

It prints command not found if $1 is google.

\$\endgroup\$
  • \$\begingroup\$ Shorter? [ "$1" != google ]&&echo ${#1}||0 \$\endgroup\$ – manatwork Sep 30 '15 at 9:16
  • \$\begingroup\$ @manatwork Shorter & beautiful! \$\endgroup\$ – Tarod Sep 30 '15 at 10:30
1
\$\begingroup\$

CoffeeScript, 32 bytes

g=(s)->(s if s!='google').length

To call:

g('bing') # returns 4
g('google') # TypeError: Cannot read property 'length' of undefined

The expression (s if s!='google') evaluates to undefined if the value of the argument s is google, otherwise it gives the argument itself. In the former case, JavaScript throws an error when attempting to access a property of undefined.

\$\endgroup\$
1
\$\begingroup\$

PowerShell, 42 bytes

function g($x){$x.Length/($x-ne'google')}
\$\endgroup\$
1
\$\begingroup\$

Powershell, 60

$f={param([string]$s);if($s-eq'google'){throw $s};$s.Length}

Usage:

PS> & $f google

Throws an exception.

PS> & $f bing

Returns 4

Shortest I could come up with :(

\$\endgroup\$

protected by mbomb007 Sep 30 '15 at 18:27

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.