Don't google "google"

166

23

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.

rybo111

Posted 2015-09-28T16:23:13.630

Reputation: 4 359

134

I googled google, and Google found Google on Google. Myth Busted.

– Geobits – 2015-09-28T16:32:27.153

97@Geobits That is simply a test to see if I will google Google, which I will not. :D – rybo111 – 2015-09-28T16:33:22.727

Does it have to be a function? Some languages like rs only support complete programs. – kirbyfan64sos – 2015-09-29T01:09:29.393

@kirbyfan64sos An equivalent would be fine in that case – rybo111 – 2015-09-29T07:03:04.470

This conversation has been moved to chat.

– Dennis – 2015-09-29T15:40:08.307

Is no output when google is entered valid, or does it have to give some kind of error? – ASCIIThenANSI – 2015-09-30T17:46:12.850

@ASCIIThenANSI It needs to cause an error. If no output is technically an error would depend on your code. – rybo111 – 2015-09-30T17:50:46.470

7Does the function need to be case sensitive? Should it throw given 'gOOgle'? – AXMIM – 2015-09-30T22:07:02.363

2

When I type google into google (the search bar on chrome), a message came up asking if I wanted to go to https://google/. (Now that it is a tld, this makes sense i.e. https://com.google works). I clicked it and got a dns lookup error. Internet:broken!

– Craig – 2015-10-01T04:18:44.133

1@AXMIM lower-case: google – rybo111 – 2015-10-01T07:28:59.077

Oracle: 53 bytes: select length(:x)/decode(:x,'google',0,1) from dual; – Michael Broughton – 2015-10-01T19:26:00.100

2@ThomasKwa courtesy of the meta-effect and the Hot Network Questions side bar (kudos to devs, it has been a fantastic way of increasing participation) – BAR – 2015-10-02T20:18:54.223

1Why is there a close vote? "Too broad"? Other than the case sensitivity, which seems like a red herring (the question says "google" in lower-case), it looks fine. – Nick T – 2015-10-02T23:46:35.650

Unusually many querie on Google for "Google" in last few days.. it's tangetially related to everybody Googling for "Malamanteau". – Ville – 2015-10-05T21:16:42.543

I can't answer but here's my beginners prolog: g(S,L):-S\=google,string_length(S,L). g(S,L):-throw(S). - 56 chars, including the \n. – whitfin – 2015-10-06T08:17:38.590

Does it matter what error is thrown? – Carcigenicate – 2016-11-29T16:02:08.887

What if your language ignores any errors? – None – 2017-01-24T21:24:09.037

@JackBates Improvise! :) – rybo111 – 2017-01-24T21:28:50.567

@rybo111 Any suggestions? I'm not sure what you mean by improvise. – None – 2017-01-24T21:30:05.927

2@JackBates Some of the better answers on this site are the ones that find loopholes. For example, "cause an error" doesn't strictly mean "displays an error". Your function not returning a count is technically an error in of itself. – rybo111 – 2017-01-24T21:36:11.933

Thanks for the clarification! Also I can't tell if that's an insult or not? – None – 2017-01-24T21:42:35.470

Google – Gryphon – 2017-07-10T00:40:03.353

1I'm voting to close this as unclear because it is not clear what an error means in the context of this question. – Wheat Wizard – 2018-03-04T20:12:41.983

(related meta.)

– user202729 – 2018-03-09T05:02:44.910

@user202729 I'm open to edit suggestions. That's more constructive than voting to close what has proved to be a popular question IMO. – rybo111 – 2018-03-09T06:41:33.693

Probably "print more bytes to STDERR than Hello World program, content printed by compiler doesn't count"? – user202729 – 2018-03-09T06:44:09.507

@user202729 Since the function is supposed to "break", how about "if the given string is google it will not return its length." It doesn't matter how the unexpected behaviour is handled. – rybo111 – 2018-03-09T06:54:38.933

Sounds good. So "do whatever except returning its length". – user202729 – 2018-03-09T06:56:42.223

@user202729 My concerns are that such an edit might invalidate an existing answer, or sway the difficulty of the challenge. It's unfortunate that this wasn't raised when first posted. I'll give it some thought. – rybo111 – 2018-03-09T07:04:17.347

6I'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. – Poke – 2018-08-01T19:52:54.327

Answers

239

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.

xnor

Posted 2015-09-28T16:23:13.630

Reputation: 128 762

2+1. You need to set g to your lambda, or call it anonymously with an input, though. – Zach Gates – 2015-09-28T16:44:58.140

6Just for fun, I tried this technique with JavaScript ES6. It ended up at 25, but returns Infinity for "google" instead of throwing an error... – ETHproductions – 2015-09-28T16:55:12.003

20

@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.

– FryAmTheEggman – 2015-09-28T16:58:50.457

3@Kevin you would need a return if you used def – FryAmTheEggman – 2015-09-28T20:10:15.070

It's anonymous if you don't set it to anything (a def is not). A lambda like this has to be called at creation. @Kevin – Zach Gates – 2015-09-28T20:26:58.840

4Amusingly, this translated to Pyth does better than my prior best Pyth solution. It is L/lbnb"google, 13 bytes. – isaacg – 2015-11-26T06:26:00.520

Nice one, exactly what I was thinking as soon as I saw this question :) – FlipTack – 2017-02-04T16:03:54.810

111

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

Hand-E-Food

Posted 2015-09-28T16:23:13.630

Reputation: 8 262

11What's the general consensus on using Excel? – Beta Decay – 2015-09-30T17:11:50.017

54@BetaDecay. Creative, uncommon, seems to work. Won't be applicable to all CG puzzles, but it is here! – kdbanman – 2015-09-30T18:03:45.843

125Managers love it! – lkraider – 2015-09-30T18:07:28.737

22So Efficient, CG Users Will Hate You For It. But Wait. B3 Will Change Your Life Forever! – Sumurai8 – 2015-10-01T07:44:23.673

10What's the specific concensus on using Excel? – GreenAsJade – 2015-10-03T23:29:34.233

7This is certainly not the first time I've used it. I figure there's MB of libraries behind any other language used here, so this is no different. The "source code" is the code typed in cells required to meet the criteria. If code is typed in multiple cells, I count another byte per cell as a separator (like semi-colon or new-line.) If a challenge required "output for 1 to 100", copying and pasting the code into 100 cells and using the ROW() command as a counter variable is reasonable. Excel has poor recursion and variable handling so is rarely a good choice for challenges. – Hand-E-Food – 2015-10-04T21:46:15.883

1If the formula is typed into file 'google.csv' and you open The file with Excel, … – WGroleau – 2015-12-04T17:45:23.567

83

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);

DLeh

Posted 2015-09-28T16:23:13.630

Reputation: 1 131

2Yeah 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. – DLeh – 2015-10-01T20:05:59.173

6

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){}).

– NightElfik – 2015-10-06T04:15:48.327

@NightElfik interesting! Running in LinqPad I get the message Query ended because an uncatchable exception was thrown, and in VS2015 I do get an SOException but I can't catch it when i wrap in a try-catch. Very interesting, thanks for the info! It still crashes the process though, which means it still kind of behaves like an exception, just an uncatchable one. Here's a screenshot of my test code http://i.imgur.com/xVq8cI5.png

– DLeh – 2015-10-06T12:53:24.693

2

@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: http://imgur.com/ErNl8LJ and little more reading about tail recursion: http://blogs.msdn.com/b/davbr/archive/2007/06/20/tail-call-jit-conditions.aspx ;)

– NightElfik – 2015-10-10T18:52:12.637

13Haha: g(string)... I'll see myself out... – gregsdennis – 2015-11-17T01:45:17.547

@DLeh after battling for a while I think you are right.. the closest I can get is 44 bytes by causing division by zero like so int g(string s)=>s.Length/(s=="google"?0:1); – lee – 2018-03-09T00:08:01.150

or 45 bytes causing a null reference exception int g(string s)=>(s=="google"?null:s).Length; – lee – 2018-03-09T00:17:48.663

@lee yeah but that's longer :) – DLeh – 2018-03-09T02:56:23.067

1@DLeh oh wait no I can match your 43 bytes but not beat it. :) int g(string s)=>s!="google"?s.Length:s[9]; – lee – 2018-03-09T03:27:14.267

58

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)

Dennis

Posted 2015-09-28T16:23:13.630

Reputation: 200 652

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... – FryAmTheEggman – 2015-09-28T17:29:49.777

You don't need the end quote. – Maltysen – 2015-09-28T20:25:02.017

@Maltysen I think I do. The function definition wouldn't be complete without it. – Dennis – 2015-09-28T20:36:08.577

