171
\$\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
  • 145
    \$\begingroup\$ I googled google, and Google found Google on Google. Myth Busted. \$\endgroup\$
    – Geobits
    Commented Sep 28, 2015 at 16:32
  • 109
    \$\begingroup\$ @Geobits That is simply a test to see if I will google Google, which I will not. :D \$\endgroup\$
    – rybo111
    Commented Sep 28, 2015 at 16:33
  • 8
    \$\begingroup\$ Does the function need to be case sensitive? Should it throw given 'gOOgle'? \$\endgroup\$
    – AXMIM
    Commented 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
    Commented 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
    Commented Aug 1, 2018 at 19:52

169 Answers 169

1
2 3 4 5 6
244
\$\begingroup\$

Python 2, 29

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

Gives a ZeroDivisionError on "google", and the length otherwise. This takes advantage of Python's booleans equaling 0 and 1.

\$\endgroup\$
7
  • 3
    \$\begingroup\$ +1. You need to set g to your lambda, or call it anonymously with an input, though. \$\endgroup\$
    – Zach Gates
    Commented Sep 28, 2015 at 16:44
  • 7
    \$\begingroup\$ Just for fun, I tried this technique with JavaScript ES6. It ended up at 25, but returns Infinity for "google" instead of throwing an error... \$\endgroup\$ Commented Sep 28, 2015 at 16:55
  • 23
    \$\begingroup\$ @ZachGates The consensus on meta is that anonymous functions are allowed unless specifically disallowed. Since the question does seem to imply something like this (but doesn't explicitly disallow it, yet), you should ask the OP about it. \$\endgroup\$ Commented Sep 28, 2015 at 16:58
  • 3
    \$\begingroup\$ @Kevin you would need a return if you used def \$\endgroup\$ Commented Sep 28, 2015 at 20:10
  • 5
    \$\begingroup\$ Amusingly, this translated to Pyth does better than my prior best Pyth solution. It is L/lbnb"google, 13 bytes. \$\endgroup\$
    – isaacg
    Commented Nov 26, 2015 at 6:26
117
\$\begingroup\$

Excel, 23 characters

Paste this into a cell other than A1 and type your search query into A1.

=LEN(A1)/(A1<>"google")

For example:

GoogleGoogle

\$\endgroup\$
7
  • 11
    \$\begingroup\$ What's the general consensus on using Excel? \$\endgroup\$
    – Beta Decay
    Commented Sep 30, 2015 at 17:11
  • 56
    \$\begingroup\$ @BetaDecay. Creative, uncommon, seems to work. Won't be applicable to all CG puzzles, but it is here! \$\endgroup\$
    – kdbanman
    Commented Sep 30, 2015 at 18:03
  • 131
    \$\begingroup\$ Managers love it! \$\endgroup\$
    – lkraider
    Commented Sep 30, 2015 at 18:07
  • 25
    \$\begingroup\$ So Efficient, CG Users Will Hate You For It. But Wait. B3 Will Change Your Life Forever! \$\endgroup\$
    – Sumurai8
    Commented Oct 1, 2015 at 7:44
  • 11
    \$\begingroup\$ What's the specific concensus on using Excel? \$\endgroup\$ Commented Oct 3, 2015 at 23:29
84
\$\begingroup\$

C#, 43 bytes

An improvement over Salah Alami's answer. Recurses to throw a stack overflow exception on providing "google"

int g(string s)=>s!="google"?s.Length:g(s);
\$\endgroup\$
9
  • 2
    \$\begingroup\$ Yeah I thought that was a pretty clever way to save some characters to throw an exception. At 4 characters, it might be the smallest way to throw an exception in C#, not sure. \$\endgroup\$
    – DLeh
    Commented Oct 1, 2015 at 20:05
  • 6
    \$\begingroup\$ This is clever! However, recent versions of C# have support for tail recursion so this function will never throw StackOverflowException. In fact it will never return (behaves as while(true){}). \$\endgroup\$
    – NightElfik
    Commented Oct 6, 2015 at 4:15
  • 2
    \$\begingroup\$ @DLeh Tail recursion calls are little bit tricky. You have to run on x64 JIT and without debugger (debugger attached will cause tail recursion to not work for obvious reasons). Here is my program as a proof: imgur.com/ErNl8LJ and little more reading about tail recursion: blogs.msdn.com/b/davbr/archive/2007/06/20/… ;) \$\endgroup\$
    – NightElfik
    Commented Oct 10, 2015 at 18:52
  • 13
    \$\begingroup\$ Haha: g(string)... I'll see myself out... \$\endgroup\$ Commented Nov 17, 2015 at 1:45
  • 2
    \$\begingroup\$ @DLeh oh wait no I can match your 43 bytes but not beat it. :) int g(string s)=>s!="google"?s.Length:s[9]; \$\endgroup\$
    – lee
    Commented Mar 9, 2018 at 3:27
