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

1
\$\begingroup\$

ECMA6,30

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

Since a string length of -1 is an error I think this is a valid answer in Javascript (ECMA6).

I was initially inspired by the python trick of causing a division by zero mentioned near the top. However this does not work in Javascript because you can divide by zero and get "Infinity" without throwing an error so I looked into other options.

This works in Chrome you can copy this into the dev console and then run it by calling g("some string here"). I assume any other browser that has partial support for ECMA6 should be able to run it.

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

C++, 81

int l(char *s){int b=0,i=0;do{b=s[i]^"google"[i]?1:b;}while(s[i++]);return--i/b;}

Divides by 0 on "google". This is my first C++ golf, so any tips would be welcome.

^ is used like !=. b is equal to 1 when the string is not "google", 0 if it is. So i/s will result in i/0.

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

TSQL 2012, 87

CREATE FUNCTION g(@p CHAR(9))RETURNS INT AS BEGIN RETURN IIF(@p='google',@p,LEN(@p))END

How to use :
SELECT dbo.g('gogle')
-- return 5

SELECT dbo.g('google')
--return Conversion failed when converting the varchar value 'google ' to data type int.

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

><>, 108 bytes

i:"g"=1-?v\]
i:"o"=1-?v\
i:"o"=1-?v\
i:"g"=1-?v\
i:"l"=1-?v\
i:"e"=1-?v\
i:01-=1-?v\
>i:0)?v~l n;
^     <  <

Try it here

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

AHK, 75 bytes

Inputbox,s
MsgBox % a(s)
a(b)
{
if (b!="google")
return StrLen(b)
throw b
}

there is no proper stdin and stdout support in ahk so im using inputbox and msgbox, the concept is the same tho.

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

Go: 92, 63, 59 bytes with panic instead of error

func g(s string)int{if s=="google"{panic(0)};return len(s)}
\$\endgroup\$
  • 2
    \$\begingroup\$ Welcome to PPCG! This is a codegolf challenge, so you should remove all spaces and newlines to get a much lower byte count. You won't get many upvotes, if you post such an ungolfed version. \$\endgroup\$ – Jakube Sep 30 '15 at 10:09
  • \$\begingroup\$ thanks for the welcome. But, Go doesn't allow one to stray too far away from the standard formatting, I'll update the answer in a minute \$\endgroup\$ – user45561 Oct 1 '15 at 14:07
  • 1
    \$\begingroup\$ using panic() instead of returning error saves some bytes: func g(s string)int{if s=="google"{panic("")};return len(s)} (60 bytes) \$\endgroup\$ – Fabian Schmengler Oct 3 '15 at 16:59
1
\$\begingroup\$

><>, 47 bytes

