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

2
\$\begingroup\$

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

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                                             ”
\$\endgroup\$
2
  • \$\begingroup\$ Note: this answer is non-competing. \$\endgroup\$
    – Zach Gates
    Mar 26, 2016 at 3:39
  • 1
    \$\begingroup\$ Gogh is epic. Just saying. \$\endgroup\$
    – Riker
    Mar 26, 2016 at 3:53
2
\$\begingroup\$

Julia, 26 24 chars

Two characters shorter now, thanks to Dennis.

The challenge says ‘[...]in as few amount of Unicode characters as possible’, so I’m going for and in my solution.

Anonymous function. Just assign it to a variable:

f->f≠"google"?endof(f):ℕ

In the case of "google" you get the error message:

julia> (f->f≠"google"?endof(f):ℕ)("google")
ERROR: UndefVarError: ℕ not defined

As ordinary function (26 chars):

x(f)=f≠"google"?endof(f):ℕ

is an unassigned variable, so it produces an error message. If that doesn’t count or is against the rules, then just using !f (one char longer) instead would produce an error anyway. Boolean not is not defined for strings.

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

Fuzzy Octo Guacamole, 19 bytes (non-competing)

"google".^={e}_!r_;

"google' pushes the string "google" to the stack.

. swaps the active stack.

^ gets input.

= is the rocketship operator, pushes 0 for equality, -1 for less than, and 1 for greater than as x <=> y with x as the top of the active stack, and y as the top of the inactive one.

{ and } denote an if statement, like bf's goto/if thing. Skips the code inside braces if the top of the stack is truthy.

e errors. That's it.

_ pops the stack, this time is just to remove the equality check result and show the input.

! sets the universal register to the top of the stack, or the length of the top of the stack for strings/lists.

r clears the register and pushes it back to the stack.

_ pops again, and

; prints.

So this checks for equality, then does a clumsy cast to int, and than prints the result.

\$\endgroup\$
8
  • \$\begingroup\$ the quotes... aren't maTCHED the song of unmatched quotes will exti​nguish the voices of mor​tal man from the sp​here I can see it can you see ̲͚̖͔̙î̩́t̲͎̩̱͔́̋̀ it is beautiful t​he final snuffing of the lie​s of Man ALL IS LOŚ͖̩͇̗̪̏̈́T ALL I​S LOST the pon̷y he comes he c̶̮omes he comes the ich​or permeates all MY FACE MY FACE ᵒh god no NO NOO̼O​O NΘ stop the an​*̶͑̾̾​̅ͫ͏̙̤g͇̫͛͆̾ͫ̑͆l͖͉̗̩̳̟̍ͫͥͨe̠̅s ͎a̧͈͖r̽̾̈́͒͑e n​ot rè̑ͧ̌aͨl̘̝̙̃ͤ͂̾̆ ZA̡͊͠͝LGΌ ISͮ̂҉̯͈͕̹̘̱ TO͇̹̺ͅƝ̴ȳ̳ TH̘Ë͖́̉ ͠P̯͍̭O̚​N̐Y̡ H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟Oͮ͏̮̪̝͍M̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ \$\endgroup\$
    – cat
    Mar 26, 2016 at 12:10
  • \$\begingroup\$ -1 for unmatched quotes ಠ_ಠ \$\endgroup\$
    – cat
    Mar 26, 2016 at 12:15
  • \$\begingroup\$ @tac they represent the beginning and end of the string literal. That is intentional. \$\endgroup\$
    – Riker
    Mar 26, 2016 at 15:31
  • \$\begingroup\$ I know that, I just don't know why anyone would willingly create a language that uses unmatched things. (I know many golfing languages do it and it makes my eyes bleed) \$\endgroup\$
    – cat
    Mar 26, 2016 at 15:32
  • \$\begingroup\$ @tac I can make it work with matched ones also if you want. \$\endgroup\$
    – Riker
    Mar 26, 2016 at 15:39
2
\$\begingroup\$

C++14, 42 chars

For giggles, as I did not see a very good c++ solution. My TI-89 solution is superior at 34 bytes

[](auto s){return s.size()/(s!="google");}
\$\endgroup\$
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\$
1
  • \$\begingroup\$ Alright, wasn't sure if I could post multiple answers to a solution @lirtosiast , thanks! \$\endgroup\$
    – STDQ
    Mar 26, 2016 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\$
2
  • \$\begingroup\$ Um... is that supposed to link to urbit? \$\endgroup\$ Nov 20, 2016 at 9:55
  • \$\begingroup\$ @DestructibleWatermelon Yup. Urbit provides the compiler/interpreter for the Hoon language. \$\endgroup\$ Nov 21, 2016 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\$