But it is complete. merely unusable ;) – Maltysen – 2015-09-28T20:53:20.487

51"Defines a named function y." But there's no y in your code!? – A.L – 2015-09-29T13:03:11.030

48@A.L That's correct. The built-in L redefines the function y. – Dennis – 2015-09-29T14:49:43.920

93I'm not sure, but I think I hate Pyth. – Mr Lister – 2015-09-30T15:36:49.253

@MrLister Yes. Implicit commands. .__. – Conor O'Brien – 2015-10-01T17:12:17.197

I can't find this Pyth language on the Intartubes. – Prof. Falken – 2015-10-01T21:05:42.947

@Prof.Falken Just click the Pyth link at the top of the online interpreter. – Dennis – 2015-10-01T21:08:08.123

@Dennis. I see. Well, I guess Pyth could get extended to add an operator to solve https://codegolf.stackexchange.com/questions/58891/dont-google-google ...

– Prof. Falken – 2015-10-01T21:48:06.780

I don't get any output when trying the link. Also, you don't seem to need the closing " – Felix Dombek – 2015-10-01T22:25:52.240

@FelixDombek The code is interpreted on the server side, which could fail for a lot of reasons. It's working fine for me. (You're the third person to suggest that I can remove the ". I'm not sure why I'm fighting this.) – Dennis – 2015-10-01T22:34:01.463

@Dennis ah, my bad, I thought I needed to put the test string in the "input" field – Felix Dombek – 2015-10-01T22:39:49.207

@FelixDombek I've edited the permalink. Input now comes from Input. – Dennis – 2015-10-01T23:06:29.287

len(b)/(b != google) : utterly awesome (possibly not the originator in this answer, but the first I've read) – GreenAsJade – 2015-10-03T23:30:51.890

42

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

rayryeng

Posted 2015-09-28T16:23:13.630

Reputation: 1 561

3You could save a byte by using strcmp instead of isequal. – Tom Carpenter – 2015-09-29T05:47:28.200

@TomCarpenter - Funny. I actually told myself to use strcmp but ended up using isequal for some reason.... thanks! – rayryeng – 2015-09-29T05:53:21.183

2nnz is two bytes shorter than numel. You had my vote a few years ago :-) – Stewie Griffin – 2017-10-17T20:13:36.187

32

JavaScript ES6, 34 27 25 characters

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

Throws a ReferenceError on Δ for google.

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

Jonathan

Posted 2015-09-28T16:23:13.630

Reputation: 541

10You could use a ternary operator to save two bytes. – Konrad Borowski – 2015-09-29T13:14:26.347

Nice one thanks – Jonathan – 2015-09-29T19:02:34.383

2Yay, 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 :) – Domino – 2015-10-01T17:07:36.743

Δ = "google is evil"; besides, I believe that these programs are self-contained. – Conor O'Brien – 2015-10-01T17:10:22.240

I would use Δ but it is 2 bytes :( – Jonathan – 2015-10-02T11:01:03.233

@Jonathan The question wants you to count "unicode characters", so I guess it's not talking about bytes, but code points. :) – heinrich5991 – 2015-10-02T19:15:22.683

1You could use #, it errors in JS afaik – clapp – 2015-10-06T01:55:51.520

7Δ Google Illuminati confirmed – None – 2015-10-07T01:59:56.313

f=>f!='google'||f.length (not an error, but false...) – Dan Eastwell – 2015-10-07T08:40:58.970

2

I'm just going to leave this here https://github.com/Rabrennie/anything.js/

– sagiksp – 2017-03-09T10:04:21.093

28

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

Conor O'Brien

Posted 2015-09-28T16:23:13.630

Reputation: 37 000

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. – lirtosiast – 2015-09-28T19:37:30.203

AGOOGLE should give 7, correct? And you shouldn't be counting the program header in your code size, so subtract 10 bytes. – lirtosiast – 2015-09-28T20:48:41.607

ERROR: I was thinking substrings. Kindly forgive me. – Conor O'Brien – 2015-09-28T20:49:37.013

1@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.) – Conor O'Brien – 2015-09-28T22:13:26.263

@lirtosiast length( is two bytes, that would make your numbers 21 and 15 bytes. – Timtech – 2016-03-29T19:28:48.173

@Timtech My mistake; Conor corrected me anyway. – lirtosiast – 2016-03-29T21:45:02.037

25

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).

marinus

Posted 2015-09-28T16:23:13.630

Reputation: 30 664

11I think you don't need to count the parens, as it can be assigned to a variable without them. – jimmy23013 – 2015-09-29T06:06:14.337

1Kind-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' – Adám – 2017-01-10T23:08:20.247

24

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.

Nick T

Posted 2015-09-28T16:23:13.630

Reputation: 3 237

works for python 2.7 too – Noodle9 – 2015-10-01T16:42:57.343

For some reason, I love this solution. – foslock – 2016-03-26T02:20:54.237

20

Haskell, 24 bytes

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

Output:

Main> g "google"

Program error: pattern match failure: g "google"

Main> g "bing"
4

chs

Posted 2015-09-28T16:23:13.630

Reputation: 301

18

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)

ಠ_ಠ

Posted 2015-09-28T16:23:13.630

Reputation: 450

2Those 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. – BAR – 2015-10-02T20:22:49.103

9I'm only missing some eval here to make it really EVIL :-) – Luis Mendo – 2015-10-05T00:11:57.303

16

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.

Dennis

Posted 2015-09-28T16:23:13.630

Reputation: 200 652

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 :( – Erik the Outgolfer – 2016-11-01T21:53:05.937

13

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!

Alex A.

Posted 2015-09-28T16:23:13.630

Reputation: 23 922

is known informally as "splat". A very appropriate name for this usage. – Adám – 2017-01-10T23:09:12.957

13

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'))

GeoffWilson

Posted 2015-09-28T16:23:13.630

Reputation: 231

2Wow, thanks for telling me there's a shorthand for lamda functions in javascript! – Tomáš Zato - Reinstate Monica – 2015-10-03T17:28:27.477

3

@TomášZato Caveat: they're brand new in ES2015, so support still varies.

– Anko – 2015-10-04T22:31:57.740

10

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.

syntonicC

Posted 2015-09-28T16:23:13.630

Reputation: 349

10Here is a slightly shorter one: g=function(x)nchar(x)[[x!="google"]] – flodel – 2015-09-29T01:38:15.170

10

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

Jarmex

Posted 2015-09-28T16:23:13.630

Reputation: 3 654

2You could make it an anonymous function: sub{…}. (Then you call it like sub{…}->("google").) – manatwork – 2015-09-29T08:30:50.840

Save 1 byte by using $_!=google instead of !/^google$/ – Gabriel Benamy – 2016-11-01T03:05:04.940

@GabrielBenamy I'm afraid != won't work to compare string... – Dada – 2017-02-16T16:24:06.477

8

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()

CoderCroc

Posted 2015-09-28T16:23:13.630

Reputation: 347

1You can also use Java 8's lambda declaration: s->(s.equals("google")?null:s).length(); – h.j.k. – 2015-09-29T03:48:35.697

3"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? – gengkev – 2015-10-06T00:52:06.020

1@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. – Yassin Hajaj – 2015-11-21T23:16:41.950

2@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. – gengkev – 2015-11-21T23:28:29.010

7

Haskell - 30 characters

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

>g "google"
 *Exception: !
>g "str"
 3

C. Quilley

Posted 2015-09-28T16:23:13.630

Reputation: 546

6Why the exclamation mark for error? Wouldn't an empty string do too? – Kritzefitz – 2015-09-28T18:36:07.540

1I 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. – Kritzefitz – 2015-09-28T18:44:06.270

18g s|s/="google"=length s avoids the need for error – chs – 2015-09-28T23:30:17.113

7

Python 3, 35 bytes

lambda n:len(n)if n!='google'else d

Zach Gates

Posted 2015-09-28T16:23:13.630

Reputation: 6 364

1@FryAmTheEggman actually 16 bits shorter. XD – DiegoDD – 2015-09-28T23:26:47.980

1@FryAmTheEggman: Good trick but id does not work with empty string: (lambda n:len(n)*(n!='google')or d)('') – pabouk – 2015-09-29T09:17:20.003

@pabouk Quite right, thanks for pointing that out. – FryAmTheEggman – 2015-09-29T12:39:49.693

7

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");

Zereges

Posted 2015-09-28T16:23:13.630

Reputation: 1 165

1You 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*. – isanae – 2015-09-28T23:35:08.143

@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. – Zereges – 2015-09-29T06:38:57.057

1

@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.

– isanae – 2015-09-29T06:42:40.663

@isanae C++14 also has "google"s to construct an std::string :) – Quentin – 2015-09-29T17:47:59.940

