Given a String as input, your task is to output 42 only if the input String happens to be exactly the following :


It may output any other value, produce an error or not output at all, if the input does not equal the aforementioned String.

Winning Criterion

This is , so the shortest code in bytes wins!

  • \$\begingroup\$ Many of the solutions provided here are wrong because they print 42 when the string is longer than the desired string and the prefix matches with the desired string. \$\endgroup\$ – fR0DDY Mar 10 '11 at 10:30
  • \$\begingroup\$ @froddy: What if the only characters? following the string (is|are) a line break? My usual input mechanism doesn't care whether the input is terminated by a line break or not but yield the same in both cases, for example. \$\endgroup\$ – Joey Mar 10 '11 at 13:22
  • \$\begingroup\$ @fR0DDY : There was no clear definition on how the rest of the input should be handled, so there's no 'wrong' here. \$\endgroup\$ – PatrickvL Mar 10 '11 at 15:46
  • 3
    \$\begingroup\$ @PatrickvL It does mention 'only' if the input is the given string. So abbcccddddeeeee...zzabc does not satisfy that i suppose and i can see some programs giving yes on that input. \$\endgroup\$ – fR0DDY Mar 10 '11 at 15:56
  • 2
    \$\begingroup\$ @fR0DDY : Let me put it another way : There's no specification on how input is delimited, so that's open to interpretation. There's also no mention of character encoding (I guess most of us assume the default of their environment - ANSI, UTF8 and UTF16LE will be the most popular ones). Also no mention how the input is presented - is it entered via the standard input, via a command-line parameter? So you see - having all this freedom gives way to some interpretation that you would mark as 'incorrect', while others would judge it 'compliant'. NOFI, but this is daily practise for some of us. \$\endgroup\$ – PatrickvL Mar 10 '11 at 16:10

77 Answers 77


Golfscript, 20


with new line, 21 chars (by Nabb)


Actually Nabb beat mine, here is original solution for with new line, 22 chars


