169
\$\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\$
30
  • 143
    \$\begingroup\$ I googled google, and Google found Google on Google. Myth Busted. \$\endgroup\$
    – Geobits
    Sep 28, 2015 at 16:32
  • 107
    \$\begingroup\$ @Geobits That is simply a test to see if I will google Google, which I will not. :D \$\endgroup\$
    – rybo111
    Sep 28, 2015 at 16:33
  • 7
    \$\begingroup\$ Does the function need to be case sensitive? Should it throw given 'gOOgle'? \$\endgroup\$
    – AXMIM
    Sep 30, 2015 at 22:07
  • 3
    \$\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, 2015 at 4:18
  • 6
    \$\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, 2018 at 19:52

166 Answers 166

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\$
2
  • 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, 2015 at 12:53
  • 1
    \$\begingroup\$ -2 bytes: The quotation marks are unnecessary. \$\endgroup\$
    – Titus
    Nov 29, 2016 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\$
2
  • 1
    \$\begingroup\$ func g(s)return(s == "google")?throw():s.length; is a bit shorter. \$\endgroup\$
    – Dennis
    Oct 1, 2015 at 5:42
  • \$\begingroup\$ @Dennis Actually, it is 32 bits shorter. \$\endgroup\$ Oct 5, 2015 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
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\$
1
  • \$\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, 2018 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\$
2
  • \$\begingroup\$ Shorter? [ "$1" != google ]&&echo ${#1}||0 \$\endgroup\$
    – manatwork
    Sep 30, 2015 at 9:16
  • \$\begingroup\$ @manatwork Shorter & beautiful! \$\endgroup\$
    – Tarod
    Sep 30, 2015 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\$
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\$
3
  • 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, 2015 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, 2015 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\$ Oct 3, 2015 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\$

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\$
4
  • \$\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, 2015 at 18:13
  • \$\begingroup\$ @manatwork I'll add that in. Thanks! \$\endgroup\$ Sep 30, 2015 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\$
    – Grimmy
    Oct 5, 2015 at 11:32
  • \$\begingroup\$ @Grimy Thanks for pointing that out, I've added that in. \$\endgroup\$ Oct 9, 2015 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\$
0
1
\$\begingroup\$

MS T-SQL, 63 bytes

CREATE PROC g @p CHAR(9) AS SELECT IIF(@p='google',1/0,LEN(@p))

Ungolfed code;

CREATE PROC g
    @p CHAR(9)
AS
    SELECT IIF(@p='google',1/0,LEN(@p))

Called by either EXEC g 'string' or simply g 'string'

Command: EXEC g 'gogle'

Result: 5

Command: EXEC g 'google'

Result: Msg 8134, Level 16, State 1, Procedure g, Line 1 Divide by zero error encountered.

\$\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\$
3
  • 1
    \$\begingroup\$ Actually, I could just divide the string google by a number and get some type-mistmatch error \$\endgroup\$ Dec 4, 2015 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, 2016 at 15:49
  • \$\begingroup\$ @tac probably. Could be a workaround through try catch \$\endgroup\$ Mar 25, 2016 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\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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