@Zereges you can simply throw; to trigger std::terminate() (because there's no current exception here). – Quentin – 2015-09-29T17:48:59.777

@Quentin Ah, I didn't know about ""s being a std::string in C++14, but I wont change that since I alredy marked my answer as C++11. throw; is betten, thanks. – Zereges – 2015-09-29T18:55:57.743

If you're willing to change to C++14, you could do this: [](auto s){return s=="google"?throw:s.size();};, (47 bytes) called with ("some_string"s) as @Quentin pointed out. No include needed – sweerpotato – 2015-09-30T18:45:27.860

I really want to make a C++ dialect where every std header is #included, and using namespace std; is presumed prefixed. One could go further (shorten class, struct, int main, template, typename etc), but that minimal boilerplate makes code that is perfectly understandable C++. – Yakk – 2015-09-30T20:26:50.987

@Yakk I noticed that, but I already stated, that this is C++11. Feel free to make C++14 answer yourself with that code :) – Zereges – 2015-10-01T00:02:05.860

7

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!

daniero

Posted 2015-09-28T16:23:13.630

Reputation: 17 634

Neat, I couldn't get this to work ( I didn't came up with leaving ^ outside the matchgroup). – Borsunho – 2015-09-28T18:00:34.290

@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. – daniero – 2015-09-28T18:07:31.893

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. – histocrat – 2015-09-28T18:30:19.960

@histocrat but I don't think you can google strings with multiple lines ;) – daniero – 2015-09-28T19:01:22.537

6

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

senshin

Posted 2015-09-28T16:23:13.630

Reputation: 651

6

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"))

Beta Decay

Posted 2015-09-28T16:23:13.630

Reputation: 21 982

Technically, this doesn't meet the OP's specs. This function alerts the length but returns undefined. – Bungle – 2015-09-30T05:00:12.420

@Bungle How's it now? – Beta Decay – 2015-09-30T05:57:56.837

Still the same. JavaScript functions return undefined unless you use the return keyword to explicitly return a value. You can see this by opening a browser console and declaring and executing your function. It will alert the string length but then return undefined in the console. Something like function f(g){if(g=="google")a;return g.length} would satisfy the specs and wouldn't add any bytes. – Bungle – 2015-09-30T15:27:06.663

1@Bungle I see. I forgot that a return was needed – Beta Decay – 2015-09-30T16:58:43.153

1Using ES6's arrow functions and ternary operator (instead of if), you can squeeze that a bit more :) – Carles Alcolea – 2015-10-01T21:09:54.717

@CarlesAlcolea If I did that, it would be pretty much a duplicate of another answer :P – Beta Decay – 2015-10-01T22:28:22.940

1@BetaDecay Originality first; I respect that. – Carles Alcolea – 2015-10-02T01:08:58.197

6

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");}

AShelly

Posted 2015-09-28T16:23:13.630

Reputation: 4 321

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. – Braden Best – 2015-09-29T21:46:31.467

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. – AShelly – 2015-09-30T00:25:12.947

1Anyways, +1. Definitely. Also, I think you can shorten it by removing the int, that's 4 characters. – Braden Best – 2015-09-30T02:37:29.750

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?

– Braden Best – 2015-09-30T03:12:55.860

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. – AShelly – 2015-09-30T18:07:14.927

The !! to reduce the strcmp to 1 or 0 is quite clever. Beat my solution by 3 bytes :) +1 – Cole Cameron – 2015-09-30T18:16:36.190

42 bytes as a preprocessor directive: -Dl(s)=(strlen(s)/!!strcmp((s),"Google")). – None – 2018-10-07T14:50:05.007

5

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'.

Borsunho

Posted 2015-09-28T16:23:13.630

Reputation: 261

2Why those parenthesis? x=='google'?t: x.size – manatwork – 2015-09-28T18:48:31.303

5

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.

Shane Smiskol

Posted 2015-09-28T16:23:13.630

Reputation: 161

4

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

Oliver

Posted 2015-09-28T16:23:13.630

Reputation: 7 440

Can you explain? – Adám – 2017-01-10T23:10:16.353

1@Adám Added an explanation :) – Oliver – 2017-01-10T23:40:38.253

4

GolfScript, 14 16 Characters

{.,\'google'=!/}

Like many others, simply compares the input to 'google' and divides the length by the inverse of the result.

Example programs:

p.s.w.g

Posted 2015-09-28T16:23:13.630

Reputation: 573

