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.
-
145\$\begingroup\$ I googled google, and Google found Google on Google. Myth Busted. \$\endgroup\$Geobits– Geobits2015年09月28日 16:32:27 +00:00Commented Sep 28, 2015 at 16:32
-
110\$\begingroup\$ @Geobits That is simply a test to see if I will google Google, which I will not. :D \$\endgroup\$rybo111– rybo1112015年09月28日 16:33:22 +00:00Commented Sep 28, 2015 at 16:33
-
8\$\begingroup\$ Does the function need to be case sensitive? Should it throw given 'gOOgle'? \$\endgroup\$AXMIM– AXMIM2015年09月30日 22:07:02 +00:00Commented Sep 30, 2015 at 22:07
-
3\$\begingroup\$ When I type google into google (the search bar on chrome), a message came up asking if I wanted to go to google. (Now that it is a tld, this makes sense i.e. com.google works). I clicked it and got a dns lookup error. Internet:broken! \$\endgroup\$Craig– Craig2015年10月01日 04:18:44 +00:00Commented Oct 1, 2015 at 4:18
-
6\$\begingroup\$ I'm voting to reopen this. I have seen no questions about what constitutes an error for this challenge and it already has 154 answers so I don't think it's fair to change the spec. This may not be an example of a good question but it's clear enough. If an answer really comes down to whether or not a certain output is an error it probably just won't get as many upvotes, anyway. \$\endgroup\$Poke– Poke2018年08月01日 19:52:54 +00:00Commented Aug 1, 2018 at 19:52
171 Answers 171
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.
-
3\$\begingroup\$ +1. You need to set
gto yourlambda, or call it anonymously with an input, though. \$\endgroup\$Zach Gates– Zach Gates2015年09月28日 16:44:58 +00:00Commented Sep 28, 2015 at 16:44 -
7\$\begingroup\$ Just for fun, I tried this technique with JavaScript ES6. It ended up at 25, but returns
Infinityfor "google" instead of throwing an error... \$\endgroup\$ETHproductions– ETHproductions2015年09月28日 16:55:12 +00:00Commented Sep 28, 2015 at 16:55 -
23\$\begingroup\$ @ZachGates The consensus on meta is that anonymous functions are allowed unless specifically disallowed. Since the question does seem to imply something like this (but doesn't explicitly disallow it, yet), you should ask the OP about it. \$\endgroup\$FryAmTheEggman– FryAmTheEggman2015年09月28日 16:58:50 +00:00Commented Sep 28, 2015 at 16:58
-
3\$\begingroup\$ @Kevin you would need a
returnif you useddef\$\endgroup\$FryAmTheEggman– FryAmTheEggman2015年09月28日 20:10:15 +00:00Commented Sep 28, 2015 at 20:10 -
5\$\begingroup\$ Amusingly, this translated to Pyth does better than my prior best Pyth solution. It is
L/lbnb"google, 13 bytes. \$\endgroup\$izzyg– izzyg2015年11月26日 06:26:00 +00:00Commented Nov 26, 2015 at 6:26
Excel, 23 characters
Paste this into a cell other than A1 and type your search query into A1.
=LEN(A1)/(A1<>"google")
For example:
-
11\$\begingroup\$ What's the general consensus on using Excel? \$\endgroup\$Beta Decay– Beta Decay2015年09月30日 17:11:50 +00:00Commented Sep 30, 2015 at 17:11
-
56\$\begingroup\$ @BetaDecay. Creative, uncommon, seems to work. Won't be applicable to all CG puzzles, but it is here! \$\endgroup\$kdbanman– kdbanman2015年09月30日 18:03:45 +00:00Commented Sep 30, 2015 at 18:03
-
131\$\begingroup\$ Managers love it! \$\endgroup\$lkraider– lkraider2015年09月30日 18:07:28 +00:00Commented Sep 30, 2015 at 18:07
-
25\$\begingroup\$ So Efficient, CG Users Will Hate You For It. But Wait. B3 Will Change Your Life Forever! \$\endgroup\$Sumurai8– Sumurai82015年10月01日 07:44:23 +00:00Commented Oct 1, 2015 at 7:44
-
11\$\begingroup\$ What's the specific concensus on using Excel? \$\endgroup\$GreenAsJade– GreenAsJade2015年10月03日 23:29:34 +00:00Commented Oct 3, 2015 at 23:29
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);
-
2\$\begingroup\$ Yeah I thought that was a pretty clever way to save some characters to throw an exception. At 4 characters, it might be the smallest way to throw an exception in C#, not sure. \$\endgroup\$DLeh– DLeh2015年10月01日 20:05:59 +00:00Commented Oct 1, 2015 at 20:05
-
6\$\begingroup\$ This is clever! However, recent versions of C# have support for tail recursion so this function will never throw
StackOverflowException. In fact it will never return (behaves aswhile(true){}). \$\endgroup\$NightElfik– NightElfik2015年10月06日 04:15:48 +00:00Commented Oct 6, 2015 at 4:15 -
2\$\begingroup\$ @DLeh Tail recursion calls are little bit tricky. You have to run on x64 JIT and without debugger (debugger attached will cause tail recursion to not work for obvious reasons). Here is my program as a proof: imgur.com/ErNl8LJ and little more reading about tail recursion: blogs.msdn.com/b/davbr/archive/2007/06/20/… ;) \$\endgroup\$NightElfik– NightElfik2015年10月10日 18:52:12 +00:00Commented Oct 10, 2015 at 18:52
-
13\$\begingroup\$ Haha: g(string)... I'll see myself out... \$\endgroup\$gregsdennis– gregsdennis2015年11月17日 01:45:17 +00:00Commented Nov 17, 2015 at 1:45
-
2\$\begingroup\$ @DLeh oh wait no I can match your 43 bytes but not beat it. :) int g(string s)=>s!="google"?s.Length:s[9]; \$\endgroup\$lee– lee2018年03月09日 03:27:14 +00:00Commented Mar 9, 2018 at 3:27
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.
How it works
L Define y(b):
lb Compute len(b).
nb"google Compute (b != "google").
/ Set _ = len(b) / (b != "google").
Return _. (implicit)
-
\$\begingroup\$ Yeah I'm actually unsure about this, I don't think it's happened before with a string. Normally you could close it with
;but obviously you can't here... \$\endgroup\$FryAmTheEggman– FryAmTheEggman2015年09月28日 17:29:49 +00:00Commented Sep 28, 2015 at 17:29 -
\$\begingroup\$ You don't need the end quote. \$\endgroup\$Maltysen– Maltysen2015年09月28日 20:25:02 +00:00Commented Sep 28, 2015 at 20:25
-
51\$\begingroup\$ "Defines a named function
y." But there's noyin your code!? \$\endgroup\$A.L– A.L2015年09月29日 13:03:11 +00:00Commented Sep 29, 2015 at 13:03 -
48\$\begingroup\$ @A.L That's correct. The built-in
Lredefines the functiony. \$\endgroup\$Dennis– Dennis2015年09月29日 14:49:43 +00:00Commented Sep 29, 2015 at 14:49 -
95\$\begingroup\$ I'm not sure, but I think I hate Pyth. \$\endgroup\$Mr Lister– Mr Lister2015年09月30日 15:36:49 +00:00Commented Sep 30, 2015 at 15:36
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:
-
3\$\begingroup\$ You could save a byte by using
strcmpinstead ofisequal. \$\endgroup\$Tom Carpenter– Tom Carpenter2015年09月29日 05:47:28 +00:00Commented Sep 29, 2015 at 5:47 -
\$\begingroup\$ @TomCarpenter - Funny. I actually told myself to use
strcmpbut ended up usingisequalfor some reason.... thanks! \$\endgroup\$rayryeng– rayryeng2015年09月29日 05:53:21 +00:00Commented Sep 29, 2015 at 5:53 -
2\$\begingroup\$
nnzis two bytes shorter thannumel. You had my vote a few years ago :-) \$\endgroup\$Stewie Griffin– Stewie Griffin2017年10月17日 20:13:36 +00:00Commented Oct 17, 2017 at 20:13
JavaScript ES6, (削除) 34 (削除ここまで) (削除) 27 (削除ここまで) 25 characters
f=>f=='google'?Δ:f.length
Throws a ReferenceError on Δ for google.
alert((f=>f=='google'?Δ:f.length)('test'))
-
11\$\begingroup\$ You could use a ternary operator to save two bytes. \$\endgroup\$null– null2015年09月29日 13:14:26 +00:00Commented Sep 29, 2015 at 13:14
-
2\$\begingroup\$ Yay, that's exactly what I just got. If you want to be fancy, use a symbol people never use instead of g to be sure it won't exist as a global variable. Δ makes for a good variable name :) \$\endgroup\$Domino– Domino2015年10月01日 17:07:36 +00:00Commented Oct 1, 2015 at 17:07
-
1\$\begingroup\$ You could use
#, it errors in JS afaik \$\endgroup\$clapp– clapp2015年10月06日 01:55:51 +00:00Commented Oct 6, 2015 at 1:55 -
7\$\begingroup\$ Δ Google Illuminati confirmed \$\endgroup\$user45178– user451782015年10月07日 01:59:56 +00:00Commented Oct 7, 2015 at 1:59
-
2\$\begingroup\$ I'm just going to leave this here github.com/Rabrennie/anything.js \$\endgroup\$sagiksp– sagiksp2017年03月09日 10:04:21 +00:00Commented Mar 9, 2017 at 10:04
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
-
\$\begingroup\$ 20 bytes:
length(Ans)/(Ans≠"google. You also have the case wrong; if uppercase is allowed it's 14 bytes. By the way, it's valid to pass arguments through Ans. \$\endgroup\$lirtosiast– lirtosiast2015年09月28日 19:37:30 +00:00Commented Sep 28, 2015 at 19:37 -
\$\begingroup\$
AGOOGLEshould give 7, correct? And you shouldn't be counting the program header in your code size, so subtract 10 bytes. \$\endgroup\$lirtosiast– lirtosiast2015年09月28日 20:48:41 +00:00Commented Sep 28, 2015 at 20:48 -
\$\begingroup\$ ERROR: I was thinking substrings. Kindly forgive me. \$\endgroup\$Conor O'Brien– Conor O'Brien2015年09月28日 20:49:37 +00:00Commented Sep 28, 2015 at 20:49
-
1\$\begingroup\$ @ThomasKwa I didn't see your comment with the code. It just so happens that we both stumbled upon the same solution. However, if you believe you deserve the credit, the credit shall be yours. ^_^ (EDIT If you would read the code, it isn't the exact same thing.) \$\endgroup\$Conor O'Brien– Conor O'Brien2015年09月28日 22:13:26 +00:00Commented Sep 28, 2015 at 22:13
-
\$\begingroup\$ @lirtosiast
length(is two bytes, that would make your numbers 21 and 15 bytes. \$\endgroup\$Timtech– Timtech2016年03月29日 19:28:48 +00:00Commented Mar 29, 2016 at 19:28
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.
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).
-
12\$\begingroup\$ I think you don't need to count the parens, as it can be assigned to a variable without them. \$\endgroup\$jimmy23013– jimmy230132015年09月29日 06:06:14 +00:00Commented Sep 29, 2015 at 6:06
-
2\$\begingroup\$ Kind-of fails on single-char arguments. Fix by replacing
⍴with≢. Also, you can make it cooler-looking by swapping the operands of∘. Oh, don't forget to remove the parens. All-in-all:≢÷≢∘'google'\$\endgroup\$Adám– Adám2017年01月10日 23:08:20 +00:00Commented Jan 10, 2017 at 23:08
Haskell, 24 bytes
g s|s/="google"=length s
Output:
Main> g "google"
Program error: pattern match failure: g "google"
Main> g "bing"
4
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)
-
2\$\begingroup\$ Those things are not evil in most languages. And this is code golf, some of the most unreadable code on the planet exists here :). Cool handle btw. \$\endgroup\$BAR– BAR2015年10月02日 20:22:49 +00:00Commented Oct 2, 2015 at 20:22
-
9\$\begingroup\$ I'm only missing some
evalhere to make it really EVIL :-) \$\endgroup\$Luis Mendo– Luis Mendo2015年10月05日 00:11:57 +00:00Commented Oct 5, 2015 at 0:11
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.
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.
-
\$\begingroup\$ Interestingly enough, a full program is shorter (15 bytes):
q_,\"google"=!/. Developed it before seeing this post. Note that this takes the whole input (which you seem to take anyways as a function argument). Unfortunately, you can't use it, since this asks for a function :( \$\endgroup\$Erik the Outgolfer– Erik the Outgolfer2016年11月01日 21:53:05 +00:00Commented Nov 1, 2016 at 21:53
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
}
Saved two bytes thanks to Dennis!
-
\$\begingroup\$
⍟is known informally as "splat". A very appropriate name for this usage. \$\endgroup\$Adám– Adám2017年01月10日 23:09:12 +00:00Commented Jan 10, 2017 at 23:09
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'))
-
2\$\begingroup\$ Wow, thanks for telling me there's a shorthand for lamda functions in javascript! \$\endgroup\$Tomáš Zato– Tomáš Zato2015年10月03日 17:28:27 +00:00Commented Oct 3, 2015 at 17:28
-
3\$\begingroup\$ @TomášZato Caveat: they're brand new in ES2015, so support still varies. \$\endgroup\$Anko– Anko2015年10月04日 22:31:57 +00:00Commented Oct 4, 2015 at 22:31
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
-
2\$\begingroup\$ You could make it an anonymous function:
sub{...}. (Then you call it likesub{...}->("google").) \$\endgroup\$manatwork– manatwork2015年09月29日 08:30:50 +00:00Commented Sep 29, 2015 at 8:30 -
\$\begingroup\$ Save 1 byte by using
$_!=googleinstead of!/^google$/\$\endgroup\$Gabriel Benamy– Gabriel Benamy2016年11月01日 03:05:04 +00:00Commented Nov 1, 2016 at 3:05 -
\$\begingroup\$ @GabrielBenamy I'm afraid
!=won't work to compare string... \$\endgroup\$Dada– Dada2017年02月16日 16:24:06 +00:00Commented Feb 16, 2017 at 16:24
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.
-
11\$\begingroup\$ Here is a slightly shorter one:
g=function(x)nchar(x)[[x!="google"]]\$\endgroup\$flodel– flodel2015年09月29日 01:38:15 +00:00Commented Sep 29, 2015 at 1:38
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()
-
1\$\begingroup\$ You can also use Java 8's lambda declaration:
s->(s.equals("google")?null:s).length();\$\endgroup\$h.j.k.– h.j.k.2015年09月29日 03:48:35 +00:00Commented Sep 29, 2015 at 3:48 -
3\$\begingroup\$ "Worth to note that == compares reference and won't work for String Objects." Actually, all strings are objects, so comparing strings with
==in Java will generally not work (unless you're relying on string interning, which is, well, bad). Perhaps you got confused with JavaScript? \$\endgroup\$gengkev– gengkev2015年10月06日 00:52:06 +00:00Commented Oct 6, 2015 at 0:52 -
1\$\begingroup\$ @gengkev If they are both litterals, it will work since it is the same object that's referenced to on the String pool. The spec gives a litteral and here it is a litteral so it will work. \$\endgroup\$Yassin Hajaj– Yassin Hajaj2015年11月21日 23:16:41 +00:00Commented Nov 21, 2015 at 23:16
-
3\$\begingroup\$ @YassinHajaj I agree that the spec gives it as a literal, but that's just an example. The function should probably perform the same if given input from stdin as well, or if the function is called from another class that's compiled separately. In any case, relying on compiler optimizations (string interning) is a poor idea, which is what I originally said. \$\endgroup\$gengkev– gengkev2015年11月21日 23:28:29 +00:00Commented Nov 21, 2015 at 23:28
Haskell - 30 characters
g"google"=error"!";g s=length s
>g "google"
*Exception: !
>g "str"
3
-
6\$\begingroup\$ Why the exclamation mark for error? Wouldn't an empty string do too? \$\endgroup\$Kritzefitz– Kritzefitz2015年09月28日 18:36:07 +00:00Commented Sep 28, 2015 at 18:36
-
1\$\begingroup\$ I wanted to suggest to change it to
x=x;g"google"=x;g s=length s, but for some reason, <<loop>> exceptions aren't thrown in ghci. \$\endgroup\$Kritzefitz– Kritzefitz2015年09月28日 18:44:06 +00:00Commented Sep 28, 2015 at 18:44 -
18\$\begingroup\$
g s|s/="google"=length savoids the need forerror\$\endgroup\$chs– chs2015年09月28日 23:30:17 +00:00Commented Sep 28, 2015 at 23:30
Python 3, 35 bytes
lambda n:len(n)if n!='google'else d
-
1\$\begingroup\$ @FryAmTheEggman actually 16 bits shorter. XD \$\endgroup\$DiegoDD– DiegoDD2015年09月28日 23:26:47 +00:00Commented Sep 28, 2015 at 23:26
-
1\$\begingroup\$ @FryAmTheEggman: Good trick but id does not work with empty string:
(lambda n:len(n)*(n!='google')or d)('')\$\endgroup\$pabouk - Ukraine stay strong– pabouk - Ukraine stay strong2015年09月29日 09:17:20 +00:00Commented Sep 29, 2015 at 9:17 -
\$\begingroup\$ @pabouk Quite right, thanks for pointing that out. \$\endgroup\$FryAmTheEggman– FryAmTheEggman2015年09月29日 12:39:49 +00:00Commented Sep 29, 2015 at 12:39
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");
-
1\$\begingroup\$ You can call
size()to save 2 bytes. In C++14, you could also use generic lambdas and replacestd::stringbyauto. You'd need to pass an actualstd::stringto it instead of aconst char*. \$\endgroup\$anon– anon2015年09月28日 23:35:08 +00:00Commented Sep 28, 2015 at 23:35 -
\$\begingroup\$ @isanae I didn't know
std::stringhassize()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"isconst char*and notstd::string. \$\endgroup\$Zereges– Zereges2015年09月29日 06:38:57 +00:00Commented Sep 29, 2015 at 6:38 -
1\$\begingroup\$ @Zereges
std::stringhassize()andlength()because it's both a container and a string. As forauto, you'd call the lambda with(std::string("google"))instead of("google"). The question only says "accepts 1 string" without specifying what a "string" is. \$\endgroup\$anon– anon2015年09月29日 06:42:40 +00:00Commented Sep 29, 2015 at 6:42 -
\$\begingroup\$ @isanae C++14 also has
"google"sto construct anstd::string:) \$\endgroup\$Quentin– Quentin2015年09月29日 17:47:59 +00:00Commented Sep 29, 2015 at 17:47 -
\$\begingroup\$ @Zereges you can simply
throw;to triggerstd::terminate()(because there's no current exception here). \$\endgroup\$Quentin– Quentin2015年09月29日 17:48:59 +00:00Commented Sep 29, 2015 at 17:48
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");}
-
\$\begingroup\$ Wow, that is some interesting logic there. If I understand the golfy part right, you are somehow shifting the first six chars to fit into a single, giant number (almost like a hash), which, because of the stack being little-endian, ends up being "google", but backwards (
0x656c676f6f67=elgoog). I think this answer needs an explanation for those of us who appreciate this kind of crazy low-level stuff. \$\endgroup\$Braden Best– Braden Best2015年09月29日 21:46:31 +00:00Commented Sep 29, 2015 at 21:46 -
\$\begingroup\$ You basically have it. It simply casts the memory storing the string into a 64 bit number. Endianness makes it 'backward' on x86 architectures. The text only occupies 7 bytes, so the mask just hides whatever may be next in memory. Its a fun trick, but I think '!!strcmp(s,"google")' is actually shorter. \$\endgroup\$AShelly– AShelly2015年09月30日 00:25:12 +00:00Commented Sep 30, 2015 at 0:25
-
1\$\begingroup\$ Anyways, +1. Definitely. Also, I think you can shorten it by removing the
int, that's 4 characters. \$\endgroup\$Braden Best– Braden Best2015年09月30日 02:37:29 +00:00Commented Sep 30, 2015 at 2:37 -
\$\begingroup\$ After some typing, I figured it out! If
char *, with units of8-bits, is casted tolong *, with units of64-bits, without being properly reallocated, the data in those 8 bytes of heap space becomes corrupted, and treated as a single number (8*8 = 64). That's why you get the first 6 chars, + NUL + garbage. That is very clever. Dangerous, too. Wonder why it doesn't segfault. That 8th garbage byte is out of bounds, no? \$\endgroup\$Braden Best– Braden Best2015年09月30日 03:12:55 +00:00Commented Sep 30, 2015 at 3:12 -
\$\begingroup\$ I looked at your analysis. You are correct, the shift should have been 56, not 54. Also, I wouldn't use the word corrupted. The memory is the same, the bits are just interpreted differently. Technically, accessing the garbage byte is undefined behavior, and could actually segfault. Practically, that byte almost certainly resides in the same legal memory block as the rest of the string, and generally these blocks (heap, stack, constants) are allocated in word sized units at a minimum. So the memory belongs to the program, it just contains something other than the string. \$\endgroup\$AShelly– AShelly2015年09月30日 18:07:14 +00:00Commented Sep 30, 2015 at 18:07
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!
-
\$\begingroup\$ Neat, I couldn't get this to work ( I didn't came up with leaving
^outside the matchgroup). \$\endgroup\$Borsunho– Borsunho2015年09月28日 18:00:34 +00:00Commented Sep 28, 2015 at 18:00 -
\$\begingroup\$ @Borsunho I have to admit I just "brute forced" the regex untill I got the result that I wanted :) I think the
.*at the end is what makes it work. \$\endgroup\$daniero– daniero2015年09月28日 18:07:31 +00:00Commented Sep 28, 2015 at 18:07 -
\$\begingroup\$ Breaks if the input string has multiple lines and contains google on its own line. I think
/\A(?!google\Z).*/mfixes it (at the cost of three bytes, though).^and$match the beginning and end of lines, while\Aand\Zmatch the beginning and end of the string as a whole. \$\endgroup\$histocrat– histocrat2015年09月28日 18:30:19 +00:00Commented Sep 28, 2015 at 18:30 -
\$\begingroup\$ @histocrat but I don't think you can google strings with multiple lines ;) \$\endgroup\$daniero– daniero2015年09月28日 19:01:22 +00:00Commented Sep 28, 2015 at 19:01
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>.
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"))
-
\$\begingroup\$ Technically, this doesn't meet the OP's specs. This function alerts the length but returns
undefined. \$\endgroup\$Bungle– Bungle2015年09月30日 05:00:12 +00:00Commented Sep 30, 2015 at 5:00 -
\$\begingroup\$ @Bungle How's it now? \$\endgroup\$Beta Decay– Beta Decay2015年09月30日 05:57:56 +00:00Commented Sep 30, 2015 at 5:57
-
1\$\begingroup\$ @Bungle I see. I forgot that a return was needed \$\endgroup\$Beta Decay– Beta Decay2015年09月30日 16:58:43 +00:00Commented Sep 30, 2015 at 16:58
-
1\$\begingroup\$ Using ES6's arrow functions and ternary operator (instead of if), you can squeeze that a bit more :) \$\endgroup\$Neithan Max– Neithan Max2015年10月01日 21:09:54 +00:00Commented Oct 1, 2015 at 21:09
-
1\$\begingroup\$ @BetaDecay Originality first; I respect that. \$\endgroup\$Neithan Max– Neithan Max2015年10月02日 01:08:58 +00:00Commented Oct 2, 2015 at 1:08
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'.
-
2\$\begingroup\$ Why those parenthesis?
x=='google'?t: x.size\$\endgroup\$manatwork– manatwork2015年09月28日 18:48:31 +00:00Commented Sep 28, 2015 at 18:48
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 **'.
-
\$\begingroup\$ Also, this function uses no library functions. I assume using
strlenandstrcmpis cheating and/or not worth the#include <string.h>. \$\endgroup\$Braden Best– Braden Best2015年09月29日 21:39:52 +00:00Commented Sep 29, 2015 at 21:39 -
\$\begingroup\$ I think you need to give correct output for every string other than
google. \$\endgroup\$lirtosiast– lirtosiast2015年09月29日 21:50:25 +00:00Commented Sep 29, 2015 at 21:50 -
\$\begingroup\$ @ThomasKwa Ah well, I tried. \$\endgroup\$Braden Best– Braden Best2015年09月29日 22:02:22 +00:00Commented Sep 29, 2015 at 22:02
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.
Japt, 14 bytes
U\`goog¤`?Þ:Ul
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
Zsh, 18 bytes
<<<$#1>1ドル
<^google
Explanation:
<<<$#1:1ドル: the input#: length<<<: and print it
>1ドル: redirect that output to a file called the input^google: try and find a file with any name other thangoogle<: and print its contents
So if the file created was called google, then no file will be found and an error message will appear. But if the file was called anything else, then its contents is the length of the input, and it will be outputted.
><>, 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.