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

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\$
1
  • \$\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, 2016 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\$
3
  • \$\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, 2016 at 20:39
  • \$\begingroup\$ @DrGreenEggsandHamDJ Try it here \$\endgroup\$
    – penalosa
    Apr 26, 2016 at 20:48
  • \$\begingroup\$ The spec asks for a function. This is a full program. \$\endgroup\$
    – Dennis
    Nov 21, 2016 at 0:21
1
\$\begingroup\$

Python, 47 bytes

a=input()
print(0/0 if a=="google" else len(a))
\$\endgroup\$
1
  • \$\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, 2015 at 22:21
1
\$\begingroup\$

Python 2, 46 bytes

a=raw_input()
print len(a)if a!='google'else b

Errors out on input of "google" because b is an undefined identifier, but succeeds on other strings since control never reaches b in those cases.

\$\endgroup\$
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\$
8
  • \$\begingroup\$ Who edited it? Because you aren't allowed to edit a language to improve your score. \$\endgroup\$
    – user63571
    Jan 24, 2017 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\$
    – user63187
    Jan 24, 2017 at 23:17
  • \$\begingroup\$ That's ok then. Just checking ;) \$\endgroup\$
    – user63571
    Jan 24, 2017 at 23:37
  • \$\begingroup\$ Yeah otherwise my language would be called g. It would just have functions called with one byte :P \$\endgroup\$
    – user63187
    Jan 24, 2017 at 23:38
  • \$\begingroup\$ Smart idea! Why don't you make it? \$\endgroup\$
    – user63571
    Jan 24, 2017 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\$

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

05AB1E, 10 bytes

“Š¹“Qi.0ëg

Try it online!


“Š¹“       # Push "google".
    Qi   # If input == "google"...
      .0   # Divide by 0.
     ë   # Else...
      g    # Return length of input.
\$\endgroup\$
2
  • \$\begingroup\$ ....0 is divide by 0? Why? \$\endgroup\$ Oct 17, 2017 at 19:06
  • \$\begingroup\$ Why the built-in in the first place when 0/ could have achived the same result with the same bytecount? \$\endgroup\$
    – user85052
    Jan 2, 2020 at 10:29
1
\$\begingroup\$

Common Lisp, 50 bytes

(lambda(n)(assert(not(equal"google"n)))(length n))

Try it online!

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

C, 35 bytes

-Df(s)=strlen(s)/strcmp(s,"google")

Compiler flag :) Returns the length of the string provided. If it's google it throws a Floating point exception.

\$\endgroup\$
1
  • 3
    \$\begingroup\$ How does this return the length of the string? It seems like this would return a negative result in some cases. \$\endgroup\$ Mar 8, 2018 at 21:38
1
\$\begingroup\$

SmileBASIC, 41 38 bytes

DEF G(S)RETURN LEN(S)/(S!="google")END

If S is not google, the length is divided by 1. Otherwise it's divided by 0, causing an error.

G("SAND")
4

G("google")
Divide by 0 in 0:1
\$\endgroup\$
1
\$\begingroup\$

Stax, 9 bytes

ôK▓ÿσ▄Ω?╠

Run and debug online!

Well, defeated some of the 10-byters ...

Explanation

Uses the unpacked version to explain.

`!:X9`|^hy%
`!:X9`         "google"
      |^       array xor (can't use `-` here, which means **set** difference)
        h      head of array, error if it is empty
         y%    length of input
\$\endgroup\$
1
\$\begingroup\$

JavaScript (V8), 41 bytes

s=>s[['length']['google'==s|0]].toFixed()

Try it online!

JavaScript (V8), 33 bytes

s=>[_=>s.length]['google'==s|0]()

Try it online!

JavaScript (V8), 28 bytes

s=>[s]['google'==s|0].length

Try it online!

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

Racket, 46 bytes

(λ(x)(if(eq? x"google")(-)(string-length x)))

Try it online!

Gives an arity mismatch error on the input "google" since - needs at least one argument.

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

Whispers v1, 53 bytes

> Input
> "google"
>> #1
>> 1≠2
>> 3÷4
>> Output 5

Try it online!

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

Python 3.8 (pre-release), 37 35 bytes

lambda s:len(s)if"google"!=s else~s

Try it online!

Reverted to this solution whilst comparing to the other answers and noticing that it was the same. -2 bytes thanks to the suggestion by Makonede to use ~s instead of s.s

Raises TypeError: bad operand type for unary ~: 'str'

\$\endgroup\$
2
  • 1
    \$\begingroup\$ -2 bytes by using else~s instead of else s.s. ~ is bitwise NOT, where ~x is equivalent to -x-1. Since this doesn't work on strings, it raises TypeError: bad operand type for unary ~: 'str'. You can also golf off the space after else since there's an operator right after it \$\endgroup\$
    – Makonede
    Feb 21, 2021 at 22:24
  • \$\begingroup\$ Note: you can also replace ~s with -s, +s, +a, -a, ~a, ‎ a, etc. with any one-char undefined variable \$\endgroup\$
    – Makonede
    Apr 10, 2021 at 1:50
1
\$\begingroup\$

05AB1E, 8 bytes

'Š¹QiFëg

Try it online!

'Š¹QiFëg  # full program
    i     # if...
          # implicit input...
   Q      # is equal to...
'Š¹       # "google"...
     F    # then...
          # (implicit) do nothing...
          # implicit input...
     F    # times
      ë   # else...
       g  # push length of...
          # implicit input
          # implicit output
\$\endgroup\$
1
  • \$\begingroup\$ Not tying anymore lol ;p \$\endgroup\$
    – lyxal
    Apr 10, 2021 at 0:19
1
+50
\$\begingroup\$

Red, 46 bytes

func[a][(length? a)/ either a ="google"[0][1]]

Try it online!

My first attempt on writing something somewhat serious with Red

sighs in boolean cannot be used as int

\$\endgroup\$
4
  • 1
    \$\begingroup\$ I think func[a][either"google"= a[length? a][1/0]] may work (spaces may need to be added). ~42 bytes \$\endgroup\$
    – Wezl
    Jun 2, 2021 at 13:29
  • \$\begingroup\$ @Wzl no it dosen't work ( I have even tried shuffling some stuff around, it still dosen't work though ) \$\endgroup\$
    – Wasif
    Jun 2, 2021 at 17:14
  • \$\begingroup\$ oh sorry I mean func[a][either"google"= a[1/0][length? a]], although it sounds like you tried that \$\endgroup\$
    – Wezl
    Jun 2, 2021 at 17:48
  • \$\begingroup\$ (length? a)/ make 0 a <>"google". \$\endgroup\$
    – 9214
    Jun 4, 2021 at 20:26