@Dennis I see your point. In it's original form it wasn't exactly reusable (you couldn't, say apply the code over an a list). Also I didn't realize that you had written a virtually identical answer in CJam well before I posted this (actually I was only vaguely aware of CJam as a language until now). +1 for your solution, too. – p.s.w.g – 2015-09-30T04:34:35.563

4

><>, 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.

cole

Posted 2015-09-28T16:23:13.630

Reputation: 3 886

4

Javascript ES6, 51 27 25 bytes

Hi, I'm new to code golf so this can probably be golfed much more, but here it goes:

_=>_=="google"?a:_.length

g=_=>_=="google"?a:_.length

g=_=>{if("google"==_)throw Error();return _.length}

and some test:

(_=>_=="google"?a:_.length)("bing")//4
(_=>_=="google"?a:_.length)("google")// Error: a is not defined

g("bing")// returns 4
g("google")// Error: a is not defined

Edit: Added ? to replace if and replace Error with an undefined object.

Edit 2: I realized my byte count was wrong, and removed the g=

Generic User

Posted 2015-09-28T16:23:13.630

Reputation: 373

4

Stuck, 16 Bytes

s_l1u"google"=-/

Following a similar method to most people, will cause a divide by 0 error on "google" being input.

Kade

Posted 2015-09-28T16:23:13.630

Reputation: 7 623

3

Zsh --extendedglob, 21 bytes

>$1
: ^google&&<<<$#1

Try it online!

Zsh, 23 bytes

$1()<<<$#0
google()[
$1

Try it online!

Zsh, 23 bytes

<<<$#1>$1
rm google
<$1

Try it online!

pxeger

Posted 2015-09-28T16:23:13.630

Reputation: 2 650

3

Matlab, 50 51 bytes

Thanks to @rayryeng for removing 1 byte.

This uses an anonymous function, and exploits the fact that the error function with an empty input issues no error.

It's noteworthy that the error given for input 'google' is meta: it's an error using the error function.

@(s)eval('error(find(strcmp(s,''google''))),numel(s)')

Examples:

>> @(s)eval('error(find(strcmp(s,''google''))),numel(s)')
ans = 
    @(s)eval('error(find(strcmp(s,''google''))),numel(s)')
>> ans('abcd')
ans =
     4

>> @(s)eval('error(find(strcmp(s,''google''))),numel(s)')
ans = 
    @(s)eval('error(find(strcmp(s,''google''))),numel(s)')
>> ans('google')
Error using error
The message must be specified as either a string or a message structure.
Error in @(s)eval('error(find(strcmp(s,''google''))),numel(s)')

Luis Mendo

Posted 2015-09-28T16:23:13.630

Reputation: 93 987

You could potentially save a byte if you used strcmp! – rayryeng – 2015-10-01T15:22:21.477

Slight change to your error statement... still an isequal there! – rayryeng – 2015-10-01T16:38:19.163

@rayryeng Oops... I should have pasted the new thing from scratch! Corrected, thanks – Luis Mendo – 2015-10-01T16:41:54.537

3

C# .NET, 65 bytes

int g(string s){return(s!="google")?s.Length:(1/int.Parse("0"));}

Test:

Console.WriteLine(g("str"));
Console.WriteLine(g("google"));

Salah Alami

Posted 2015-09-28T16:23:13.630

Reputation: 71

1with C# 6.0 you can save a few characters by doing an expression-bodied method: int g(string s)=>s!="google"?s.Length:(1/int.Parse("0")); – DLeh – 2015-09-28T19:18:08.260

3also you could cause an exception by recursing, eventually you'll get a stack overflow int g(string s)=>s!="google"?s.Length:g(s); – DLeh – 2015-09-28T19:19:13.180

1You can make it crash faster by just calling int.Parse(""). Although the infinite recursion strategy would be even shorter. – sara – 2015-09-29T09:23:14.973

@kai Something like "".Length is shorter than int.Parse(""). – Bob – 2015-09-29T12:41:54.877

1@Bob "".Length just returns 0, it doesn't throw. – DLeh – 2015-10-01T13:03:53.107

@DLeh Ah missed that. Whoops. – Bob – 2015-10-01T13:05:17.853

3

Common Lisp, 50 48 bytes

(defun g(s)(if(equal s"google")(g s)(length s)))

Ungolfed:

(defun g(s)                ; Define a function g with one argument s
    (if (equal s "google") ; If s == "google",
        (g s)              ; Then recurse!
        (length s)         ; Else, return the length of s in characters
    )
)

Defines a function g that accepts one string as input. If it is not exactly 'google', then it returns the length. Otherwise, it will call itself on the same string, creating an infinite recursive loop and eventually causing a stack overflow error.

Usage (inside an interactive CLISP shell):

>(load "google.lsp")
Finished loading.
>(g "foo")
3
>(g "Lisp is cool!")
13
>(g "google")
*** - Program stack overflow. RESET

This is pretty long compared to the others, but using recursion seemed fitting for Lisp.

jqblz

Posted 2015-09-28T16:23:13.630

Reputation: 2 132

3This won't cause a stack overflow in some Common Lisp implementations (CCL and SBCL won't overflow). – nanny – 2015-09-28T20:57:14.697

3

PHP 5.4+, 40 49 bytes

This one is quite unexpectedly long.

function g($x){echo[strlen($x),[]][$x==google];}

To run it, just pass a value:

g($argv[1]);

Test-cases:

$php google.php googlea
7
$php google.php google
Notice: Array to string conversion in [...][...] on line 1
Array

I'm not sure if this can ve considered an error for this challenge or not.


One could use the over-used boring method:

function g($x){echo strlen($x)/$x==google;}

Which gives me a size of only 43 bytes.


As an alternative, one could use an exit error code, using the exit construct, for also 49 bytes:

function g($x){exit($x==google?strlen($x).'':1);}

All values between 1 and 254 are valid error codes that PHP uses when exiting.

Ismael Miguel

Posted 2015-09-28T16:23:13.630

Reputation: 7 200

You could use function g($x){echo$x==google?a():strlen($x);} which is 46 bytes (3 bytes shorter) and throws an actual error and not just a warning. Also your second example function g($x){echo strlen($x)/$x==google;} should be: function g($x){echo strlen($x)/($x!=google);}. / has a higher precedence than == and you have to switch it to !=as well to make it work. – insertusernamehere – 2015-11-16T22:53:44.357

3

Perl 6, 19 bytes

{.comb/!/^google$/}

.comb returns list of characters in string (which in numeric context is a number of characters, I use this instead of .chars because it's shorter). Because there is nothing before a period, Perl 6 assumes you wanted to call a method on $_. This is divided by a negated match on regex ^google$ with implicit $_ variable. If it matches, the value becomes 0, and Perl 6 errors because of a division by zero.

Example:

> {.comb/!/^google$/}("qwerty")
6
> {.comb/!/^google$/}("google")
Attempt to divide 6 by zero using div
  in any interactive at src/Perl6/Compiler.nqp line 62

Konrad Borowski

Posted 2015-09-28T16:23:13.630

Reputation: 11 536

3

Scala, 48

def g(s:String)=if(s=="google")0/0 else s.length

To call:

 g("bing")      //> res1: Int = 4
 g("google")    //> java.lang.ArithmeticException: / by zero

ekrich

Posted 2015-09-28T16:23:13.630

Reputation: 131

you can use an anonymous function, and shave off 4 characters. also, it will be more neat, IMHO, to use ??? rather than 0/0. – Jacob – 2016-03-27T14:55:14.393

3

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 **'.

Braden Best

Posted 2015-09-28T16:23:13.630

Reputation: 161

Also, this function uses no library functions. I assume using strlen and strcmp is cheating and/or not worth the #include <string.h>. – Braden Best – 2015-09-29T21:39:52.877

I think you need to give correct output for every string other than google. – lirtosiast – 2015-09-29T21:50:25.893

@ThomasKwa Ah well, I tried. – Braden Best – 2015-09-29T22:02:22.457

3

bash + coreutils, 57 49 38 36 33 bytes

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

Calling it with google produces expr: division by zero.

The quotes around $1 are required in order to handle the empty string correctly.

The use of ${#1} is shamelessly stolen from Tarod's answer.

Ben

Posted 2015-09-28T16:23:13.630

Reputation: 380

Good! But I think you're mixing bash & linux commands. If you want to, check my answer where I'm using bash to count characters. Happy coding! :) – Tarod – 2015-09-29T21:57:58.300

@Tarod You're right, I should have said bash + coreutils. Combining your use of Bash to count the length of the input with my use of expr allows a shorter answer than either though - see my edit. – Ben just now edit – Ben – 2015-09-29T22:22:44.287

Amazing! :D I'm going to upvote you! Good job, Ben! :) – Tarod – 2015-09-30T06:08:38.980

BTW, I think you should set a new title for your answer. Just 'bash'. – Tarod – 2015-09-30T11:55:00.630

I don't think so - expr seems to be part of coreutils.

– Ben – 2015-09-30T13:16:16.580

It's true. Thanks! – Tarod – 2015-10-01T08:02:04.163

3

O, 20 characters

{."google"={@}{.e}?}

Sample run:

bash-4.3$ java xyz.jadonfowler.o.O <( echo '{."google"={@}{.e}?} :f "yahoo" f o' )
5

bash-4.3$ java xyz.jadonfowler.o.O <( echo '{."google"={@}{.e}?} :f "google" f o' )
java.lang.ArrayIndexOutOfBoundsException: Can't pop from empty stack!
        at xyz.jadonfowler.o.Stack.pop(O.java:980)
        at xyz.jadonfowler.o.O.parse(O.java:407)
        at xyz.jadonfowler.o.CodeBlock.run(O.java:1031)
        at xyz.jadonfowler.o.O.parse(O.java:735)
        at xyz.jadonfowler.o.CodeBlock.run(O.java:1031)
        at xyz.jadonfowler.o.O.parse(O.java:99)
        at xyz.jadonfowler.o.O.runFile(O.java:37)
        at xyz.jadonfowler.o.O.main(O.java:20)
java.lang.ArrayIndexOutOfBoundsException: Can't pop from empty stack!
        at xyz.jadonfowler.o.Stack.pop(O.java:980)
        at xyz.jadonfowler.o.O.parse(O.java:425)
        at xyz.jadonfowler.o.O.runFile(O.java:37)
        at xyz.jadonfowler.o.O.main(O.java:20)

manatwork

Posted 2015-09-28T16:23:13.630

Reputation: 18 847

3

Scala, 36 34 30 29 characters

s=>(Set(s)-"google").max.size

Calling this function on "google" produces java.lang.UnsupportedOperationException: empty.max

Ben

Posted 2015-09-28T16:23:13.630

Reputation: 380

Nice idea! However, I'm afraid it does not compile, one must declare s's type: (s:String)=>... When I copy-paste it to scala's REPL I get <console>:1: error: ';' expected but '=>' found. – Jacob – 2016-03-27T14:58:12.100

@Jacob it compiles if the type of s can be inferred from the context, e.g.: val s: String => Int = s=>(Set(s)-"google").max.size. – Ben – 2016-03-27T21:57:55.697

If you want us to use it like that, you must add val s:String=>Int= to your answer. The answer should be a valid Scala expression as-is. – Jacob – 2016-03-28T02:06:11.070

@Jacob it is a valid Scala expression as-is: an anonymous function is a perfectly valid self-contained answer. Valid Scala expressions aren't only those that can be pasted into the Scala REPL without context. The question asks for a function that takes a string and returns an integer: in contexts in which such a function is expected, the answer will compile. However, feel free to take this to Meta. – Ben – 2016-03-28T08:48:45.430

3

Java, 84 68 37 bytes

b->b.equals("google")?1/0:b.length();

This is a java.util.function.Function<String, Integer> that divides by 0 if b is the string google.

dorukayhan

Posted 2015-09-28T16:23:13.630

Reputation: 1 282

2

JavaScript, 25 bytes

p=>p=='google'?_:p.length

Oliver

Posted 2015-09-28T16:23:13.630

Reputation: 7 440

“However, if the given string is google (lowercase), it will cause an error.” – Will this? – manatwork – 2016-11-29T15:15:34.890

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. – manatwork – 2016-11-29T15:38:43.533

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} – ETHproductions – 2016-11-29T16:44:06.030

Also, you don't have to explicitly throw an error; calling some undefined variable, such as _, will do the trick. – ETHproductions – 2016-11-29T16:44:55.223

2

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);');}

Titus

Posted 2015-09-28T16:23:13.630

Reputation: 14 172

2

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!

steenbergh

Posted 2015-09-28T16:23:13.630

Reputation: 7 844

2

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

caird coinheringaahing

Posted 2015-09-28T16:23:13.630

Reputation: 24 300

2

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!

RaviRavioli

