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.

• @Geobits That is simply a test to see if I will google Google, which I will not. :D – rybo111 Sep 28 '15 at 16:33
• Does the function need to be case sensitive? Should it throw given 'gOOgle'? – AXMIM Sep 30 '15 at 22:07
• 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! – Craig Oct 1 '15 at 4:18
• 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. – Poke Aug 1 '18 at 19:52

# Stuck, 16 Bytes

s_l1u"google"=-/


Following a similar method to most people, will cause a divide by 0 error on "google" being input.

# Japt, 14 bytes

U¥goog¤?Þ:Ul


Try it here!

### Explanation

U¥goog¤?Þ:Ul
U                     // U is the input
¥                    // ¥ is the Unicode shortcut for ==
                   // backticks are used to uncompress goog¤
Þ           // An undefined variable
Ul        // l is a built-in that returns the length of U
// Implicit: output result of last expression

• Can you explain? – Adám Jan 10 '17 at 23:10
• @Adám Added an explanation :) – Oliver Jan 10 '17 at 23:40

# Zsh, 18 bytes

<<<$#1>$1


Try it online!

Explanation:

• <<<$#1: • $1: the input
• #: length
• <<<: and print it
• >$1: redirect that output to a file called the input • ^google: try and find a file with any name other than google • <: and print its contents So if the file created was called google, then no file will be found and an error message will appear. But if the file was called anything else, then its contents is the length of the input, and it will be outputted. # C# .NET, 65 bytes int g(string s){return(s!="google")?s.Length:(1/int.Parse("0"));}  Test: Console.WriteLine(g("str")); Console.WriteLine(g("google"));  • with C# 6.0 you can save a few characters by doing an expression-bodied method: int g(string s)=>s!="google"?s.Length:(1/int.Parse("0")); – DLeh Sep 28 '15 at 19:18 • also you could cause an exception by recursing, eventually you'll get a stack overflow int g(string s)=>s!="google"?s.Length:g(s); – DLeh Sep 28 '15 at 19:19 • You can make it crash faster by just calling int.Parse(""). Although the infinite recursion strategy would be even shorter. – sara Sep 29 '15 at 9:23 • @kai Something like "".Length is shorter than int.Parse(""). – Bob Sep 29 '15 at 12:41 • @Bob "".Length just returns 0, it doesn't throw. – DLeh Oct 1 '15 at 13:03 # PHP 5.4+, 40 49 bytes This one is quite unexpectedly long. function g($x){echo[strlen($x),[]][$x==google];}


To run it, just pass a value:

g($argv[1]);  Test-cases:$php google.php googlea
7
$php google.php google Notice: Array to string conversion in [...][...] on line 1 Array I'm not sure if this can ve considered an error for this challenge or not. One could use the over-used boring method: function g($x){echo strlen($x)/$x==google;}


Which gives me a size of only 43 bytes.

As an alternative, one could use an exit error code, using the exit construct, for also 49 bytes:

function g($x){exit($x==google?strlen($x).'':1);}  All values between 1 and 254 are valid error codes that PHP uses when exiting. • You could use function g($x){echo$x==google?a():strlen($x);} which is 46 bytes (3 bytes shorter) and throws an actual error and not just a warning. Also your second example function g($x){echo strlen($x)/$x==google;} should be: function g($x){echo strlen($x)/($x!=google);}. / has a higher precedence than == and you have to switch it to !=as well to make it work. – insertusernamehere Nov 16 '15 at 22:53

# Common Lisp, 50 48 bytes

(defun g(s)(if(equal s"google")(g s)(length s)))


Ungolfed:

(defun g(s)                ; Define a function g with one argument s
(g s)              ; Then recurse!
(length s)         ; Else, return the length of s in characters
)
)


Defines a function g that accepts one string as input. If it is not exactly 'google', then it returns the length. Otherwise, it will call itself on the same string, creating an infinite recursive loop and eventually causing a stack overflow error.

Usage (inside an interactive CLISP shell):

>(load "google.lsp")
>(g "foo")
3
>(g "Lisp is cool!")
13
*** - Program stack overflow. RESET


This is pretty long compared to the others, but using recursion seemed fitting for Lisp.