i:0(?\
?\ln;>~l6=
"\ "elgoog
!\{=?!\l ?
=< ;n6<

Here's a line-by-line breakdown:

i:0(?\

A standard ><> input loop, pushes the input string followed by -1.

?\ln;>~l6=

Starts at >. Discards the -1, checks the length is equal to 6. If it is, move to next line, otherwise gets the length, prints, and exits.

"\ "elgoog

Starts at \. Pushes 'google' in reverse. If the input string was google, stack is now googleelgoog

!\{=?!\l ?

Starts at the first \. Rolls the stack one to the left. If top two elements aren't equal, moves to next line. Otherwise, if the stack is length is zero, the strings are equal, so also step to next line.

=< ;n6<

Starts on the 1st < if the string was 'google'. This is only reached when the stack is empty, so attempting to pop any number of values will cause an error - in this case, = is used. If the string wasn't 'google', outputs 6 and exits.

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

J, 18

   #`^@.('google'-:])

Usage:

   #`^@.('google'-:]) 'googl'
5
   #`^@.('google'-:]) 'google'
|domain error
|       #`^@.('google'-:])'google'

Explanation

Count (#) if y does not match (-:]) the string 'google', but if it does match, compute e to the power of the string 'google', which is an error.

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

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.
\$\endgroup\$
1
\$\begingroup\$

Perl, 49 46 39 31 bytes

sub g{sub g{$_=pop;y///c/!/^google$/}}

Call with g(string), print with print g(string).

How it works

The ternary operator only evaluates the expression if the condition is met. So when the input isn't google, it simply returns the original string and passes it on to length. However, is the input is google, it tries to divide by zero and causes this error:

Illegal division by zero at filename.pl line 1.

And as we all know, dividing by zero will break the internet (and the rest of reality).

Changes

  • Saved 3 bytes by changing return to print and removing unneeded parentheses.
  • Saved 6 bytes thanks to @manatwork, and saved an additional 1 byte by re-arranging my code.
  • Saved 8 bytes and fixed an error thanks to @Grimy.
\$\endgroup\$
  • \$\begingroup\$ Wouldn't save more by returning, but implicitly, without using the return keyword? sub g{length($_[0]=~"google"?1/0:$_[0])} \$\endgroup\$ – manatwork Sep 30 '15 at 18:13
  • \$\begingroup\$ @manatwork I'll add that in. Thanks! \$\endgroup\$ – ASCIIThenANSI Sep 30 '15 at 19:04
  • 1
    \$\begingroup\$ This will incorrectly raise an error for any string that contains “google” (e.g. “ungoogleable”). A shorter and more correct version would be: sub g{$_=pop;y///c/!/^google$/} \$\endgroup\$ – Grimy Oct 5 '15 at 11:32
  • \$\begingroup\$ @Grimy Thanks for pointing that out, I've added that in. \$\endgroup\$ – ASCIIThenANSI Oct 9 '15 at 20:21
1
\$\begingroup\$

Zsh and bc, 29 bytes

[ "$1" = google ];bc<<<$#1/$?

Sample output:

$ zsh not_google.sh oogle
5
$ zsh not_google.sh google
Runtime error (func=(main), adr=5): Divide by zero

 

Explanation:

The first command exits true (zero) when the argument equals "google" and false (one) otherwise. That exit code is stored in $? until another command completes, allowing us to divide by that number.

We then run bc (with input via herestring) to compute the length of the argument divided by that exit code. This is either length ÷ 1 (the length) or length ÷ 0 (an error).

An un-golfed version:

if [ "$1" = google ]; then
  divisor=0
else
  divisor=1
fi
length="${#1}"
echo "$length / $divisor" |bc

 


Bash and bc, 31 bytes

This uses the same logic, but bash can't handle $#1 without braces:

[ "$1" = google ];bc<<<${#1}/$?

 


Zsh and bc, 26 bytes (also errors on empty string)

This version also has an error when given an empty string, so I assume it doesn't count. It has the exact same output as the previous version (except when given an empty string or no argument).

bc<<<$#1/(0!=${#1#google})

Un-golfed version of 26 byte answer:

length="${#1}"                 # the length of the first argument
unprefix_google="${1#google}"  # google → "", googler → r, goog → goog, "" → ""
length_unprefix_google="${#unprefix_google}"

if [ 0 != "$length_unprefix_google" ]; then
  divisor=1                # $unprefix_google is an empty string
else
  divisor=0                # $unprefix_google is not empty
fi

echo "$length / $divisor" |bc
\$\endgroup\$
1
\$\begingroup\$

Java, 96 Bytes

This should work, but IDK for sure since I cant assess a computer at the moment:

Golfed:

 int g(String s){if(s.equals("google"))throw new
 IllegalArgumentException();return s.length();}

Ungolfed:

int g(String s){ 
    if(s.equals("google")) throw new IllegalArgumentException();
    return s.length(); }

I realize I could proably shorten this, let me know in the comments.

\$\endgroup\$
  • 1
    \$\begingroup\$ Actually, I could just divide the string google by a number and get some type-mistmatch error \$\endgroup\$ – Ashwin Gupta Dec 4 '15 at 17:45
  • \$\begingroup\$ Wouldn't a type mismatch be checked at compile time, not run time, because of type erasure? \$\endgroup\$ – cat Mar 25 '16 at 15:49
  • \$\begingroup\$ @tac probably. Could be a workaround through try catch \$\endgroup\$ – Ashwin Gupta Mar 25 '16 at 17:16
1
\$\begingroup\$

Go, 110 102 93 92 bytes

It makes sense to use a language developed by Google employees to Google Google!

note that this is actually a valid, compilable program, unlike the other go answer.

will take input forever until "google" is input:

package main
import."fmt"
func main(){a:=""
Scan(&a)
if a=="google"{panic(0)}
Print(len(a))}

example i/o:

bing
4
oogle
5
google
panic: 0

goroutine 1 [running]:
runtime.panic(0x480e60, 0xc21000a190)
        /usr/lib/go/src/pkg/runtime/panic.c:266 +0xb6
main.main()
        /home/cat/projects/go/src/not-google/main.go:10 +0x115
exit status 2

ungolfed:

package main

import . "fmt"

func main() {
    a := ""
    Scan(&a)
    if a == "google" {
        panic(0)
    }
    Print(len(a))
}

apparently i had forgotten that var a string is just "" aka empty string. sigh.

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

Milky Way 1.0.0, 18 bytes

This language was created after the challenge was posted.

'?{"google"b~z~y!}

Explanation

'                   # read input from command line
 ?{         ~ ~  }  # if-else statement
   "google"         # push "google" to the stack
           b        # == on top two stack items (input and "google")
             z      # non-existent opcode raises an exception
               y    # push the length of the TOS to the stack
                !   # output the TOS

Milky Way (current version), 18 bytes

'?{"google"b_z_y!}

Usage

The code is called via the command line as follows:

./mw <path-to-code> -i <input>
\$\endgroup\$
1
\$\begingroup\$

Lua, 42 bytes

function g(s)return #(s~='google'and s)end

This creates a function g that takes an argument s and (assuming it is a string) returns the length (#) of the result of the evaluation s~='google'and s, which equates to s if s is not 'google', or false if it is. Since there is no length of false, if s is google, this will error, else, it will return the length. Simple and effective.

I know there are other Lua answers, and that I could shorten this by using io.read(), but I'm going to disregard both of those for the same reason: they don't actually use functions, like the question specifically calls for.

If I'm wrong in that it doesn't need to be a function, we can cut this to 32 bytes by doing:

s=io.read()g=#(s~='google'and s)
\$\endgroup\$
1
\$\begingroup\$

jq, 39 characters

def g(s):s|length/({"google":0}[s]//1);

Sample run:

bash-4.3$ bin/jq -n 'def g(s):s|length/({"google":0}[s]//1); g("google")'
jq: error (at <unknown>): number (6) and number (0) cannot be divided because the divisor is zero

bash-4.3$ bin/jq -n 'def g(s):s|length/({"google":0}[s]//1); g("yahoo")'
5

On-line test:

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

Mathcad, 23 "bytes"

enter image description here

And it even works with foreign languages ...

enter image description here

Note: Mathcad displays errors by showing the expression in red; clicking on the expression shows the error message.

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

Rust, 41 chars

rust solution, provided by a friend who does have a rep of 10 to post (and asked me to post it on his behalf).

|x:str|{if x=="google"{panic!();}x.len()}
\$\endgroup\$
1
\$\begingroup\$

TI-83 Basic, 21 bytes

Simple solution. (Lowercase tokens are two bytes each).

length(Ans)/(Ans≠"google

Alternate solution (22 bytes):

If Ans="google
.
length(Ans

Alternate solution (23 bytes):

length(Ans)+0/(Ans≠"google
\$\endgroup\$
  • \$\begingroup\$ This is exactly what I posted in a comment siz months ago. Additionally, you aren't allowed to take input through Ans anymore; there's a meta post about it. \$\endgroup\$ – lirtosiast Mar 29 '16 at 21:45
1
\$\begingroup\$

Molecule (v5.6+), 16 bytes

I_"google"=?p¿#

Explanation:

I_"google"=?p¿#
I_              duplicate
  "google"=     add google and compare
           ?p¿  if true, do a primality test on "google"
              # get length

This way the program will error and shutdown if it does a primality test on a string.

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

Pyth, 12 bytes

/lznz"google

len(input())/input()!="google"

\$\endgroup\$
  • \$\begingroup\$ This isn't really working for me here. If I enter "Hello" It should return 5, but it returns {} 2.584962500721156, and if I enter "google" it doesn't cause an error. \$\endgroup\$ – DJMcMayhem Apr 26 '16 at 20:39
  • \$\begingroup\$ @DrGreenEggsandHamDJ Try it here \$\endgroup\$ – macleos Apr 26 '16 at 20:48
  • \$\begingroup\$ The spec asks for a function. This is a full program. \$\endgroup\$ – Dennis Nov 21 '16 at 0:21
1
\$\begingroup\$

Python, 47 bytes

a=input()
print(0/0 if a=="google" else len(a))
\$\endgroup\$
  • \$\begingroup\$ It should print the length of the string if the string is not "google", not the string itself. replacing else a with else len(a) will do the trick. \$\endgroup\$ – cat Nov 21 '15 at 22:21
1
\$\begingroup\$

Ruby, 26 bytes

Not shorter than the existing ones, but an alternative solution.

->x{(x=='google'||x).size}

If given google, it tries to do true.size which results in an error:

NoMethodError: undefined method `size' for true:TrueClass
\$\endgroup\$
1
\$\begingroup\$

Clojure, 35 33 bytes

#(/(count %)(if(= %"google")0 1))

(def g #(/(count %)(if(= %"google")0 1)))

(g "google")

ArithmeticException Divide by zero  clojure.lang.Numbers.divide

(g "bing")

4

Unfortunately, 0 is true is Clojure, and there aren't any simple ways of casting a bool to an int anyways, so I had to spend some bytes on a ternary. Still ended up being shorter than my first attempt.

V1: #(if(= % "google")(/ 1 0)(count %)))

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

Edited processing JS: 68 bytes

var a =function(i){if(i==="google"){throw"a";}else{print(i.length);}};

Used a edited version of processing. When run here you can see it works. If you input google then the error buddy pops up without any message. This is my first golf!

Edited version of processing (didn't cheat by making my own version) https://github.com/Khan/processing-js

\$\endgroup\$
  • \$\begingroup\$ Who edited it? Because you aren't allowed to edit a language to improve your score. \$\endgroup\$ – user63571 Jan 24 '17 at 23:06
  • \$\begingroup\$ I did not edit it. The khanacademy team edited it. github.com/Khan/processing-js It is its own fork. \$\endgroup\$ – Christopher Jan 24 '17 at 23:17
  • \$\begingroup\$ That's ok then. Just checking ;) \$\endgroup\$ – user63571 Jan 24 '17 at 23:37
  • \$\begingroup\$ Yeah otherwise my language would be called g. It would just have functions called with one byte :P \$\endgroup\$ – Christopher Jan 24 '17 at 23:38
  • \$\begingroup\$ Smart idea! Why don't you make it? \$\endgroup\$ – user63571 Jan 24 '17 at 23:54
1
\$\begingroup\$

Ruby, 19+1 = 20 bytes

Uses the -n flag. Because -n includes the trailing newline for any line of input, it must be piped in from a file w/o the trailing newline or it will not give the error and will instead return 7.

p +~/(?<!^google)$/

Version that requires a trailing newline in the input, so you can type in directly from STDIN, for 20+1=21 bytes

p +~/(?<!^google)\n/

Alternate version that works with or without trailing newlines, for 23+1=24 bytes.

+(! ~/^google$/&&p~/$/)

All versions return the following error:

undefined method `+@' for nil:NilClass (NoMethodError)
\$\endgroup\$
1
\$\begingroup\$

tcl, 46

proc x s {if \$s=="google" !;string length $s}

demo

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

05AB1E, 8 bytes (non-competing)

g¹“Š¹“Ê÷

Uses the CP-1252 encoding. Try it online!

Explanation:

           # Implicit input
 g         # Take length
  ¹        # Get first input
   “Š¹“Ê   # != compressed form of "google"
        ÷  # Integer division (Zero Division Error if invalid)
\$\endgroup\$
  • \$\begingroup\$ There's no error in 05AB1E. It just doesn't push a result. \$\endgroup\$ – Erik the Outgolfer Apr 6 '17 at 12:01
1
\$\begingroup\$

GNU sed, 137 bytes

Adding to the diversity of languages used here, I present a sed answer. There are no integer types or arithmetic operations in sed, so I wrote an increment method to get a string's length (111 bytes).

/^google$/{:;s:a*:&&a:;t}
s:^:0,:
:i
s:^9*,:0&:
s:.9*,:/&:;h
s:[0-9]*/::
y:0123456789:1234567890:
x;s:/.*::
G;s:\n::
s:,.:,:
/,./ti
s:,::

The first line of code checks if the input string is google, and if so it continuously increases the pattern space until a memory allocation error is raised. Try it online!

Tests: from a virtual Linux OS I setup with low memory

test@test:~$ sed -f google_error.sed <<< "yahoo"
5
test@test:~$ echo $?
0
test@test:~$ sed -f google_error.sed <<< "google"
sed: couldn't re-allocate memory
test@test:~$ echo $?
4
\$\endgroup\$
1
\$\begingroup\$

Mathematica, 33 bytes

#=="google"&&1/0||StringLength@#&

TFW Length doesn't work on strings. >.>

\$\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.