Posted 2015-09-28T16:23:13.630

Reputation: 1 464

2

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.

Tornado547

Posted 2015-09-28T16:23:13.630

Reputation: 837

2

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).

Unrelated String

Posted 2015-09-28T16:23:13.630

Reputation: 8 486

2

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

user85052

Posted 2015-09-28T16:23:13.630

Reputation:

2

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!

Satoshi

Posted 2015-09-28T16:23:13.630

Reputation: 23

1

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

– caird coinheringaahing – 2021-02-20T20:16:46.133

@cairdcoinheringaahing thank you^^ – Satoshi – 2021-02-20T20:19:10.540

2

Julia, 25 bytes

x->length(x)[x!="google"]

Try it online!

MarcMush

Posted 2015-09-28T16:23:13.630

Reputation: 1 031

2

CoffeeScript 43 bytes

(g)->return g.length if g!="google";throw-1

Makes an anonymous function that throws -1 if the string is "google", and returns it's length otherwise. Not as obfuscated as I wanted, though.

Link to the online testing environment.

Another variation, 1 byte longer:

(g)->if g!="google"then g.length else throw-1

Bojidar Marinov

Posted 2015-09-28T16:23:13.630

Reputation: 209

Nah, too late. There is already a better answer in CoffeeScript... – Bojidar Marinov – 2015-09-28T18:15:50.817

2

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

AdmBorkBork

Posted 2015-09-28T16:23:13.630

Reputation: 42 210

you can use param($a)$a.length/($a-cne'google') to skip using the the !, saving one byte. – colsw – 2016-11-29T10:57:41.440

@ConnorLSW Indeed. Thanks. – AdmBorkBork – 2016-11-29T15:54:44.577

2

PHP 5.4, 81 bytes

<?function g($s){eval('if(isset('.($s==google?"$s":'$s').'))print strlen($s);');}
// following added for easy testing, not included in bytes count
g($argv[1]);

Everyone's favourite error when searching for Google! Didn't work out quite as obfuscated as I'd hoped...

Usage:

php 58891.php 'test'
4
php 58891.php 'google'
# error

Dom Hastings

Posted 2015-09-28T16:23:13.630

Reputation: 19 484

1Just thought I'd point this out: the challenge ID is 58891, not 85591. Otherwise, good job! – clapp – 2015-10-06T01:59:23.193

1@ConfusedMr_C hah, good spot! I'd like to say I did that deliberately, but that would definitely be a lie! – Dom Hastings – 2015-10-06T04:43:00.790

2

Lua, 42 Bytes

This challenge has made me realize how hard it is to cause an error in Lua.

x=io.read()print(x~="google"and #x or t())

Takes an input and if that input isn't google than print the length of the input, if not call a function t which doesn't exist, throwing an error.

Nico A

Posted 2015-09-28T16:23:13.630

Reputation: 2 490

Can shave off one byte by removing the space before the '#x'. – ouflak – 2018-11-22T16:27:29.450

Can shave off two more bytes on top of that by saying 'or~x' instead of 'or t()'. Throws a conversion error. – ouflak – 2018-11-22T16:38:22.420

2

PARI/GP, 21 19 bytes

x->#x/(x!="google")

Example:

? g = x->#x/(x!="google")
%1 = (x)->#x/(x!="google")
? g("bing")
%2 = 4
? g("google")
  ***   at top-level: g("google")
  ***                 ^-----------
  ***   in function g: #x/(x!="google")
  ***                    ^--------------
  *** _/_: impossible inverse in dvmdii: 0.
  ***   Break loop: type 'break' to go back to GP prompt
break> 

alephalpha

Posted 2015-09-28T16:23:13.630

Reputation: 24 427

2

Prolog – 32 bytes

"google"*_:-x.
X*Y:-length(X,Y).

Defines a predicate (*)/2 that throws ERROR: */2: Undefined procedure: x/0 for the input "google":

?- "bing" * Length.
Length = 4.

?- "google" * Length.
ERROR: */2: Undefined procedure: x/0
   Exception: (8) x ? no debug

kay

Posted 2015-09-28T16:23:13.630

Reputation: 230

Ha nice! I tried a Prolog one and only got 56 chars (I'm a beginner). What does the * do? – whitfin – 2015-10-06T08:21:06.237

1

@zackehh *, +, ... are valid names for predicates. They have to be written in infix notation and are quite handy for golfing because you can omit the parentheses and the comma for a predicate with two argument. a(A,B):-A is B.A*B:-A is B.: 3 bytes saved for every invocation.

– kay – 2015-10-06T11:22:55.037

1learn something new every day, thanks! ;) – whitfin – 2015-10-06T15:11:53.337

2

PHP error via a warning(), 62, 52 46 bytes

I feel dirty for these, but it isn't about pretty:

function g($s){echo$s!=google?strlen($s):g();}

This will give "Warning: Missing argument 1 for g()" when you insert 'google', thought that was funny.

function g($s){echo$s!=google?strlen($s):die(err);}

function g($s){if($s!=google){return strlen($s);}die(error);}

PHP error as string, 46 bytes

function g($s){echo$s!=google?strlen($s):err;}

String dont have to be quoted (but should be!)


You can run these via the commandline using g($argv[1]);, or via an older PHP version's register_globals method as an GET g($_GET['string']) or whichever :)

Martijn

Posted 2015-09-28T16:23:13.630

Reputation: 733

If it is to play a bit 'dirty', you could use err instead, since it is a common abbreviature – Ismael Miguel – 2015-09-29T14:14:51.943

You mean instead of the string 'error'? I wan't too sure about wether to count those bytes, so I just left it there, it's about the logic anyways. – Martijn – 2015-09-29T14:16:14.670

It is. But hey, everybody knows what err means, and you save 2 bytes! Some used undefined variables to show errors. Why can't you use an abbreviation!? – Ismael Miguel – 2015-09-29T14:24:29.757

I guess your right, changed it. Still thinking of another method. I could simply call a undefined function, would safe me even more, but I tough of that as cheating – Martijn – 2015-09-29T14:57:53.750

I don't see it as cheating. But function g($s){$a=$s==google?:strlen;echo$a($s);} is 49 bytes long. – Ismael Miguel – 2015-09-29T15:19:41.113

That doesnt work when I try it (unexpected :), php 5.4, even before calling it :( – Martijn – 2015-09-30T09:00:19.620

It works for me: http://sandbox.onlinephpfunctions.com/code/e233f4c02b38825871a1b912991da08177a1bcc3

– Ismael Miguel – 2015-09-30T09:02:56.050

Af, after examining it, this wont work in my current php version, but clever method. I can;t use this technique yet, so it took me a moment ^_^. I came up with another method, which I also like, 46 bytes! – Martijn – 2015-09-30T09:09:22.143

1That's quite a funny alternative! I wouldn't have though of that! – Ismael Miguel – 2015-09-30T09:10:43.033

2

rs, 31 bytes

^(google)|(.*)$/((^^\2))^^(1\1)

In rs, ^^ is the length and repetition operator. Used in the unary form, it will get the length of the following text (^^\2). Used in binary form, it will repeat the LHS RHS times ((^^\2))^^(1\1).

Take the input bing. The input is not google, so the second group will match, not the first. Once the substitutions take place, the result is ((^^bing))^^(1). ^^ gets the length to result in (4)^^(1), and the result gets repeated 1 time to result in 4.

However, if the input is google, the first group will match. That will result in ((^^))^^(1google) after substitutions. ^^ will just get the length of the empty string (0), so the result after ^^ is applied will be (0)^^(1google). Now the repetition operator can do its work...or not. See it will try to repeat 0 1google times. As 1google isn't a number, the output will be:

Traceback (most recent call last):
  File "c callback", line 6, in <module>
  File "<string>", line 5, in <module>
  File "<string>", line 167, in main
  File "<string>", line 125, in run
  File "<string>", line 72, in expand
ValueError: invalid literal for int() with base 10: '1google'

Live demo. (Put the input text in the box at the bottom left.)

kirbyfan64sos

Posted 2015-09-28T16:23:13.630

Reputation: 8 922

2

C# 4.0, 51 bytes

int g(string s){return s.Length/(s!="google"?1:0);}

Sample:

string userInput = Console.ReadLine();
Console.WriteLine(g(userInput));

Output:

// "pogi" 4
// "google" DivideByZeroException was unhandled

peter saliente

Posted 2015-09-28T16:23:13.630

Reputation: 21

2

C++14, 47 bytes

[](auto s){return s=="google"?throw:s.size();};

This is a generic lambda expression in C++14. It simply checks if the argument (string) is "google" and calls terminate if it is - else it returns the length of the string.

It can be called as such:

[](auto s){return s=="google"?throw:s.size();}("some_string"s);

Zereges has a very similar answer here written in C++11. Since this was C++14 it was O.K. by him for me to post this.

sweerpotato

Posted 2015-09-28T16:23:13.630

Reputation: 2 467

2

Befunge-93, 59 characters

<+1\_v#+1:~
vp00$<
<*_v#:\
v_v>$"google"*****-!#
< >00g.@>1

Befunge has no way to actually throw an error, so I just push an "infinite" number of 1s onto the stack. An error will happen somewhere eventually...

Explanation

Anyway, this works by reading in the input and simultaneously keeping track of its length.

<+1\_v#+1:~

This length is stored at location 0,0.

vp00$<

The remaining numbers are multiplied together.

<*_v#:\

This is then compared to the product of "google".

v_v>$"google"*****-!#

If they are the same (i.e., if their difference is zero), then the "error" is thrown. Otherwise, the value stored at 0,0 is retrieved and outputted.

< >00g.@>1

El'endia Starman

Posted 2015-09-28T16:23:13.630

Reputation: 15 112

2

O, 17 bytes

{e\"google"=L@N?}

To use this function:

"wow" {e\"google"=L@N?} ~

Explanation:

e\               Get the length of the string and swap it on the stack
  "google"=      Compare the string
               ? If
            L@    True (it is google): Rotate top three elements on the stack, throwing an underflow error
              N   False (it is not google): do nothing
                   Length is printed out automatically

phase

Posted 2015-09-28T16:23:13.630

Reputation: 2 594

2

Japt, 16 14 bytes (non-competing)

U¥`goog¤`?Δ:Ul

Throws reference error on input of "google". Try it online!

noisyass2

Posted 2015-09-28T16:23:13.630

Reputation: 211

Nice! Two tips: 1) "google" can be compressed to goog¤, wrapped in backticks. 2) == can be compressed to ¥. – ETHproductions – 2015-11-26T15:36:34.003