• This won't cause a stack overflow in some Common Lisp implementations (CCL and SBCL won't overflow). – nanny Sep 28 '15 at 20:57

# Scala, 48

def g(s:String)=if(s=="google")0/0 else s.length


To call:

 g("bing")      //> res1: Int = 4
g("google")    //> java.lang.ArithmeticException: / by zero

• you can use an anonymous function, and shave off 4 characters. also, it will be more neat, IMHO, to use ??? rather than 0/0. – Jacob Mar 27 '16 at 14:55

# bash + coreutils, 57493836 33 bytes

[ "$1" = google ];expr${#1} / $?  Calling it with google produces expr: division by zero. The quotes around$1 are required in order to handle the empty string correctly.

The use of ${#1} is shamelessly stolen from Tarod's answer. • Good! But I think you're mixing bash & linux commands. If you want to, check my answer where I'm using bash to count characters. Happy coding! :) – Tarod Sep 29 '15 at 21:57 • @Tarod You're right, I should have said bash + coreutils. Combining your use of Bash to count the length of the input with my use of expr allows a shorter answer than either though - see my edit. – Ben just now edit – Ben Sep 29 '15 at 22:22 • Amazing! :D I'm going to upvote you! Good job, Ben! :) – Tarod Sep 30 '15 at 6:08 • BTW, I think you should set a new title for your answer. Just 'bash'. – Tarod Sep 30 '15 at 11:55 • I don't think so - expr seems to be part of coreutils. – Ben Sep 30 '15 at 13:16 # O, 20 characters {."google"={@}{.e}?}  Sample run: bash-4.3$ java xyz.jadonfowler.o.O <( echo '{."google"={@}{.e}?} :f "yahoo" f o' )
5

bash-4.3$java xyz.jadonfowler.o.O <( echo '{."google"={@}{.e}?} :f "google" f o' ) java.lang.ArrayIndexOutOfBoundsException: Can't pop from empty stack! at xyz.jadonfowler.o.Stack.pop(O.java:980) at xyz.jadonfowler.o.O.parse(O.java:407) at xyz.jadonfowler.o.CodeBlock.run(O.java:1031) at xyz.jadonfowler.o.O.parse(O.java:735) at xyz.jadonfowler.o.CodeBlock.run(O.java:1031) at xyz.jadonfowler.o.O.parse(O.java:99) at xyz.jadonfowler.o.O.runFile(O.java:37) at xyz.jadonfowler.o.O.main(O.java:20) java.lang.ArrayIndexOutOfBoundsException: Can't pop from empty stack! at xyz.jadonfowler.o.Stack.pop(O.java:980) at xyz.jadonfowler.o.O.parse(O.java:425) at xyz.jadonfowler.o.O.runFile(O.java:37) at xyz.jadonfowler.o.O.main(O.java:20)  # Scala, 36 34 30 29 characters s=>(Set(s)-"google").max.size  Calling this function on "google" produces java.lang.UnsupportedOperationException: empty.max • Nice idea! However, I'm afraid it does not compile, one must declare s's type: (s:String)=>... When I copy-paste it to scala's REPL I get <console>:1: error: ';' expected but '=>' found. – Jacob Mar 27 '16 at 14:58 • @Jacob it compiles if the type of s can be inferred from the context, e.g.: val s: String => Int = s=>(Set(s)-"google").max.size. – Ben Mar 27 '16 at 21:57 • If you want us to use it like that, you must add val s:String=>Int= to your answer. The answer should be a valid Scala expression as-is. – Jacob Mar 28 '16 at 2:06 • @Jacob it is a valid Scala expression as-is: an anonymous function is a perfectly valid self-contained answer. Valid Scala expressions aren't only those that can be pasted into the Scala REPL without context. The question asks for a function that takes a string and returns an integer: in contexts in which such a function is expected, the answer will compile. However, feel free to take this to Meta. – Ben Mar 28 '16 at 8:48 # Matlab, 50 51 bytes Thanks to @rayryeng for removing 1 byte. This uses an anonymous function, and exploits the fact that the error function with an empty input issues no error. It's noteworthy that the error given for input 'google' is meta: it's an error using the error function. @(s)eval('error(find(strcmp(s,''google''))),numel(s)')  Examples: >> @(s)eval('error(find(strcmp(s,''google''))),numel(s)') ans = @(s)eval('error(find(strcmp(s,''google''))),numel(s)') >> ans('abcd') ans = 4 >> @(s)eval('error(find(strcmp(s,''google''))),numel(s)') ans = @(s)eval('error(find(strcmp(s,''google''))),numel(s)') >> ans('google') Error using error The message must be specified as either a string or a message structure. Error in @(s)eval('error(find(strcmp(s,''google''))),numel(s)')  • You could potentially save a byte if you used strcmp! – rayryeng Oct 1 '15 at 15:22 • Slight change to your error statement... still an isequal there! – rayryeng Oct 1 '15 at 16:38 • @rayryeng Oops... I should have pasted the new thing from scratch! Corrected, thanks – Luis Mendo Oct 1 '15 at 16:41 ## Perl 6, 19 bytes {.comb/!/^google$/}


.comb returns list of characters in string (which in numeric context is a number of characters, I use this instead of .chars because it's shorter). Because there is nothing before a period, Perl 6 assumes you wanted to call a method on $_. This is divided by a negated match on regex ^google$ with implicit $_ variable. If it matches, the value becomes 0, and Perl 6 errors because of a division by zero. Example: > {.comb/!/^google$/}("qwerty")
6
> {.comb/!/^google$/}("google") Attempt to divide 6 by zero using div in any interactive at src/Perl6/Compiler.nqp line 62  # Java, 8468 37 bytes b->b.equals("google")?1/0:b.length();  This is a java.util.function.Function<String, Integer> that divides by 0 if b is the string google. # Julia, 25 bytes x->length(x)[x!="google"]  Try it online! # CoffeeScript 43 bytes (g)->return g.length if g!="google";throw-1  Makes an anonymous function that throws -1 if the string is "google", and returns it's length otherwise. Not as obfuscated as I wanted, though. Link to the online testing environment. Another variation, 1 byte longer: (g)->if g!="google"then g.length else throw-1  • Nah, too late. There is already a better answer in CoffeeScript... – Bojidar Marinov Sep 28 '15 at 18:15 ## Lua, 42 Bytes This challenge has made me realize how hard it is to cause an error in Lua. x=io.read()print(x~="google"and #x or t())  Takes an input and if that input isn't google than print the length of the input, if not call a function t which doesn't exist, throwing an error. • Can shave off one byte by removing the space before the '#x'. – ouflak Nov 22 '18 at 16:27 • Can shave off two more bytes on top of that by saying 'or~x' instead of 'or t()'. Throws a conversion error. – ouflak Nov 22 '18 at 16:38 ## Prolog – 32 bytes "google"*_:-x. X*Y:-length(X,Y).  Defines a predicate (*)/2 that throws ERROR: */2: Undefined procedure: x/0 for the input "google": ?- "bing" * Length. Length = 4. ?- "google" * Length. ERROR: */2: Undefined procedure: x/0 Exception: (8) x ? no debug  • Ha nice! I tried a Prolog one and only got 56 chars (I'm a beginner). What does the * do? – whitfin Oct 6 '15 at 8:21 • @zackehh *, +, ... are valid names for predicates. They have to be written in infix notation and are quite handy for golfing because you can omit the parentheses and the comma for a predicate with two argument. a(A,B):-A is B.A*B:-A is B.: 3 bytes saved for every invocation. – kay Oct 6 '15 at 11:22 • learn something new every day, thanks! ;) – whitfin Oct 6 '15 at 15:11 # rs, 31 bytes ^(google)|(.*)$/((^^\2))^^(1\1)


In rs, ^^ is the length and repetition operator. Used in the unary form, it will get the length of the following text (^^\2). Used in binary form, it will repeat the LHS RHS times ((^^\2))^^(1\1).

Take the input bing. The input is not google, so the second group will match, not the first. Once the substitutions take place, the result is ((^^bing))^^(1). ^^ gets the length to result in (4)^^(1), and the result gets repeated 1 time to result in 4.

However, if the input is google, the first group will match. That will result in ((^^))^^(1google) after substitutions. ^^ will just get the length of the empty string (0), so the result after ^^ is applied will be (0)^^(1google). Now the repetition operator can do its work...or not. See it will try to repeat 0 1google times. As 1google isn't a number, the output will be:

Traceback (most recent call last):
File "c callback", line 6, in <module>
File "<string>", line 5, in <module>
File "<string>", line 167, in main
File "<string>", line 125, in run
File "<string>", line 72, in expand
ValueError: invalid literal for int() with base 10: '1google'


Live demo. (Put the input text in the box at the bottom left.)

# PHP error via a warning(), 62, 52 46 bytes

I feel dirty for these, but it isn't about pretty:

function g($s){echo$s!=google?strlen($s):g();}  This will give "Warning: Missing argument 1 for g()" when you insert 'google', thought that was funny. function g($s){echo$s!=google?strlen($s):die(err);}

function g($s){if($s!=google){return strlen($s);}die(error);} # PHP error as string, 46 bytes function g($s){echo$s!=google?strlen($s):err;}


String dont have to be quoted (but should be!)

You can run these via the commandline using g($argv[1]);, or via an older PHP version's register_globals method as an GET g($_GET['string']) or whichever :)

• If it is to play a bit 'dirty', you could use err instead, since it is a common abbreviature – Ismael Miguel Sep 29 '15 at 14:14
• You mean instead of the string 'error'? I wan't too sure about wether to count those bytes, so I just left it there, it's about the logic anyways. – Martijn Sep 29 '15 at 14:16
• It is. But hey, everybody knows what err means, and you save 2 bytes! Some used undefined variables to show errors. Why can't you use an abbreviation!? – Ismael Miguel Sep 29 '15 at 14:24
• I guess your right, changed it. Still thinking of another method. I could simply call a undefined function, would safe me even more, but I tough of that as cheating – Martijn Sep 29 '15 at 14:57
• That's quite a funny alternative! I wouldn't have though of that! – Ismael Miguel Sep 30 '15 at 9:10

# C# 4.0, 51 bytes

int g(string s){return s.Length/(s!="google"?1:0);}

Sample:

string userInput = Console.ReadLine();
Console.WriteLine(g(userInput));


Output:

// "pogi" 4


# C++14, 47 bytes

[](auto s){return s=="google"?throw:s.size();};


This is a generic lambda expression in C++14. It simply checks if the argument (string) is "google" and calls terminate if it is - else it returns the length of the string.

It can be called as such:

[](auto s){return s=="google"?throw:s.size();}("some_string"s);


Zereges has a very similar answer here written in C++11. Since this was C++14 it was O.K. by him for me to post this.

## Befunge-93, 59 characters

<+1\_v#+1:~
vp00$< <*_v#:\ v_v>$"google"*****-!#
< >00g.@>1


Befunge has no way to actually throw an error, so I just push an "infinite" number of 1s onto the stack. An error will happen somewhere eventually...

### Explanation

Anyway, this works by reading in the input and simultaneously keeping track of its length.

<+1\_v#+1:~


This length is stored at location 0,0.

vp00$<  The remaining numbers are multiplied together. <*_v#:\  This is then compared to the product of "google". v_v>$"google"*****-!#


If they are the same (i.e., if their difference is zero), then the "error" is thrown. Otherwise, the value stored at 0,0 is retrieved and outputted.

< >00g.@>1


# PHP 5.4, 81 bytes

<?function g($s){eval('if(isset('.($s==google?"$s":'$s').'))print strlen($s);');} // following added for easy testing, not included in bytes count g($argv[1]);


Everyone's favourite error when searching for Google! Didn't work out quite as obfuscated as I'd hoped...

Usage:

php 58891.php 'test'
4
# error

• Just thought I'd point this out: the challenge ID is 58891, not 85591. Otherwise, good job! – clapp Oct 6 '15 at 1:59
• @ConfusedMr_C hah, good spot! I'd like to say I did that deliberately, but that would definitely be a lie! – Dom Hastings Oct 6 '15 at 4:43

# OCaml 42 bytes

This does exactly what is asked1: it returns a function which returns the length of its (string) argument, except when the argument is "google", in which case it fails with:

Exception: Division_by_zero.

function"google"->0/0|s->String.length s;;


It doesn’t provide any way to actually call that function, though. In order to do that, you could either write:

(function"google"->0/0|s->String.length s)"some string";;


or you could, you know, give it a name.

let f=function"google"->0/0|s->String.length s;;
f"bing";;


Unpacked, this would give:

(* let f be function with one argument. *)
let f = function
(* If the argument matches exactly "google", return 0/0 *)
| "google" -> 0 / 0
(* If no previous cases were a match, give your argument the name 'string'. *)
(* and return its length. *)
| string   -> String.length string
;;
(* Call f with "bing" as it’s argument. *)
f "bing";;


The type of 0 / 0 is int, so the function is correctly typed as string -> int.

1. Well, I must admit I have not checked these pesky Unicode details.

# O, 17 bytes

{e\"google"=L@N?}

To use this function:

"wow" {e\"google"=L@N?} ~

Explanation:

e\               Get the length of the string and swap it on the stack
? If
L@    True (it is google): Rotate top three elements on the stack, throwing an underflow error
N   False (it is not google): do nothing
Length is printed out automatically


# PARI/GP, 21 19 bytes

x->#x/(x!="google")


Example:

? g = x->#x/(x!="google")
? g("bing")
%2 = 4
***                 ^-----------
***                    ^--------------
*** _/_: impossible inverse in dvmdii: 0.
***   Break loop: type 'break' to go back to GP prompt
break>


# Ruby, 4632 29 bytes

->s{b=Hash.new(0);b['google']=nil;b[s]+s.size}


New shortened approach:

->g{(g.to_a-['google'])[0].size}


Reduced 3 bytes with manatwork's suggestion

->g{([g]-['google'])[0].size}

• Couple of tips to shorten it: new(0)new 0; nilp. Possibly more tips to shorten it: Tips for golfing in Ruby. – manatwork Nov 26 '15 at 15:44
• Found different approach. Thanks anyway :) @manatwork – Vasu Adari Nov 26 '15 at 15:59
• Interesting. Which Ruby version? The 2.1.5 I use has no String#to_a method. But with the shorter [g]-['google'] works. – manatwork Nov 26 '15 at 16:02
• I missed it. Thank you very much :). My ruby version is 2.0.0p576. – Vasu Adari Nov 26 '15 at 16:08

# Japt, 16 14 bytes (non-competing)

U¥goog¤?Δ:Ul


Throws reference error on input of "google". Try it online!

• Nice! Two tips: 1) "google" can be compressed to goog¤, wrapped in backticks. 2) == can be compressed to ¥. – ETHproductions Nov 26 '15 at 15:36
• Totally ignored compression. I have only scratched the surface of your language @ETHproductions, and thought this may be a great starting point for it. The \u<hex> shorthands are easily missable, better put it inside the docs. – noisyass2 Nov 27 '15 at 2:24
• I've added a section on Unicode shortcuts in the online interpreter. @ThomasKwa You are correct. I've edited the post. – ETHproductions Dec 4 '15 at 17:14