57
\$\begingroup\$

Pyth, 14 13 characters

L/lbnb"google

Defines a named function y.

This divides the length by 1 if the string is not google and by 0 otherwise. The idea is not novel, but I came up with it independently.

Try it online.

How it works

L                 Define y(b):
  lb                Compute len(b).
    nb"google       Compute (b != "google").
 /                  Set _ = len(b) / (b != "google").
                  Return _. (implicit)
\$\endgroup\$
16
  • \$\begingroup\$ Yeah I'm actually unsure about this, I don't think it's happened before with a string. Normally you could close it with ; but obviously you can't here... \$\endgroup\$ Commented Sep 28, 2015 at 17:29
  • \$\begingroup\$ You don't need the end quote. \$\endgroup\$
    – Maltysen
    Commented Sep 28, 2015 at 20:25
  • 51
    \$\begingroup\$ "Defines a named function y." But there's no y in your code!? \$\endgroup\$ Commented Sep 29, 2015 at 13:03
  • 48
    \$\begingroup\$ @A.L That's correct. The built-in L redefines the function y. \$\endgroup\$
    – Dennis
    Commented Sep 29, 2015 at 14:49
  • 95
    \$\begingroup\$ I'm not sure, but I think I hate Pyth. \$\endgroup\$
    – Mr Lister
    Commented Sep 30, 2015 at 15:36
45
\$\begingroup\$

MATLAB, 63 41 40 38 36 bytes

Thanks to Tom Carpenter for shaving off 1 byte!

Thanks to Stewie Griffin for shaving off 2 bytes!

@(x)nnz(x(+~strcmp('google',x):end))

Unlike the other more elegant solutions, performing a division by zero operation in MATLAB will not give an error, but rather Inf. This solution finds the length of the string by nnz. The string that is produced is in such a way that you index from the beginning of the string to the end, which is essentially a copy of the string. However, what is important is that the beginning of where to access the string is produced by checking whether or not the input is equal to 'google'. If it isn't, this produces a beginning index of 1 and we index into the string normally... as MATLAB starts indexing at 1. Should it be equal, the index produced is 0 and MATLAB will throw an indexing error stating that the index needs to be a positive integer. The extra + is to ensure that the output of the equality check is numerical rather than Boolean/logical. Omitting the + will produce a warning, but because this challenge's specifications doesn't allow for warnings, the + is required... thus completing the code.

Example uses

>> f=@(x)nnz(x(+~strcmp('google',x):end)) %// Declare anonymous function

f = 

    @(x)nnz(x(+~strcmp('google',x):end))

>> f('bing')

ans =

     4

>> f('google')
Subscript indices must either be real positive integers or logicals.

Error in @(x)nnz(x(+~strcmp('google',x):end))

A more fun version, 83 77 76 74 72 bytes

Thanks to Tom Carpenter for shaving off 1 byte!

Thanks to Stewie Griffin for shaving off 2 bytes!

@(x)eval('if strcmp(''google'',x),web([x ''.com/i'']);else nnz(x),end');

The above isn't an official submission, but it's something that's a bit more fun to run. Abusing eval within anonymous functions, what the code does is that it checks to see if the input string is equal to 'google'... and if it is, this will open up MATLAB's built-in web browser and shows Google's 404 error page trying to access the subpage located at i when that doesn't exist. If not, we display the length of the string normally.

Example uses

>> f=@(x)eval('if strcmp(''google'',x),web([x ''.com/i'']);else nnz(x),end'); %// Declare anonymous function
>> f('bing')

ans =

     4

>> f('google')
>> 

The last call using 'google' gives us this screen:

enter image description here

\$\endgroup\$
3
  • 3
    \$\begingroup\$ You could save a byte by using strcmp instead of isequal. \$\endgroup\$ Commented Sep 29, 2015 at 5:47
  • \$\begingroup\$ @TomCarpenter - Funny. I actually told myself to use strcmp but ended up using isequal for some reason.... thanks! \$\endgroup\$
    – rayryeng
    Commented Sep 29, 2015 at 5:53
  • 2
    \$\begingroup\$ nnz is two bytes shorter than numel. You had my vote a few years ago :-) \$\endgroup\$ Commented Oct 17, 2017 at 20:13