Totally ignored compression. I have only scratched the surface of your language @ETHproductions, and thought this may be a great starting point for it. The \u<hex> shorthands are easily missable, better put it inside the docs. – noisyass2 – 2015-11-27T02:24:39.803

I've added a section on Unicode shortcuts in the online interpreter. @ThomasKwa You are correct. I've edited the post.

– ETHproductions – 2015-12-04T17:14:43.943

2

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}

Vasu Adari

Posted 2015-09-28T16:23:13.630

Reputation: 939

Couple of tips to shorten it: new(0)new 0; nilp. Possibly more tips to shorten it: Tips for golfing in Ruby.

– manatwork – 2015-11-26T15:44:37.713

Found different approach. Thanks anyway :) @manatwork – Vasu Adari – 2015-11-26T15:59:03.557

Interesting. Which Ruby version? The 2.1.5 I use has no String#to_a method. But with the shorter [g]-['google'] works. – manatwork – 2015-11-26T16:02:03.000

I missed it. Thank you very much :). My ruby version is 2.0.0p576. – Vasu Adari – 2015-11-26T16:08:36.140

2

05AB1E, 10 bytes (non-competing)

Non-competing, since the language postdates the challenge.

Code:

g“Š¹“¹Q</Ä

Explanation:

g           # Take the length of the implicit input
 “Š¹“       # Compressed version of "google"
     ¹Q     # Take the first input again and check if equal to "google"
       <    # Decrement on the bool
        /   # Divide the length by the value
         Ä  # Take the abstract value of the result
            # This is then implicitly printed

Try it online!. When the input is google, nothing is printed due to a division by zero exception.

Adnan

Posted 2015-09-28T16:23:13.630

Reputation: 42 659

1*absolute value – Oliver Ni – 2017-02-06T02:08:27.293

2

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. :)

Robert Benson

Posted 2015-09-28T16:23:13.630

Reputation: 1 429

1+1 for "Segmentation fault (core dumped)" -- my favourite error message – cat – 2016-03-25T15:46:48.820

It's my favorite message, too... if I'm not the one that has to debug it. :p – Robert Benson – 2016-03-25T16:04:08.630

1On 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. – cat – 2016-06-28T13:34:28.853

My testing was done on a RHEL 6 machine with 128GB of RAM so thanks for the info @cat – Robert Benson – 2016-06-28T16:24:33.900

1Aha! 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 – cat – 2016-06-28T16:32:26.603

At least it still satisfies the task, since Killed is still a nifty error :) – Robert Benson – 2016-06-28T16:42:08.687

1It's not wrong at all, I think recursing forever and possibly forcing a shutdown is a perfectly acceptable error – cat – 2016-06-28T16:52:57.807

2

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.

STDQ

Posted 2015-09-28T16:23:13.630

Reputation: 141

Alright, wasn't sure if I could post multiple answers to a solution @lirtosiast , thanks! – STDQ – 2016-03-26T20:20:07.273

2

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.

M L

Posted 2015-09-28T16:23:13.630

Reputation: 3 015

2

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.

Rɪᴋᴇʀ

Posted 2015-09-28T16:23:13.630

Reputation: 7 376

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̨̥̫͎̭ͯ̿̔̀ͅ – cat – 2016-03-26T12:10:59.603

-1 for unmatched quotes ಠ_ಠ – cat – 2016-03-26T12:15:06.933

@tac they represent the beginning and end of the string literal. That is intentional. – Rɪᴋᴇʀ – 2016-03-26T15:31:18.903

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) – cat – 2016-03-26T15:32:49.857

@tac I can make it work with matched ones also if you want. – Rɪᴋᴇʀ – 2016-03-26T15:39:06.930

Well, I was mostly being facetious -- you don't have to change it, sorry. – cat – 2016-03-26T15:40:26.703

eh. I was being lazy earlier, and was thinking it would be easier to use unmatched ones. You can just add 1, so fixed now. – Rɪᴋᴇʀ – 2016-03-26T15:43:51.907

Let us continue this discussion in chat.

– Rɪᴋᴇʀ – 2016-03-26T15:44:07.033

2

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                                             ”

Zach Gates

Posted 2015-09-28T16:23:13.630

Reputation: 6 364

Note: this answer is non-competing. – Zach Gates – 2016-03-26T03:39:06.933

1Gogh is epic. Just saying. – Rɪᴋᴇʀ – 2016-03-26T03:53:50.690

2

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");}

STDQ

Posted 2015-09-28T16:23:13.630

Reputation: 141

2

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]

RenderSettings

Posted 2015-09-28T16:23:13.630

Reputation: 650

Um... is that supposed to link to urbit? – Destructible Lemon – 2016-11-20T09:55:20.690

@DestructibleWatermelon Yup. Urbit provides the compiler/interpreter for the Hoon language. – RenderSettings – 2016-11-21T04:00:59.780

2

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^.

m654

Posted 2015-09-28T16:23:13.630

Reputation: 753

1

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

nyuszika7h

Posted 2015-09-28T16:23:13.630

Reputation: 1 725

1

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 %)))

Carcigenicate

Posted 2015-09-28T16:23:13.630

Reputation: 3 405

1

tcl, 46

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

demo

sergiol

Posted 2015-09-28T16:23:13.630

Reputation: 3 128

1

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

12Me21

Posted 2015-09-28T16:23:13.630

Reputation: 6 290

1

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

Christopher

Posted 2015-09-28T16:23:13.630

Reputation: 3 524

Who edited it? Because you aren't allowed to edit a language to improve your score. – None – 2017-01-24T23:06:37.780

I did not edit it. The khanacademy team edited it. https://github.com/Khan/processing-js It is its own fork.

– Christopher – 2017-01-24T23:17:36.300

That's ok then. Just checking ;) – None – 2017-01-24T23:37:03.690

Yeah otherwise my language would be called g. It would just have functions called with one byte :P – Christopher – 2017-01-24T23:38:15.820

Smart idea! Why don't you make it? – None – 2017-01-24T23:54:28.107

It is against the rules. – Christopher – 2017-01-24T23:56:08.987

Just say that it's non competing. Check mine above you. – None – 2017-01-24T23:57:30.557

Let us continue this discussion in chat.

– None – 2017-01-24T23:57:34.573

1

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)

Value Ink

Posted 2015-09-28T16:23:13.630

Reputation: 11 196

1

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)

Oliver Ni

Posted 2015-09-28T16:23:13.630

Reputation: 9 958

There's no error in 05AB1E. It just doesn't push a result. – Erik the Outgolfer – 2017-04-06T12:01:05.047

1

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

seshoumara

Posted 2015-09-28T16:23:13.630

Reputation: 3 417

1

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.

MD XF

Posted 2015-09-28T16:23:13.630