# 05AB1E, 10 bytes (non-competing)

Non-competing, since the language postdates the challenge.

Code:

g“Š¹“¹Q</Ä


Explanation:

g           # Take the length of the implicit input
“Š¹“       # Compressed version of "google"
¹Q     # Take the first input again and check if equal to "google"
<    # Decrement on the bool
/   # Divide the length by the value
Ä  # Take the abstract value of the result
# This is then implicitly printed


Try it online!. When the input is google, nothing is printed due to a division by zero exception.

• *absolute value – Oliver Ni Feb 6 '17 at 2:08

# Gogh, 20 bytes

÷GD$"google"={¤+}¦:$


Usage:

./gogh o '÷GD$"google"={¤+}¦:$' "google"


### Explanation

             “ Implicit input                                              ”
÷            “ Duplicate the input                                         ”
GD           “ Push a range of [1, len(input)]                             ”
$“ Rotate input to the TOS ” "google"= “ Determine equality ” {¤+}¦: “ Error if equals "google" (empties stack and tries addition) ”$            “ Leave the length on the stack                               ”
“ Implicit output                                             ”

• Note: this answer is non-competing. – Zach Gates Mar 26 '16 at 3:39
• Gogh is epic. Just saying. – Rɪᴋᴇʀ Mar 26 '16 at 3:53