32
\$\begingroup\$

JavaScript ES6, 34 27 25 characters

f=>f=='google'?Δ:f.length

Throws a ReferenceError on Δ for google.

alert((f=>f=='google'?Δ:f.length)('test'))

\$\endgroup\$
9
  • 11
    \$\begingroup\$ You could use a ternary operator to save two bytes. \$\endgroup\$
    – null
    Commented Sep 29, 2015 at 13:14
  • 2
    \$\begingroup\$ Yay, that's exactly what I just got. If you want to be fancy, use a symbol people never use instead of g to be sure it won't exist as a global variable. Δ makes for a good variable name :) \$\endgroup\$
    – Domino
    Commented Oct 1, 2015 at 17:07
  • 1
    \$\begingroup\$ You could use #, it errors in JS afaik \$\endgroup\$
    – clapp
    Commented Oct 6, 2015 at 1:55
  • 7
    \$\begingroup\$ Δ Google Illuminati confirmed \$\endgroup\$
    – user45178
    Commented Oct 7, 2015 at 1:59
  • 2
    \$\begingroup\$ I'm just going to leave this here github.com/Rabrennie/anything.js \$\endgroup\$
    – sagiksp
    Commented Mar 9, 2017 at 10:04
29
\$\begingroup\$

TI-BASIC, 15 bytes

Heck, while we're at it, might as well get a TI-BASIC answer in here.

Input format is "string":prgmNAME. Credit to Thomas Kwa for finding it first!