Reputation: 12 356

2How does this return the length of the string? It seems like this would return a negative result in some cases. – Esolanging Fruit – 2018-03-08T21:38:24.453

1

Mathematica, 33 bytes

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

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

totallyhuman

Posted 2015-09-28T16:23:13.630

Reputation: 15 657

1

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.

Magic Octopus Urn

Posted 2015-09-28T16:23:13.630

Reputation: 19 936

....0 is divide by 0? Why? – ETHproductions – 2017-10-17T19:06:56.370

Why the built-in in the first place when 0/ could have achived the same result with the same bytecount? – None – 2020-01-02T10:29:19.207

1

Common Lisp, 50 bytes

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

Try it online!

Renzo

Posted 2015-09-28T16:23:13.630

Reputation: 2 370

1

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

Weijun Zhou

Posted 2015-09-28T16:23:13.630

Reputation: 3 486

1

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!

Yaroslav Gaponov

Posted 2015-09-28T16:23:13.630

Reputation: 371

1

05AB1E, 8 bytes

'Š¹QiFëg

Try it online! Beats all other answers. There is another 8-byte 05AB1E answer, but that one seems to work just fine with google as input.

'Š¹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

Makonede

Posted 2015-09-28T16:23:13.630

Reputation: 1 361

1

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.

MLavrentyev

Posted 2015-09-28T16:23:13.630

Reputation: 283

1

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'

Gotoro

Posted 2015-09-28T16:23:13.630

Reputation: 139

1-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 – Makonede – 2021-02-21T22:24:16.170

1

Whispers v1, 53 bytes

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

Try it online!

Michael Chatiskatzi

Posted 2015-09-28T16:23:13.630

Reputation: 806

1

Vyxal, 8 bytes

ı•÷?₌L≠/

Try it Online!

ı•÷?₌L≠/
ı•÷       # "google" 
   ?      # input
    ₌L≠/. # length(^) / (^ != ^^)

If the string is google, then the program will error when trying to divide by 0 (google != google -> 0). Otherwise, it divides the length by 1 (which gives the same integer)

Lyxal

Posted 2015-09-28T16:23:13.630

Reputation: 11 711

You might want to clarify that it's length(^) / (^ != ^^) instead of (length(^) / ^) != ^^. – Wezl – 2021-02-22T16:02:28.830

1

CoffeeScript, 36 bytes

f=(x)->throw 0if'google'==x;x.length

rink.attendant.6

Posted 2015-09-28T16:23:13.630

Reputation: 2 796

1

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:

manatwork

Posted 2015-09-28T16:23:13.630

Reputation: 18 847

1

Emacs Lisp, 43 bytes

(lambda(s)(if(equal s"google")*(length s)))

Throws the error (void-variable *) for any string that equals google.

nanny

Posted 2015-09-28T16:23:13.630

Reputation: 171

@FryAmTheEggman I'm sorry, I just wrote the explanation wrong, the code is correct. – nanny – 2015-09-28T18:55:05.437

1

STATA, 44 bytes

pr de a
if"google"==`0' f
di length(`0')
end

prints "unrecognized command: f" when input is "google"

bmarks

Posted 2015-09-28T16:23:13.630

Reputation: 2 104

1

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]"}~}

user52889

Posted 2015-09-28T16:23:13.630

Reputation: 211

1

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

p.s.w.g

Posted 2015-09-28T16:23:13.630

Reputation: 573

1

><>, 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

DanTheMan

Posted 2015-09-28T16:23:13.630

Reputation: 3 485

1

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

Daniel M.

Posted 2015-09-28T16:23:13.630

Reputation: 3 769

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. – Alex A. – 2015-09-29T15:53:26.267

@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 http://codegolf.stackexchange.com/a/58981/41505)

– Daniel M. – 2015-09-29T16:31:18.917

You are going to have to change == to .equals unless I'm missing something with java 8 – jlars62 – 2015-10-02T16:55:49.567

It worked for me using the provided implementation. It may be a subtle difference between String objects and literals, but it works for me – Daniel M. – 2015-10-02T17:08:54.913

1

Lua, 47 bytes

print(assert(arg[1]~="google")and arg[1]:len())

Throws "assertion failed" if it's "google"

Trebuchette

Posted 2015-09-28T16:23:13.630

Reputation: 1 692

1

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

manatwork

Posted 2015-09-28T16:23:13.630

Reputation: 18 847

1

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

cfx

Posted 2015-09-28T16:23:13.630

Reputation: 11

1

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.

axiac

Posted 2015-09-28T16:23:13.630

Reputation: 769

1You get a +1 from me for the division-by-zero, clever! But a -1 for not making it a function as the topic states :) – Martijn – 2015-09-29T12:53:35.413

1-2 bytes: The quotation marks are unnecessary. – Titus – 2016-11-29T15:48:25.790

1

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.

Kametrixom

Posted 2015-09-28T16:23:13.630

Reputation: 426

1

Hassium, 52 Bytes

func g(s){if(s=="google")throw("");return s.length;}

Run and see expanded here

Jacob Misirian

Posted 2015-09-28T16:23:13.630

Reputation: 747

1func g(s)return(s == "google")?throw():s.length; is a bit shorter. – Dennis – 2015-10-01T05:42:03.873

@Dennis Actually, it is 32 bits shorter. – Ismael Miguel – 2015-10-05T02:17:56.687

1

Haskell, 24 characters

g n|n/="google"=length n

"Unexhaustive patterns" if you pass it "google".

Ludwik

Posted 2015-09-28T16:23:13.630

Reputation: 111

1

bash, 55 51 34 bytes

Thanks @manatwork!

[ "$1" != google ]&&echo ${#1}||0

It prints command not found if $1 is google.

Tarod

Posted 2015-09-28T16:23:13.630

Reputation: 181

Shorter? [ "$1" != google ]&&echo ${#1}||0 – manatwork – 2015-09-30T09:16:30.850

@manatwork Shorter & beautiful! – Tarod – 2015-09-30T10:30:21.740

1

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.

Édouard

Posted 2015-09-28T16:23:13.630

Reputation: 245

1

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.

maharvey67

Posted 2015-09-28T16:23:13.630

Reputation: 141

1

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)}

djechlin

Posted 2015-09-28T16:23:13.630

Reputation: 111

There's already a shorter answer.

– lirtosiast – 2015-09-30T02:39:11.490

1

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.

Bungle

Posted 2015-09-28T16:23:13.630

Reputation: 111

1

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.

TellsTogo

Posted 2015-09-28T16:23:13.630

Reputation: 11

You can shorten {L[} to qL[. q is a syntax prefix as a shortcut for Blocks that only contain one value. – mroman – 2018-11-15T12:36:07.757

1

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'])

Michael Kay

Posted 2015-09-28T16:23:13.630

Reputation: 191

1

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

func g(s string)int{if s=="google"{panic(0)};return len(s)}

user45561

Posted 2015-09-28T16:23:13.630

Reputation:

2Welcome 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. – Jakube – 2015-09-30T10:09:45.343

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 – None – 2015-10-01T14:07:37.153

1using panic() instead of returning error saves some bytes: func g(s string)int{if s=="google"{panic("")};return len(s)} (60 bytes) – Fabian Schmengler – 2015-10-03T16:59:51.893

1

PowerShell, 42 bytes

function g($x){$x.Length/($x-ne'google')}

Sean

Posted 2015-09-28T16:23:13.630

Reputation: 141

1

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 :(

Erik

Posted 2015-09-28T16:23:13.630

Reputation: 11

1

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.

ASCIIThenANSI

Posted 2015-09-28T16:23:13.630

Reputation: 1 935

Wouldn't save more by returning, but implicitly, without using the return keyword? sub g{length($_[0]=~"google"?1/0:$_[0])} – manatwork – 2015-09-30T18:13:29.077

@manatwork I'll add that in. Thanks! – ASCIIThenANSI – 2015-09-30T19:04:37.300

1This 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$/} – Grimmy – 2015-10-05T11:32:18.397

@Grimy Thanks for pointing that out, I've added that in. – ASCIIThenANSI – 2015-10-09T20:21:50.543

1

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.

SparkX120

Posted 2015-09-28T16:23:13.630

Reputation: 11

1

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.

MegaTom

Posted 2015-09-28T16:23:13.630

Reputation: 4 011

1

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.

AXMIM

Posted 2015-09-28T16:23:13.630

Reputation: 209

1

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.

downrep_nation

Posted 2015-09-28T16:23:13.630

Reputation: 1 152

1

><>, 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.

Sok

Posted 2015-09-28T16:23:13.630

Reputation: 5 862

1

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.

Alex Shroyer

Posted 2015-09-28T16:23:13.630

Reputation: 770

1

Python, 47 bytes

a=input()
print(0/0 if a=="google" else len(a))

m654

Posted 2015-09-28T16:23:13.630

Reputation: 753

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. – cat – 2015-11-21T22:21:06.107

1

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

Adam Katz

Posted 2015-09-28T16:23:13.630

Reputation: 336

1

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.

cat

Posted 2015-09-28T16:23:13.630

Reputation: 5 297

1

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.

Steve Matthews

Posted 2015-09-28T16:23:13.630

Reputation: 131

1

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>

Zach Gates

Posted 2015-09-28T16:23:13.630

Reputation: 6 364

1

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.

Ashwin Gupta

Posted 2015-09-28T16:23:13.630

Reputation: 481

1Actually, I could just divide the string google by a number and get some type-mistmatch error – Ashwin Gupta – 2015-12-04T17:45:28.000

Wouldn't a type mismatch be checked at compile time, not run time, because of type erasure? – cat – 2016-03-25T15:49:36.500

@tac probably. Could be a workaround through try catch – Ashwin Gupta – 2016-03-25T17:16:12.110

1

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)

QuertyKeyboard

Posted 2015-09-28T16:23:13.630

Reputation: 71

1

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.

Stuart Bruff

Posted 2015-09-28T16:23:13.630

Reputation: 511

1

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()}