This is simply generating source string and just comparing it against string from stdin.

  • 3
    \$\begingroup\$ 26,{).[96+]*}%n+=42`* for 21 (inc newline). \$\endgroup\$ – Nabb Mar 11 '11 at 2:09
  • \$\begingroup\$ Heh, it doesn't work without the n+ because the array isn't flat. You'll have to either keep your original 20 chars or add a ~ to flatten the inner terms of the array. \$\endgroup\$ – Nabb Mar 12 '11 at 4:46
  • \$\begingroup\$ @Nabb, heheh, I didn't realize newline made it different. \$\endgroup\$ – YOU Mar 12 '11 at 5:44

Ruby 1.9, 46 42 39 characters

p (?a..?z).map{|a|a*$.+=1}*""==gets&&42

Assumes the input isn't terminated with a newline.

  • \$\begingroup\$ What about the newline from gets? \$\endgroup\$ – steenslag Mar 10 '11 at 12:44
  • 2
    \$\begingroup\$ @steenslag: The specs don't say anything the input being terminated by a newline, so this solution assumes there is none. \$\endgroup\$ – Ventero Mar 10 '11 at 12:48

C program - 78 89

Edit: Do not print 42 when there are extra characters.

Assumes input does not have a trailing newline.


If the prefix does not match, the program exits. If the prefix matches but there is 1-3 or so extra characters, prints 2. Otherwise, produces undefined behavior.

This can be made one character shorter by changing exit(1) to fork(). Oh, and on an unrelated note, remember to save any open documents in case, for whatever reason, your system happens to lock up.

  • 1
    \$\begingroup\$ This will print 42 if the string is longer than the desired string and the prefix matches with the desired string. \$\endgroup\$ – fR0DDY Mar 10 '11 at 8:37

PHP (60)

Assuming the input is provided in the commandline:


Explanation: you can view the string as a triangle structure.

j     i   val
0     0   a
1   1-2   bb
2   3-5   ccc
3   6-9   dddd
4 10-14   eeeee
5 15-20   ffffff

Line j starts at index i = j*(j+1)/2 (that's the triangular number formula). Solving the quadratic equation results in index i being on line j = int((sqrt(8*i+1)-1)/2) and therefore containing character 97 + int((sqrt(8*i+1)-1)/2). The 0-350 index range allows us to simplify that to 96.5 + sqrt(2*(i+1)), but that no longer holds true for larger values.

Edit: Switched to commandline input as suggested in the comments.
Edit: Uses conditional operator to save a character

  • \$\begingroup\$ +1 , that works ;) Umm could you please elaborate as how $s.=chr(96.5+sqrt($i+=2)); works ? \$\endgroup\$ – Clyde Lobo Mar 10 '11 at 12:24
  • \$\begingroup\$ Edited. I hope it makes sense :-) \$\endgroup\$ – sam hocevar Mar 10 '11 at 12:45
  • \$\begingroup\$ for(;$i<702;)$s.=chr(96.5+sqrt($i+=2));echo($s==$argv[1])*42; Only 61 chars, assuming stdin input \$\endgroup\$ – Viper_Sb Mar 10 '11 at 16:11
  • \$\begingroup\$ @Viper_Sb: thanks for the hint; I wasn't sure about the rules so I mimicked Clyde's solution. I'll go with your suggestion. \$\endgroup\$ – sam hocevar Mar 10 '11 at 17:37
  • 1
    \$\begingroup\$ @powtac the language syntax doesn’t require a space here \$\endgroup\$ – sam hocevar Dec 31 '11 at 4:49

Perl, 35 43

map$s.=$_ x++$a,a..z;say 42if<>~~$s

Needs Perl 5.10 or later (run with -E), no newline in input.

I liked my side-effects regex better, but the shorter code has spoken. Here it is as a souvenir. Also intended for Perl 5.10 or later, but only for the advanced/experimental regex features, so only a p command-line option is needed.

  • \$\begingroup\$ Excellent. I tried hard to beat this w/recursive regex but couldn't get below 43c. :-(( \$\endgroup\$ – rubber boots Mar 10 '11 at 11:04
  • \$\begingroup\$ Why is it necessary to say $a++."{$b}" instead of just $a++.$b? \$\endgroup\$ – Timwi Mar 14 '11 at 0:11
  • \$\begingroup\$ @Timwi because I do need those braces to appear in the resulting string. I don't want to match on literal "d4", I want "dddd", expressed as regex "d{4}" \$\endgroup\$ – J B Mar 14 '11 at 6:55
  • \$\begingroup\$ Of course. Thanks for explaining! \$\endgroup\$ – Timwi Mar 18 '11 at 15:07
  • \$\begingroup\$ Came up with a 33 byte solution for this! Try it online! \$\endgroup\$ – Dom Hastings Dec 10 '17 at 19:52

05AB1E, 7 bytes (non-competing)


Try it online!


A       push lowercase alphabet
 ƶ      lift every letter, push it and multiply it by its index
  J     join the list
   Qi   does it equal the input?
     42 push 42 and output implicitly

Just going through some challenges to learn 05AB1E (and golfing in general). This challenge was marked as active yesterday and I found a short solution, so why not share? :)

  • 3
    \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ – Steadybox Nov 10 '17 at 14:57

Haskell program - 71 67 64 57

Assumes no trailing newline, and does not output one either.

f x|x==[c|c<-['a'..'z'],_<-['a'..c]]="42"
main=interact f


$ echo -n 'abbcccddddeeeeeffffffggggggghhhhhhhhiiiiiiiiijjjjjjjjjjkkkkkkkkkkkllllllllllllmmmmmmmmmmmmmnnnnnnnnnnnnnnoooooooooooooooppppppppppppppppqqqqqqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrsssssssssssssssssssttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuvvvvvvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzzzzzzzzz' | { ./42; echo; }
$ echo -n 'something else' | { ./42; echo; }
42: 42.hs:1:0-54: Non-exhaustive patterns in function f

  • 1
    \$\begingroup\$ fwiw this code is also still very readable. \$\endgroup\$ – Dan Burton Mar 11 '11 at 5:13
  • 1
    \$\begingroup\$ Since zipWith stops when it reaches the end of the shorter list, you can replace ['a'..'z'] with ['a'..] and save 3 characters. \$\endgroup\$ – hammar Jun 9 '11 at 19:29
  • \$\begingroup\$ @hammar: Thanks. I saved 1 more char by using >>= (concatMap) in lieu of concat and zipWith. \$\endgroup\$ – Joey Adams Jun 10 '11 at 0:16
  • \$\begingroup\$ @hammar: Saved even more by using do notation instead of >>= and lambda :-) \$\endgroup\$ – Joey Adams Jun 10 '11 at 0:22
  • 2
    \$\begingroup\$ @Joey: Or even better: [c|c<-['a'..'z'],_<-['a'..c]] \$\endgroup\$ – hammar Jun 10 '11 at 0:44

J, 29



f 'oasijfiojasef'

f 23841235

f 'abbccc...'
  • \$\begingroup\$ I like J. And I find it ugly and horrible. And I like it. \$\endgroup\$ – seequ Nov 3 '14 at 16:40

D: 94 Characters

void f(S)(S s){S t;foreach(i;0..26)t~=array(repeat(cast(char)(i+'a'),i+1));s==t&&writeln(42);}

More Legibly:

void f(S)(S s)
    S t;

    foreach(i; 0 .. 26)
        t ~= array(repeat(cast(char)(i + 'a'), i + 1));

    s == t && writeln(42);

Delphi, 164 132

This one builds a string and just compares it against the first command-line argument. It's shorter and less tricky than my other submission :

var s:string;c,i:int8;begin repeat s:=s+Char(c+97);i:=i-1;c:=c+Ord(i<0);if i<0then i:=c;until c=26;Write(42*Ord(s=ParamStr(1)));end.

(Note, that this version assumes that the c and i variables start out initialized at 0, as is the case in my version of Delphi (2010).)

Like my other submission, this one needs less characters if the string-building doesn't take place in a function, like I did before :

Delphi, 181

program a;{$APPTYPE CONSOLE}function s(c,i:byte):string;begin if(i>0)then Exit(Char(c)+s(c,i-1));if(c<122)then Exit(s(c+1,c-95));end;begin if(s(97,1)=ParamStr(1))then Write(42);end.

Note that the output doesn't need a newline, so WriteLn() became Write().


PHP - 45 characters

I'm surprise nobody posted any answer that used hashing. It's a very size effecient way of testing for exact string.

echo md5($argv[1],1)!='¯è a@ÛÚƒ:ïT�p'?:42;

The data is kind of hard to copy/paste since there is a null-byte in the middle of the code. Here's an hex-dump of the code for testing purposes.

65 63 68 6f 20 6d 64 35 28 24 61 72 67 76 5b 31 5d 2c 31 29 21 3d 27 af e8 a0 61 40 db da 7f 11 0f 83 3a ef 54 00 70 27 3f 3a 34 32 3b

  • 2
    \$\begingroup\$ Clever! Though since there are technically other input values yielding this same hash, it doesn't quite satisfy the requirement of outputting 42 only if the input is in the specified format. \$\endgroup\$ – mellamokb Jun 10 '11 at 3:50

Scala 79

 if((for(i <- 1 to 26;j<-1 to i)yield(96+i).toChar).mkString==args(0))print(42)

Pyth, 14


Just constructs the necessary string, then compares with the input and multiplies by 42.

  • \$\begingroup\$ 'compares with the input and multiplies by 42.' would have never thought of that on my own. You just help me shave 1 character off my solution. Thanks. \$\endgroup\$ – AndoDaan Nov 4 '14 at 21:43
  • \$\begingroup\$ Argh, I came too late. Can you explain how it works? The function m cause me trouble… \$\endgroup\$ – Jim May 31 '17 at 16:36
  • 1
    \$\begingroup\$ @Jim We start with the map function, m, which applies a function to each element of its input. The input is G, the alphabet. xGd finds the position of d, the character in the alphabet, in G, the alphabet. h increases that by one, and *d replicates the character as that many times. Outside the m function, s combines the resulting list of strings into a single string, then qz checks whether the result is equal to the input. Booleans are represented as 0 if False and 1 if true, so *42 resultings in a value of 42 if True and 0 if False. \$\endgroup\$ – isaacg May 31 '17 at 22:11

Brachylog (2), 15 bytes, language postdates challenge


Try it online!

And now for an answer which works on a completely different principle to most seen here. This is a function submission (the question doesn't specify what sort of submission is desired, but functions are permitted by default).


This answer works by defining a sort of string: those which a) contain all lowercase letters of the alphabet, b) are in sorted order, and c) for which taking the number of occurrences of each character in the string produces a sequence of consecutive integers starting from 1. (It should be clear that there are many such strings, but the one we want to special-case is the shortest.) Then if the string fulfils those criteria, we add 16 to the number of distinct characters in the string; this will produce 42 if the string is the one the question asks us to special-case, and at least 43 in all other cases. (If the string fails any of the criteria to belong to the category, the function will end in failure, which is kind-of like throwing an exception.)

Here's how to interpret the source code:

⊇Ạ               {the input} contains all lowercase letters
  ∧              and
   ?o?           the input sorts to itself
                 {and; implied when two conditions overlap}
     ?ọ          the {character, number of occurrences} pairs for the input
       tᵐ        when the second element of each is taken
         ~       create an output that could have been produced by
          ⟦₁     outputting the list of integers from 1 to some input inclusive;
            +₁₆  add 16 to that input {and output it}

R, 60 58



Thanks for the suggestion by @giusppe

  • \$\begingroup\$ I think just paste is fine here, and you can use scan(,"") instead of readline(). \$\endgroup\$ – Giuseppe Dec 11 '17 at 17:10

Python (84)

Assumes a trailing newline at the end of the input.

import sys
if''.join(c*chr(c+96)for c in range(27))+'\n'==sys.stdin.read():print 42
  • 1
    \$\begingroup\$ Why not use raw_input instead sys.stdin.read? \$\endgroup\$ – Juan Mar 10 '11 at 11:33
  • 1
    \$\begingroup\$ @Juan: raw_input only reads a single line; I wasn't sure whether "the input" would always be a single line or whether there could be disqualifying input on later lines. \$\endgroup\$ – Hoa Long Tam Mar 10 '11 at 15:42

Python - 62 chars

print("".join(x*chr(x+96) for x in range(27))==raw_input())*42
  • 2
    \$\begingroup\$ Could be shorter in Python 3: print("".join(x*chr(x+96)for x in range(27))==input())*42. \$\endgroup\$ – mbomb007 Mar 3 '15 at 14:46

Perl, 49 46 characters

to be used in a program, not on the command line

$..=chr($+96)x$ for 1..26;$.eq(pop)&&print '42'

join('',map$_ x++$x,'a'..'z')eq pop&&print'42'



Edit: Idea ripped from Ventero


PHP 92 88 87 chars

function _($a){for($i=97;$i<123;$i++)for($j=$i-96;$j;$j--)$b.=chr($i);echo($b==$a)*42;}


Replaced $j<0 with $j and return $b==$a?42:0; with echo $b==$a?42:0;

Replaced echo $b==$a?42:0; with echo($b==$a)*42;

  • 2
    \$\begingroup\$ Could be 80 chars if it weren't for all the freaking dollar signs. \$\endgroup\$ – Joey Adams Mar 10 '11 at 6:41
  • \$\begingroup\$ Also see my entry for a single-loop solution. \$\endgroup\$ – sam hocevar Mar 10 '11 at 12:17

ECLiPSe Prolog - 173

c(_,[],_):-!. c(A,M,N):-length(L,N),checklist('='(A),L),append(F,L,M),P is N-1,B is A-1,c(B,F,P). ?- read_string(end_of_file,351,S),string_list(S,L),c(122,L,26),writeln(42).

JavaScript (91 93 94 98 102 116)

Usage: a('string'), returns 42 if valid according to spec, or 0.

function a(z){for(i=r='';i++<26;)for(j=i;j--;)r+=String.fromCharCode(i+96);return(z==r)*42}


Edit: Removed var and eliminated two spaces in for (.

Edit 2: Changed j>0 to j, and

  1. return (z==r)?42:0; to
  2. return z==r?42:0

Edit 3: Initialize i with i='', change

  1. (z==r)?42:0 to
  2. (z==r)*42

Edit 4: Change

  1. for(;i<27;i++) to
  2. while(i++<26)

Edit 5: Change

  1. i=r='';while(i++<26) to
  2. for(i=r='';i++<26;) and
  3. for(j=i;j;j--) to
  4. for(j=i;j--;)
  • \$\begingroup\$ Well you can reduce another 12 chars if you dont use var to declare variables ;) \$\endgroup\$ – Clyde Lobo Mar 10 '11 at 6:03
  • \$\begingroup\$ @Clyde: Thanks! Also found I could remove space between for (. \$\endgroup\$ – mellamokb Mar 10 '11 at 6:16
  • \$\begingroup\$ Yeah , was about to suggest the same ;) Oh and I coded a solution in PHP using the same logic as yours \$\endgroup\$ – Clyde Lobo Mar 10 '11 at 6:18
  • \$\begingroup\$ You can save another 2 chars by replacing return(z==r)?42:0; with return z==r?42:0 \$\endgroup\$ – Clyde Lobo Mar 10 '11 at 6:22
  • \$\begingroup\$ j>0 could be just j I think. \$\endgroup\$ – YOU Mar 10 '11 at 6:25

JavaScript 1.8, 99 chars

function c(x)(x.replace(/([a-z])\1*/g,function(m)!(a-m.length)*m.charCodeAt(0)-96-a++,a=1)==0)*a+15

I dare you to make sense of it :)


PHP - 59

Assumes at least 1 input is provided over cli

echo md5($argv[1])!='afe8a06140dbda7f110f833aef540070'?:42;

It more or less works, except that md5 is can technically have duplications with the hashing algo.


PowerShell v2+, 47 bytes


Constructs a range 1..26, feeds that through a loop with |%{...}. Each iteration we use the comma operator to construct an array literal of the current [char] multiplied by the current loop number. We then -join that all together to construct the string abbcccdddd... and then use a case-sensitive -ceq comparison against our input $args, which will result in either $TRUE or $FALSE. In PowerShell, Boolean values can be implicitly cast as 1 or 0, respectively, which is what happens here with the 42*. Will print out 42 iff the input is abbccc...zzzzzzzzzzzzzzzzzzzzzzzzzz and will output 0 otherwise.

  • \$\begingroup\$ you could save a byte :) Try it online! \$\endgroup\$ – mazzy Apr 4 at 8:45

K, 26 Bytes



  • \$\begingroup\$ {$[x~.Q.a@&1+!26;42;]} for 22 bytes. \$\endgroup\$ – streetster Dec 11 '17 at 12:20
  • 1
    \$\begingroup\$ 42*(&!27)~-96+"j"$ for 18 bytes (porting my oK answer). \$\endgroup\$ – streetster Jan 15 '18 at 22:33

VBA 91

There weren't any VBA answers but this works:

Function f(t)
    For i = 1 To 26
        o = o & String(i, Chr(i + 96))
    f = -42 * (t = o)
End Function
  • \$\begingroup\$ Is it really impossible to remove any whitespace from this? \$\endgroup\$ – Esolanging Fruit May 31 '17 at 16:51
  • 1
    \$\begingroup\$ Condensed Version, 61 bytes - o="":For i=1To 26:o=o &String(i,Chr(i+96)):Next:?-42*([A1]=o) \$\endgroup\$ – Taylor Scott Sep 9 '17 at 19:20
  • \$\begingroup\$ @Challenger5 No, it's not impossible. Taylor's Scott comment is exactly that. It runs in the Immediate Window and takes the value from cell A1 as input. \$\endgroup\$ – Engineer Toast Nov 10 '17 at 21:21

APL (Dyalog), 18 17 bytes


Try it online!

Four obvious bytes can be saved if we are allowed to use uppercase.

42 42

/⍨ if (lit. replicated by)

 character input

 is identical to

819⌶ the lowercased


/⍨ replicated by

 one through

26 26


Clojure - 61 chars

(fn[a](if(=(mapcat #(repeat%(char(+% 96)))(range 1 27))a)42))

Exploits the following facts:

  • Clojure can interpret any string automatically as a sequence of chars
  • I can use the range of numbers from 1 to 26 to both create the characters and repeat them the correct number or times to generate the "correct" input
  • \$\begingroup\$ would save 6 chars if Clojure allowed nested #()s..... important feature request for Clojure 1.4 I think! \$\endgroup\$ – mikera Mar 10 '11 at 13:58

Javascript 144

Probably can be significantly improved, recursion has always been a head far for me.


function r(a,b,d,c){c++;if(b<d)a+=r(a,b+1,d,c);for(i=0;i<c;i++)a=String.fromCharCode(b)+a;return a}function q(a){if(q==r(a,97,122,0))return 42};

Less Compressed

function r(s, c, x, w){        
    if(c < x)
        s += r(s, c + 1, x, w);
    for(i = 0; i < w; i++)
        s = String.fromCharCode(c) + s;              
    return s;
function q(z){
    if(q==r(z,97, 122, 0))
        return 42;            


Delphi, 127

var b:Char;c,i:Int8;begin repeat if i<0then i:=c;Read(b);if c+97<>Ord(b)then Exit;i:=i-1;c:=c+Ord(i<0)until i=27;Write(42);end.

This one reads the string from the input, compares it as it goes, writes 42 when the input matches up until the last z.

Delphi, 157

var b:pchar;c,i:byte;begin b:=CmdLine+85;c:=97;i:=1;repeat Inc(b);if b^<>Char(c)then Exit;Dec(i);if i>0then Continue;c:=c+1;i:=c-96;until i=27;Write(42);end.

Delphi, 188

program a;{$APPTYPE CONSOLE}var b:pchar;c,i:byte;begin b:=CmdLine+85;c:=97;i:=1;repeat Inc(b);if(b^<>Char(c))then Exit;Dec(i);if(i>0)then Continue;c:=c+1;i:=c-96;until(i=27);Write(42);end.

This version doesn't use a function, which saves quite a few characters when compared to the previous version of this technique :

Delphi, 213

program a;{$APPTYPE CONSOLE}function t(b:pchar;c,i:byte):byte;begin repeat Inc(b);if(b^<>Char(c))then Exit(0);Dec(i);if(i>0)then Continue;c:=c+1;i:=c-96;until(i=27);t:=42;end;begin WriteLn(t(CmdLine+77,97,1));end.

Alas a bit long, mostly because Delphi's long keywords, and the need to initialize console applications before they can write output.

Also note that I incremented CmdLine by 77 characters, as that was the offset I needed to skip over my local executablepath (Delphi has no direct argument pointer). Adjust to match your own setup (could lead to 1 less character when offset < 10).

  • \$\begingroup\$ You can set the application type under ProjectOptions/DelphiCompiler/Linking/GenerateConsoleApplication. Also, you can omit the program a; line. And the brackets around b^<>Char(c), i>0 and i=27 can be removed. \$\endgroup\$ – Wouter van Nifterick Mar 12 '11 at 13:56
  • \$\begingroup\$ @Wouter van Nifterick: Thanks for the suggestions, I'll apply them to my other submissions too. (I didn't even know if i>0then would compile!) \$\endgroup\$ – PatrickvL Mar 12 '11 at 16:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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