7
  • 1
    \$\begingroup\$ +1 for "Segmentation fault (core dumped)" -- my favourite error message \$\endgroup\$
    – cat
    Mar 25, 2016 at 15:46
  • \$\begingroup\$ It's my favorite message, too... if I'm not the one that has to debug it. :p \$\endgroup\$ Mar 25, 2016 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, 2016 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, 2016 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, 2016 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\$
2
  • \$\begingroup\$ you can use param($a)$a.length/($a-cne'google') to skip using the the !, saving one byte. \$\endgroup\$
    – colsw
    Nov 29, 2016 at 10:57
  • \$\begingroup\$ @ConnorLSW Indeed. Thanks. \$\endgroup\$ Nov 29, 2016 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\$
4
  • \$\begingroup\$ “However, if the given string is google (lowercase), it will cause an error.” – Will this? \$\endgroup\$
    – manatwork
    Nov 29, 2016 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, 2016 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\$ Nov 29, 2016 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\$ Nov 29, 2016 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\$

Jelly, 10 bytes

ßL⁼“æ8Ụ»$?

Try it online! (with "google" as input)

Try it online! (with "bing" as input)

How it works

ßL⁼“æ8Ụ»$? - Main link. Argument: s (string)

         ? - if...
  ⁼     $  -   the input is equal to...
   “æ8Ụ»   -     "google"
           -   then
ß          -     call the main link (segfault)
           -   else
 L         -     return the length of the input
\$\endgroup\$
2
\$\begingroup\$

Aceto, 19 bytes

rdM"google"J=$L€lp

Took me a while, but I finally got it. Aceto uses a hilbert curve for it's ip, which is really annoying.

r grabs input
d duplicates it
M pops the top value and stores it in quick memory
"google" pushes google on the stack, but with a lot of spaces in between.
- splits it on whitespace
J concatenates it
= pushes a bool on the stack: whether the top two values are equal
$ asserts that the top value is truthy, if not it raises an error.                                    Don't ask me why i don't have to negate it
L loads the quick memory
€ explodes the string, putting each char as a separate val on the stack
l takes the height of the stack
p prints that num

Try it online!

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

Brachylog, 12 bytes

"google"∧∈|l

Try it online!

Since Brachylog simply fails a predicate that tries to divide by 0, the error here comes from trying to unify the output with a list containing an entirely un-instantiated variable instead. If the input can be unified with google, it errors, and otherwise this predicate outputs the length of the input (add one more byte w to the end to make it a full program that prints the length).

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

W d, 10 9 bytes

This is a full program but is technically also a function.

*↔XÑ║╜▄]ÿ

Explanation

Decompressed:

-Fl'I`nakS/

After string decompression:

google"nakS/
google"n     # Does the input *not* equal to "google"?
        ak   # Find the length of the input
          S/ # Divide the length of the input by the above condition
\$\endgroup\$
2
\$\begingroup\$

Clojure, 47 44 bytes

Old answer

#(/(count %)(get{false 1 true 0}(= %"google")))

Try it online!

New Answer

#(/(count %)({false 1 true 0}(= %"google")))

Removed the get function call, because you can call a hashmap with a key to get the value.

Try it online!

\$\endgroup\$
2
  • 2
    \$\begingroup\$ Welcome to the site, and nice first answer! Be sure to check out our Tips for golfing in Clojure page for ways you can golf your program \$\endgroup\$ Feb 20, 2021 at 20:16
  • \$\begingroup\$ @cairdcoinheringaahing thank you^^ \$\endgroup\$
    – Satoshi
    Feb 20, 2021 at 20:19
2
\$\begingroup\$

Red, 34 bytes

func[g][length? any[g ="google"g]]

Try it online! (the code so dense that it crashes the program).

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

Python 3, 30 bytes

lambda x:len(x)//(x!="google")

Try it online! Python 3 port of xnor's Python 2 answer. The floor division operator is necessary to convert back to an integer instead of leaving it as a float.

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

05AB1E, 8 bytes

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\$
1
  • \$\begingroup\$ There's no error in 05AB1E. It just doesn't push a result. \$\endgroup\$ Apr 6, 2017 at 12:01
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\$
1
  • \$\begingroup\$ @FryAmTheEggman I'm sorry, I just wrote the explanation wrong, the code is correct. \$\endgroup\$
    – nanny
    Sep 28, 2015 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\$
4
  • \$\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, 2015 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, 2015 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, 2015 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, 2015 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\$

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.