length(Ans)+log(Ans≠"GOOGLE

(Guide: add 1 byte for each lowercase letter replacing an upper-case one. So s/GOOGLE/google/g => +6 bytes.)

ahhhhh test cases!

"GOGGLE":prgmG
               6
"BING":prgmG
               4
"GOOGLE":prgmG
           Error
\$\endgroup\$
6
  • \$\begingroup\$ 20 bytes: length(Ans)/(Ans≠"google. You also have the case wrong; if uppercase is allowed it's 14 bytes. By the way, it's valid to pass arguments through Ans. \$\endgroup\$
    – lirtosiast
    Commented Sep 28, 2015 at 19:37
  • \$\begingroup\$ AGOOGLE should give 7, correct? And you shouldn't be counting the program header in your code size, so subtract 10 bytes. \$\endgroup\$
    – lirtosiast
    Commented Sep 28, 2015 at 20:48
  • \$\begingroup\$ ERROR: I was thinking substrings. Kindly forgive me. \$\endgroup\$ Commented Sep 28, 2015 at 20:49
  • 1
    \$\begingroup\$ @ThomasKwa I didn't see your comment with the code. It just so happens that we both stumbled upon the same solution. However, if you believe you deserve the credit, the credit shall be yours. ^_^ (EDIT If you would read the code, it isn't the exact same thing.) \$\endgroup\$ Commented Sep 28, 2015 at 22:13
  • \$\begingroup\$ @lirtosiast length( is two bytes, that would make your numbers 21 and 15 bytes. \$\endgroup\$
    – Timtech
    Commented Mar 29, 2016 at 19:28
27
\$\begingroup\$

Python 3, 30 bytes

lambda u:[len][u=='google'](u)

Indexes the 1-element function list, raising an IndexError if the u=='google' predicate is True (= 1). Such functional.

Much variants. Wow:

lambda u:[len(u)][u=='google']
lambda u:len([u][u=='google'])

If the challenge was inverted (error on everything not "google"), could save a char:

lambda u:{'google':len}[u](u)

But you already know the length, so just hardcode it.

\$\endgroup\$
2
  • \$\begingroup\$ works for python 2.7 too \$\endgroup\$
    – Noodle9
    Commented Oct 1, 2015 at 16:42
  • 1
    \$\begingroup\$ For some reason, I love this solution. \$\endgroup\$
    – foslock
    Commented Mar 26, 2016 at 2:20
24
\$\begingroup\$

APL (14)

(⍴÷'google'∘≢)

Explanation:

  • : length
  • ÷: divided by
  • 'google'∘≢: argument is not equal to 'google'.

gives the length of the string, which is divided by 1 if the string does not equal google (which gives the length back unchanged), or by 0 if the string does equal google (giving an error).

\$\endgroup\$
2
  • 12
    \$\begingroup\$ I think you don't need to count the parens, as it can be assigned to a variable without them. \$\endgroup\$
    – jimmy23013
    Commented Sep 29, 2015 at 6:06
  • 2
    \$\begingroup\$ Kind-of fails on single-char arguments. Fix by replacing with . Also, you can make it cooler-looking by swapping the operands of . Oh, don't forget to remove the parens. All-in-all: ≢÷≢∘'google' \$\endgroup\$
    – Adám
    Commented Jan 10, 2017 at 23:08
19
\$\begingroup\$

Haskell, 24 bytes

g s|s/="google"=length s

Output:

Main> g "google"

Program error: pattern match failure: g "google"

Main> g "bing"
4
\$\endgroup\$
18
\$\begingroup\$

Octave, 63 bytes

I know it is longer than the Matlab solution (which would work in Octave too), but it is particularly evil. I am making an anonymous function (evil) using cell array (evil) literals (evil) containing function handles dependent on a callback function (itself, thus recursive, evil) that must be passed via argument. Then I create another anonymous that basically reduces the function to the string argument and fixes the second argument of f as f (very evil). Any sane human would never do this, because it is almost as unreadable as Perl or regex (or cjam/pyth/any other esolang).

So if the string is not 'google' the second argument of the cell array will be called which outputs the length of the string. Otherwise the first function will be called, which is passed as a callback (and passes itself as callback to itself too) which later is the function itself. The error is basically some maximum recursion depth error.

f=@(s,f){@()f(s,f),numel(s)}{2-strcmp(s,'google')}();@(s)f(s,f)
\$\endgroup\$
2
  • 2
    \$\begingroup\$ Those things are not evil in most languages. And this is code golf, some of the most unreadable code on the planet exists here :). Cool handle btw. \$\endgroup\$
    – BAR
    Commented Oct 2, 2015 at 20:22
  • 9
    \$\begingroup\$ I'm only missing some eval here to make it really EVIL :-) \$\endgroup\$
    – Luis Mendo
    Commented Oct 5, 2015 at 0:11
16
\$\begingroup\$

CJam, 16 characters

{_,\"google"=!/}

This divides the length by 1 if the string is not google and by 0 otherwise. The idea is not novel, but I came up with it independently.

Try it online.

How it works

_                 Push a copy of the string on the stack.
 ,                Compute the length of the copy.
  \               Swap the length and the original string.
   "google"=      Push 1 if the string is "google", 0 otherwise.
            !     Apply logical NOT. Maps 1 to 0 and 0 to 1.
             /    Divide the length by the Boolean.
\$\endgroup\$
1
  • \$\begingroup\$ Interestingly enough, a full program is shorter (15 bytes): q_,\"google"=!/. Developed it before seeing this post. Note that this takes the whole input (which you seem to take anyways as a function argument). Unfortunately, you can't use it, since this asks for a function :( \$\endgroup\$ Commented Nov 1, 2016 at 21:53
14
\$\begingroup\$

APL, 19 17 bytes

{⍵≡'google':⍟⋄≢⍵}

This is an unnamed monadic function that will throw a syntax error if the input is google. This is accomplished by attempting to take the natural logarithm of nothing.

{
 ⍵≡'google':          ⍝ If the right argument is "google"...
            ⍟⋄        ⍝ Compute log(<nothing>), which brings only sadness
              ≢⍵      ⍝ Otherwise compute the length
}

Try it online

Saved two bytes thanks to Dennis!

\$\endgroup\$
1
  • \$\begingroup\$ is known informally as "splat". A very appropriate name for this usage. \$\endgroup\$
    – Adám
    Commented Jan 10, 2017 at 23:09
12
\$\begingroup\$

JavaScript, 25 Bytes

Nice and simple JavaScript example:

e=>e!='google'?e.length:g

If "google" is entered then it passes a ReferenceError

Example

alert((e=>e!='google'?e.length:g)('test'))

\$\endgroup\$
2
  • 2
    \$\begingroup\$ Wow, thanks for telling me there's a shorthand for lamda functions in javascript! \$\endgroup\$ Commented Oct 3, 2015 at 17:28
  • 3
    \$\begingroup\$ @TomášZato Caveat: they're brand new in ES2015, so support still varies. \$\endgroup\$
    – Anko
    Commented Oct 4, 2015 at 22:31
11
\$\begingroup\$

Perl, 31 29 bytes

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

-2b thanks to manatwork

Usage:

sub{$_=pop;y///c/!/^google$/}->("google")

If I could get away with a program rather than a function, the following would be valid with only 20 bytes (+1 byte command line)

$_=y///c/!/^google$/

Error is division by zero.

Explanation:

y///c returns the length, then !/^google$/ will return 0 iff input matches 'google'.

Usage:

perl -p entry.pl input.txt
\$\endgroup\$
3
  • 2
    \$\begingroup\$ You could make it an anonymous function: sub{…}. (Then you call it like sub{…}->("google").) \$\endgroup\$
    – manatwork
    Commented Sep 29, 2015 at 8:30
  • \$\begingroup\$ Save 1 byte by using $_!=google instead of !/^google$/ \$\endgroup\$ Commented Nov 1, 2016 at 3:05
  • \$\begingroup\$ @GabrielBenamy I'm afraid != won't work to compare string... \$\endgroup\$
    – Dada
    Commented Feb 16, 2017 at 16:24
10
\$\begingroup\$

R, 46 bytes

g=function(x)ifelse(x!="google",nchar(x),)

Unless I'm misreading, the original post never specified that the code had to be correct syntax.

Example:

> g("bing")
[1] 4
> g("google")
Error in ifelse(x != "google", nchar(x), ) : 
  argument "no" is missing, with no default

I never added anything for the "no" parameter of the ifelse statement so it will return an error if this parameter is evoked.

\$\endgroup\$
1
  • 11
    \$\begingroup\$ Here is a slightly shorter one: g=function(x)nchar(x)[[x!="google"]] \$\endgroup\$
    – flodel
    Commented Sep 29, 2015 at 1:38
8
\$\begingroup\$

Java 7:53 52 Bytes

int g(String _){return"google"==_?0/0:_.length();} 

Above code will throw ArithmeticException for division by zero and for any String other than google. Worth to note that == compares reference and won't work for String Objects.

Java 8 : 29 Bytes

(Based on suggestion given in below comment)

s->s=="google"?0/0:s.length()
\$\endgroup\$
4
  • 1
    \$\begingroup\$ You can also use Java 8's lambda declaration: s->(s.equals("google")?null:s).length(); \$\endgroup\$
    – h.j.k.
    Commented Sep 29, 2015 at 3:48
  • 3
    \$\begingroup\$ "Worth to note that == compares reference and won't work for String Objects." Actually, all strings are objects, so comparing strings with == in Java will generally not work (unless you're relying on string interning, which is, well, bad). Perhaps you got confused with JavaScript? \$\endgroup\$
    – gengkev
    Commented Oct 6, 2015 at 0:52
  • 1
    \$\begingroup\$ @gengkev If they are both litterals, it will work since it is the same object that's referenced to on the String pool. The spec gives a litteral and here it is a litteral so it will work. \$\endgroup\$ Commented Nov 21, 2015 at 23:16
  • 3
    \$\begingroup\$ @YassinHajaj I agree that the spec gives it as a literal, but that's just an example. The function should probably perform the same if given input from stdin as well, or if the function is called from another class that's compiled separately. In any case, relying on compiler optimizations (string interning) is a poor idea, which is what I originally said. \$\endgroup\$
    – gengkev
    Commented Nov 21, 2015 at 23:28
7
\$\begingroup\$

Haskell - 30 characters

g"google"=error"!";g s=length s

>g "google"
 *Exception: !
>g "str"
 3
\$\endgroup\$
3
  • 6
    \$\begingroup\$ Why the exclamation mark for error? Wouldn't an empty string do too? \$\endgroup\$
    – Kritzefitz
    Commented Sep 28, 2015 at 18:36
  • 1
    \$\begingroup\$ I wanted to suggest to change it to x=x;g"google"=x;g s=length s, but for some reason, <<loop>> exceptions aren't thrown in ghci. \$\endgroup\$
    – Kritzefitz
    Commented Sep 28, 2015 at 18:44
  • 18
    \$\begingroup\$ g s|s/="google"=length s avoids the need for error \$\endgroup\$
    – chs
    Commented Sep 28, 2015 at 23:30
7
\$\begingroup\$

Python 3, 35 bytes

lambda n:len(n)if n!='google'else d
\$\endgroup\$
3
  • 1
    \$\begingroup\$ @FryAmTheEggman actually 16 bits shorter. XD \$\endgroup\$
    – DiegoDD
    Commented Sep 28, 2015 at 23:26
  • 1
    \$\begingroup\$ @FryAmTheEggman: Good trick but id does not work with empty string: (lambda n:len(n)*(n!='google')or d)('') \$\endgroup\$ Commented Sep 29, 2015 at 9:17
  • \$\begingroup\$ @pabouk Quite right, thanks for pointing that out. \$\endgroup\$ Commented Sep 29, 2015 at 12:39
7
\$\begingroup\$

C++11, 54 (code) + 14 (#include) = 68

Well, division by zero is just undefined behaviour, which I would not call an error. So my approach.

#include<ios>
[](std::string s){return s!="google"?s.size():throw;};

usage

[](std::string s){return s!="google"?s.size():throw;}("google");
\$\endgroup\$
9
  • 1
    \$\begingroup\$ You can call size() to save 2 bytes. In C++14, you could also use generic lambdas and replace std::string by auto. You'd need to pass an actual std::string to it instead of a const char*. \$\endgroup\$
    – isanae
    Commented Sep 28, 2015 at 23:35
  • \$\begingroup\$ @isanae I didn't know std::string has size() method, thanks for that. I am aware of generic lambdas in C++14, but I don't know how it would help me, since "string" is const char* and not std::string. \$\endgroup\$
    – Zereges
    Commented Sep 29, 2015 at 6:38
  • 1
    \$\begingroup\$ @Zereges std::string has size() and length() because it's both a container and a string. As for auto, you'd call the lambda with (std::string("google")) instead of ("google"). The question only says "accepts 1 string" without specifying what a "string" is. \$\endgroup\$
    – isanae
    Commented Sep 29, 2015 at 6:42
  • \$\begingroup\$ @isanae C++14 also has "google"s to construct an std::string :) \$\endgroup\$
    – Quentin
    Commented Sep 29, 2015 at 17:47
  • \$\begingroup\$ @Zereges you can simply throw; to trigger std::terminate() (because there's no current exception here). \$\endgroup\$
    – Quentin
    Commented Sep 29, 2015 at 17:48
7
\$\begingroup\$

C, 66 48

Original:

int l(long*s){return strlen(s)/((*s&~(-1L<<56))!=0x656c676f6f67);}

Using OSX gcc,
l("duck"); returns 4,
l("google"); causes Floating point exception: 8.

On other platforms, the constants may need to be adjusted for endianness.

Shorter:

less trickyness, same results.

 l(int*s){return strlen(s)/!!strcmp(s,"Google");}
\$\endgroup\$
7
  • \$\begingroup\$ Wow, that is some interesting logic there. If I understand the golfy part right, you are somehow shifting the first six chars to fit into a single, giant number (almost like a hash), which, because of the stack being little-endian, ends up being "google", but backwards (0x656c676f6f67 = elgoog). I think this answer needs an explanation for those of us who appreciate this kind of crazy low-level stuff. \$\endgroup\$ Commented Sep 29, 2015 at 21:46
  • \$\begingroup\$ You basically have it. It simply casts the memory storing the string into a 64 bit number. Endianness makes it 'backward' on x86 architectures. The text only occupies 7 bytes, so the mask just hides whatever may be next in memory. Its a fun trick, but I think '!!strcmp(s,"google")' is actually shorter. \$\endgroup\$
    – AShelly
    Commented Sep 30, 2015 at 0:25
  • 1
    \$\begingroup\$ Anyways, +1. Definitely. Also, I think you can shorten it by removing the int , that's 4 characters. \$\endgroup\$ Commented Sep 30, 2015 at 2:37
  • \$\begingroup\$ After some typing, I figured it out! If char *, with units of 8-bits, is casted to long *, with units of 64-bits, without being properly reallocated, the data in those 8 bytes of heap space becomes corrupted, and treated as a single number (8*8 = 64). That's why you get the first 6 chars, + NUL + garbage. That is very clever. Dangerous, too. Wonder why it doesn't segfault. That 8th garbage byte is out of bounds, no? \$\endgroup\$ Commented Sep 30, 2015 at 3:12
  • \$\begingroup\$ I looked at your analysis. You are correct, the shift should have been 56, not 54. Also, I wouldn't use the word corrupted. The memory is the same, the bits are just interpreted differently. Technically, accessing the garbage byte is undefined behavior, and could actually segfault. Practically, that byte almost certainly resides in the same legal memory block as the rest of the string, and generally these blocks (heap, stack, constants) are allocated in word sized units at a minimum. So the memory belongs to the program, it just contains something other than the string. \$\endgroup\$
    – AShelly
    Commented Sep 30, 2015 at 18:07
7
\$\begingroup\$

Ruby, 29 bytes

I first came up with something very similar to @Borsunho's first attempt, but mine was slightly longer and he posted his before I was done. Came up with this before his 30 bytes edit :)

->s{s[/^(?!google$).*/].size}

Usage examples:

$ irb
2.2.1 :001 > f = ->s{s[/^(?!google$).*/].size}
 => #<Proc:0x007fa0ea03eb60@(irb):1 (lambda)> 
2.2.1 :002 > f[""]
 => 0 
2.2.1 :003 > f["bing"]
 => 4 
2.2.1 :004 > f["google"]
NoMethodError: undefined method `size' for nil:NilClass
  from (irb):1:in `block in irb_binding'
  from (irb):4:in `[]'
  from (irb):4
  from /Users/daniel/.rvm/rubies/ruby-2.2.1/bin/irb:11:in `<main>'

edit: Two years and some Ruby versions later

Ruby, 25 bytes

->s{+s[/^(?!google$).*/]}

Replaced String#size with the new unary plus. Try it online!

\$\endgroup\$
4
  • \$\begingroup\$ Neat, I couldn't get this to work ( I didn't came up with leaving ^ outside the matchgroup). \$\endgroup\$
    – Borsunho
    Commented Sep 28, 2015 at 18:00
  • \$\begingroup\$ @Borsunho I have to admit I just "brute forced" the regex untill I got the result that I wanted :) I think the .* at the end is what makes it work. \$\endgroup\$
    – daniero
    Commented Sep 28, 2015 at 18:07
  • \$\begingroup\$ Breaks if the input string has multiple lines and contains google on its own line. I think /\A(?!google\Z).*/m fixes it (at the cost of three bytes, though). ^ and $ match the beginning and end of lines, while \A and \Z match the beginning and end of the string as a whole. \$\endgroup\$
    – histocrat
    Commented Sep 28, 2015 at 18:30
  • \$\begingroup\$ @histocrat but I don't think you can google strings with multiple lines ;) \$\endgroup\$
    – daniero
    Commented Sep 28, 2015 at 19:01
6
\$\begingroup\$

MUMPS, 28 bytes

g(s) q $S(s'="google":$L(s))

Usage:

>w $$g^MYROUTINE("bing")                                      
4
>w $$g^MYROUTINE("google")

<SELECT>g^MYROUTINE

Why? Well, $S[ELECT] is basically a compact multi-clause if-else statement - almost like a pattern-match in a language like Haskell or Rust. Except... unlike in Haskell or Rust, the patterns aren't checked for exhaustiveness, because the notion of "compile-time safety" is completely alien to MUMPS. So if your input is a pattern you didn't account for, you get a lovely runtime error called <SELECT>.

\$\endgroup\$
6
\$\begingroup\$

JavaScript, 47 bytes

Nice and simple.

Edit: Now complies with the rules

function f(g){if(g=="google")a;return g.length}

Testing

Error thrown

function f(g){if(g=="google")a;return g.length}

alert(f("Hello"))
alert(f("google"))
alert(f("hi"))

No error thrown

function f(g){if(g=="google")a;return g.length}

alert(f("Hello"))
alert(f("bing"))
alert(f("hi"))

\$\endgroup\$
7
  • \$\begingroup\$ Technically, this doesn't meet the OP's specs. This function alerts the length but returns undefined. \$\endgroup\$
    – Bungle
    Commented Sep 30, 2015 at 5:00
  • \$\begingroup\$ @Bungle How's it now? \$\endgroup\$
    – Beta Decay
    Commented Sep 30, 2015 at 5:57
  • 1
    \$\begingroup\$ @Bungle I see. I forgot that a return was needed \$\endgroup\$
    – Beta Decay
    Commented Sep 30, 2015 at 16:58
  • 1
    \$\begingroup\$ Using ES6's arrow functions and ternary operator (instead of if), you can squeeze that a bit more :) \$\endgroup\$ Commented Oct 1, 2015 at 21:09
  • 1
    \$\begingroup\$ @BetaDecay Originality first; I respect that. \$\endgroup\$ Commented Oct 2, 2015 at 1:08
5
\$\begingroup\$

Ruby, 34 30 27 26

->x{x=='google'?t: x.size}

Unknown t raises exception.

->x{x=='google'?fail():x.size}

Edit: totally readable and obvious version that is shorter...

->x{x[x=~/^(?!google$)/..-1].size}

Old: Pretty similar to other ideas it seems. Will raise ArgumentError if x is 'google'.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Why those parenthesis? x=='google'?t: x.size \$\endgroup\$
    – manatwork
    Commented Sep 28, 2015 at 18:48
5
\$\begingroup\$

C - 99 75 67 63 bytes

g(char*s){int i=0,j=*s;while(s[i])j^=s[++i];return j^9?i:g(s);}

Ungolfed:

int g(char *s){
    int i = 0,
        j = s[0]; // first char of s
    while(s[i] != '\0'){
        j ^= s[++i]; // j = j XOR [next char]
    }
    if(j != 9){ // g^o^o^g^l^e = 9
        return i;
    } else {
        g(s); // infinite recursion
    }
}

Using it:

g("bing")       // 4
g("duckduckgo") // 10
g("google")     // segmentation fault

Will return the length if g XOR o XOR o XOR g XOR l XOR e isn't 9, else it will infinite recurse causing a stack overflow.

How it works

I used a (very) crappy hashing algorithm (a XOR b XOR c ...) to get a single number from the first six chars of the string. Collision likelyhood is very high, but if we assume the string has to be the name of an actual search engine, then the collision likelyhood is fairly low.

So, first we have i, which iterates through the string until s[i] is NUL (0), and while counting the length of the string, the selected char is XOR'd onto j, which is initialized to the first char in s. For "google", the result of this operation is 9.

The main thing this takes advantage of is the way pointers work in C. A pointer is actually a large number that denotes an address in memory, &var will return a pointer to var, while *var will dereference a pointer (grab the value at that address). Thus, *s is equivalent to s[0]. I think this is where most beginners get lost, confused and frustrated when it comes to C, like when you try to send a struct * to a function that takes struct * by sending &struct_ptr, which would be a memory address to a memory address, effectively making the compiler give an error such as function expects 'struct *' but got 'struct **'.

\$\endgroup\$
3
  • \$\begingroup\$ Also, this function uses no library functions. I assume using strlen and strcmp is cheating and/or not worth the #include <string.h>. \$\endgroup\$ Commented Sep 29, 2015 at 21:39
  • \$\begingroup\$ I think you need to give correct output for every string other than google. \$\endgroup\$
    – lirtosiast
    Commented Sep 29, 2015 at 21:50
  • \$\begingroup\$ @ThomasKwa Ah well, I tried. \$\endgroup\$ Commented Sep 29, 2015 at 22:02
5
\$\begingroup\$

Windows Batch, 118 characters

IF /I "%string%"=="google" exit
echo %string%> string.txt
for %%? in (string.txt) do ( SET /A stringlength=%%~z? - 2 )

Output is %stringlength%.

Full code:

@echo off
del string.txt
cls
echo Type your string
echo.
set /p string=String:
IF /I "%string%"=="google" goto err
echo %string%> string.txt
for %%? in (string.txt) do ( SET /A stringlength=%%~z? - 2 )
cls
echo %stringlength%
pause
del string.txt
:err
color c
echo There seems to be an error with your input...
pause>nul

Modified from Joshua Honig's answer, here.

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

Japt, 14 bytes

U¥`goog¤`?Þ:Ul

Try it here!

Explanation

U¥`goog¤`?Þ:Ul  
U                     // U is the input
 ¥                    // ¥ is the Unicode shortcut for ==
  goog¤               // "google" compressed
 `      `             // 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
\$\endgroup\$
2
  • \$\begingroup\$ Can you explain? \$\endgroup\$
    – Adám
    Commented Jan 10, 2017 at 23:10
  • 1
    \$\begingroup\$ @Adám Added an explanation :) \$\endgroup\$
    – Oliver
    Commented Jan 10, 2017 at 23:40
5
\$\begingroup\$

Zsh, 18 bytes

<<<$#1>$1
<^google

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.

\$\endgroup\$
4
\$\begingroup\$

><>, 55 bytes

i:0(?v
31&l~<v0"google"~~.?%2l
$v?(2l<S?*=2l=6:+={
&<;n

Figured I'd give this a go, not my best golfing attempt or algorithm, though. Not a function per se, but I think that this should still qualify. I'll see if I can edit in a better version.

If you're allowed to print the length and then error, here's a 46 byte solution:

i:0(?v
2lnl~<v0"google";?%
$;?(2l<S?*=2l=6:+={

49 byte previous solution of this nature:

i:0(?v
l0nl~<v;!?=7
:;?(2l<S?*=2l=6:+=@@g3
elgoog

I'm happy to put up an explanation if there's any interest, and please let me know if there's anything wrong with my answer or if you have golfing suggestions.

\$\endgroup\$
1
2 3 4 5 6

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