1
\$\begingroup\$

GNU sed, 102 bytes

I did stumble over this 137 byte sed solution, but besides the counting method can be improved the probably shortest way to produce an error with GNU sed is using the e flag to execute illegal code:

s/^google$/./e
s/.$/#/
:1
/#9*$/s/#/&0/
s/.9*$/_&/
h
y/0123456789/1234567890/
x
G
s/_.*_//
s/.//
/#/b1

Try it online!

Of course, you could save two more bytes using the buggy old version with empty labels.

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

TypeScript's Type System, 113 (or 73) bytes

type F<I,S=I,L extends{}[]=[]>=S extends`${infer A}${infer B}`?F<I,B,[...L,A]>:I extends"google"?F<I>:L["length"]

Try it at the TypeScript playground!

Recursively take each character of the string and put it into a list. When no characters remain, check if the initial string was "google"; if so, recurse with the same initial string (i.e. recursion error), otherwise return the length of the list. (We must split the string into a list of characters because that's the only way to get the string's length in TypeScript's Type System.)

Or, by taking input as a tuple of characters instead of a string - 73 bytes:

type F<S extends{}[]>=S extends["g","o","o","g","l","e"]?F<S>:S["length"]

Try it at the TypeScript playground!

We can skip the whole recursive splitting process by taking the input directly as a list of strings, and comparing to the split string "google", with the same recursion error idea as the above.

\$\endgroup\$
0
\$\begingroup\$

Groovy, 32 chars

e={(it=='google'?0:it).length()}

A similar approach like a bunch of others here. The closure tries to return the length of either

  • the passed string, if it's not equal to google
  • the length of the integer 0, if the passed string is equal to google, which results in a MissingMethodException as there's no Integer.length() method

Tested with

e('bing')
e('google')
e('duckduckgo')
\$\endgroup\$
1
  • \$\begingroup\$ No need to assign to a variable, anonymous functions are allowed. .size() is shorter than .length() and is still not implemented for integers. {(it=='google'?0:it).size()} \$\endgroup\$
    – manatwork
    Mar 25, 2016 at 9:24
0
\$\begingroup\$

Ruby, 41 characters

def g(s)puts s!="google"?s.length: a end
\$\endgroup\$
0
\$\begingroup\$

Rust, 170 bytes

I didn't see anything in rust, so I figured I'd make one. Hopefully someone can improve this a bit! (or perhaps a byte... see what I did there ;) )

use std::io;fn main(){let s=io::stdin();let mut b=String::new();s.read_line(&mut b).unwrap();let l=b.len();b.truncate(l-2);assert!(b!="google");println!("{}", b.len());}

Throws the error:

thread '<main>' panicked at 'assertion failed: buffer != "google"', main.rs:7

when you try "google."

Ungolfed Code:

use std::io;
fn main() {
    let stdin = io::stdin();
    let mut buffer = String::new();
    stdin.read_line(&mut buffer).unwrap();
    let leng = buffer.len();
    buffer.truncate(leng-2);
    assert!(buffer!="google");
    println!("{}", buffer.len());
}
\$\endgroup\$
0
\$\begingroup\$

Clojure (43 bytes)

I know Clojure has been answered before, and shorter too, but I love the way this one generates a StackOverflow error when "google" is passed in:

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

Example:

user=> (f "google")

StackOverflowError user/f (NO_SOURCE_FILE:213)

\$\endgroup\$

Your Answer

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

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