STDQ

Posted 2015-09-28T16:23:13.630

Reputation: 141

1

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

Timtech

Posted 2015-09-28T16:23:13.630

Reputation: 12 141

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. – lirtosiast – 2016-03-29T21:45:59.027

1

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.

user47018

Posted 2015-09-28T16:23:13.630

Reputation:

1

Pyth, 12 bytes

/lznz"google

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

penalosa

Posted 2015-09-28T16:23:13.630

Reputation: 533

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.

– James – 2016-04-26T20:39:15.050

@DrGreenEggsandHamDJ Try it here

– penalosa – 2016-04-26T20:48:13.230

The spec asks for a function. This is a full program. – Dennis – 2016-11-21T00:21:28.470

0

Excel VBA, 52 Bytes

Subroutine that take input a as unassigned/variant of expected type variant/String and outputs to the VBE Immediates window. If a = "google" throws Run-time error '3': Return without GoSub else outputs the length of the input a.

Sub g(a)
If a="google"Then Return
Debug.?Len(a)
End Sub

Taylor Scott

Posted 2015-09-28T16:23:13.630

Reputation: 7 199

0

shortC, 21 bytes

Df(s)Ss)/Ms,"google")
  • Df(s) defines a function f that takes one argument s.
  • Ss) calculates the length of s.
  • Ms,"google) compares s to "google".
  • Ss)/Ms,"google") divides the length of s by 0 if the strings are equal. This throws floating point exception if they're equal.

Try it online!

MD XF

Posted 2015-09-28T16:23:13.630

Reputation: 12 356

0

Syms, 18 bytes

{[#~{google}=!1/]}

Try it online!

CalculatorFeline

Posted 2015-09-28T16:23:13.630

Reputation: 2 658

0

Bash

[ $1 == google ]; return $((${#1}/$?))

iBug

Posted 2015-09-28T16:23:13.630

Reputation: 2 547

0

GameMaker Language, 46 bytes

x=argument0
return string_length(x)/x!=google

Uses the same logic as this Python answer, abusing GMLs type coercion making the function divide by zero if the string equals google

I also haven't and can't test this because I currently don't have GameMaker installed, just made this from memory

FireCubez

Posted 2015-09-28T16:23:13.630

Reputation: 857

0

Keg, 16 bytes

:`google`=[0/|÷!

Try it online!

Attempt ruined by the fact that google isn't in Keg's dictionary. That's why I use DuckDuckGo, which at least has parts of it's name in the dictionary!

Lyxal

Posted 2015-09-28T16:23:13.630

Reputation: 11 711

0

Lua, 35 bytes

load'return #(...=="google"or ...)'

Try it online!

Idea is like one in @QuertyKeyboard's answer, but better optimized: load is used to create function and inverting check for "googleness" allows us to save one byte by replacing and with or.

Again, if full programs are allowed, we can cut down to 29 bytes!

Lua, 29 bytes

print(#(...=="google"or ...))

Try it online!

val says Reinstate Monica

Posted 2015-09-28T16:23:13.630

Reputation: 560

0

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')

codeporn

Posted 2015-09-28T16:23:13.630

Reputation: 261

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()} – manatwork – 2016-03-25T09:24:51.647

0

Ruby, 41 characters

def g(s)puts s!="google"?s.length: a end

CocoaBean

Posted 2015-09-28T16:23:13.630

Reputation: 355

0

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());
}

Liam

Posted 2015-09-28T16:23:13.630

Reputation: 3 125

0

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)

Bob Jarvis - Reinstate Monica

Posted 2015-09-28T16:23:13.630

Reputation: 614

0

Powershell 34 Bytes

param($a)$a.length*($a-ne'google')

Multiply length by 0,1 boolean value of not-equal google.

Gives 0 if google (not case-sensitive), length otherwise.

Jonathan Leech-Pepin

Posted 2015-09-28T16:23:13.630

Reputation: 273

Your answer should be case-sensitive, and should throw an actual error for google. – lirtosiast – 2015-10-08T10:33:41.330

0

, 15 chars / 21 bytes (noncompetitive)

ï≔`google`?$:ïꝈ

Try it here (Firefox only).

Mama Fun Roll

Posted 2015-09-28T16:23:13.630

Reputation: 7 436

why noncompetitive? – cat – 2015-11-21T22:17:26.767

1Language was made after the challenge. – Mama Fun Roll – 2015-11-21T22:19:18.273

0

Game Maker Language, 60 bytes

a=argument0;if a="google"a=1/0show_message(string_length(a))

Timtech

Posted 2015-09-28T16:23:13.630

Reputation: 12 141

2"Your task is to create a function that accepts 1 string..." This does not meet specs, but all you would have to do is replace the first and last a with argument0. – GamrCorps – 2015-11-21T23:59:42.987

1You're right, fixed. – Timtech – 2015-11-23T11:40:29.327

0

ಠ_ಠ, 110 bytes (noncompetitive)

ಠ_ಠ
ಠgoogleಠ
ಠ=ಠ
ಠ"ಠ
ಠ$ಠ
ಠ$ಠ
ಠ11ಠ
ಠ13ಠ
ಠ(ಠ
ಠ?ಠ
ಠ_ಠ
ಠ#ಠ
ಠ^ಠ

Try it here.

Mama Fun Roll

Posted 2015-09-28T16:23:13.630

Reputation: 7 436

0

Factor, 55 53 49 bytes

: g ( s -- l ) dup length swap "google" = not / ;

Throws the string "google". throw happens to be the same length as 0 0 /. Or I could just divide a string by a number... Or I could just divide the length of the string by if it's not google...

Example use:

cat @ mint-kitty : ~/projects/factor/factor(master??!) $ ./factor -run=listener
Factor 0.98 x86.64 (1742, heads/master-0bb3228063, Tue Mar 15 14:18:40 2016)
[Clang (GCC 4.2.1 Compatible Ubuntu Clang 3.6.2 (tags/RELEASE_362/final))] on linux
IN: scratchpad : dont-google ( str -- int ) dup "google" = [ throw ] [ length ] if ; 
IN: scratchpad "bing" dont-google

--- Data stack:
4
IN: scratchpad "google" dont-google
google

Type :help for debugging help.

--- Data stack:
4
IN: scratchpad 

The error in the UI:

enter image description here

cat

Posted 2015-09-28T16:23:13.630

Reputation: 5 297

0

Scratch, 16 bytes

Script
(scoring used)
Stopping the project is the closest thing to an error that I can get.

weatherman115

Posted 2015-09-28T16:23:13.630

Reputation: 645

I think this should be 6 bytes + "google" = 12 bytes... – m654 – 2016-05-24T14:56:51.403

Google=6 bytes, 6 blocks, 2 operators, 2 variables. 6+6+2+2=8+8=16 – weatherman115 – 2016-05-24T15:01:00.797

Shouldn't you use a divide by 0 error (only one I know of)? – Julian Lachniet – 2017-01-11T00:42:43.427

Does not error in Scratch v456. – CalculatorFeline – 2017-05-29T23:21:33.330

0

C++, 77 Bytes

#include <string>
int G(std::string S){1/int(S!="google");return S.length();}

user54200

Posted 2015-09-28T16:23:13.630

Reputation:

0

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.

James Murphy

Posted 2015-09-28T16:23:13.630

Reputation: 255