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!

  • 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. – fR0DDY Mar 10 '11 at 10:30
  • @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. – Joey Mar 10 '11 at 13:22
  • @fR0DDY : There was no clear definition on how the rest of the input should be handled, so there's no 'wrong' here. – PatrickvL Mar 10 '11 at 15:46
  • 3
    @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. – fR0DDY Mar 10 '11 at 15:56
  • 2
    @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. – PatrickvL Mar 10 '11 at 16:10

74 Answers 74

up vote 20 down vote accepted

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
    26,{).[96+]*}%n+=42`* for 21 (inc newline). – Nabb Mar 11 '11 at 2:09
  • 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. – Nabb Mar 12 '11 at 4:46
  • @Nabb, heheh, I didn't realize newline made it different. – 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.

  • What about the newline from gets? – steenslag Mar 10 '11 at 12:44
  • 2
    @steenslag: The specs don't say anything the input being terminated by a newline, so this solution assumes there is none. – 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
    This will print 42 if the string is longer than the desired string and the prefix matches with the desired string. – fR0DDY Mar 10 '11 at 8:37
  • @fR0DDY: Thanks, fixed. – Joey Adams Mar 10 '11 at 20:19

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

  • +1 , that works ;) Umm could you please elaborate as how $s.=chr(96.5+sqrt($i+=2)); works ? – Clyde Lobo Mar 10 '11 at 12:24
  • Edited. I hope it makes sense :-) – sam hocevar Mar 10 '11 at 12:45
  • for(;$i<702;)$s.=chr(96.5+sqrt($i+=2));echo($s==$argv[1])*42; Only 61 chars, assuming stdin input – Viper_Sb Mar 10 '11 at 16:11
  • @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. – sam hocevar Mar 10 '11 at 17:37
  • 1
    @powtac the language syntax doesn’t require a space here – 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.

  • Excellent. I tried hard to beat this w/recursive regex but couldn't get below 43c. :-(( – rubber boots Mar 10 '11 at 11:04
  • Why is it necessary to say $a++."{$b}" instead of just $a++.$b? – Timwi Mar 14 '11 at 0:11
  • @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}" – J B Mar 14 '11 at 6:55
  • Of course. Thanks for explaining! – Timwi Mar 18 '11 at 15:07
  • Came up with a 33 byte solution for this! Try it online! – Dom Hastings Dec 10 '17 at 19:52

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

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
    Welcome to PPCG! – Steadybox Nov 10 '17 at 14:57
  • @Steadybox thank you! – Cinari Nov 10 '17 at 22:02

J, 29



f 'oasijfiojasef'

f 23841235

f 'abbccc...'
  • I like J. And I find it ugly and horrible. And I like it. – 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
    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. – 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.

  • '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. – AndoDaan Nov 4 '14 at 21:43
  • Argh, I came too late. Can you explain how it works? The function m cause me trouble… – Jim May 31 '17 at 16:36
  • 1
    @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. – 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}

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
    Why not use raw_input instead sys.stdin.read? – Juan Mar 10 '11 at 11:33
  • 1
    @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. – 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
  • 1
    Could be shorter in Python 3: print("".join(x*chr(x+96)for x in range(27))==input())*42. – 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
    Could be 80 chars if it weren't for all the freaking dollar signs. – Joey Adams Mar 10 '11 at 6:41
  • Also see my entry for a single-loop solution. – 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--;)
  • Well you can reduce another 12 chars if you dont use var to declare variables ;) – Clyde Lobo Mar 10 '11 at 6:03
  • @Clyde: Thanks! Also found I could remove space between for (. – mellamokb Mar 10 '11 at 6:16
  • Yeah , was about to suggest the same ;) Oh and I coded a solution in PHP using the same logic as yours – Clyde Lobo Mar 10 '11 at 6:18
  • You can save another 2 chars by replacing return(z==r)?42:0; with return z==r?42:0 – Clyde Lobo Mar 10 '11 at 6:22
  • j>0 could be just j I think. – YOU Mar 10 '11 at 6:25

C++ (110 chars)

Assumes use of the std namespace, headers, etc. And make use of everything not specified in the question (whether it can output something else when the string doesn't match, etc.)

int main(int, char **c)
    string s(c[1]), t;
    for(int i=1; i < 27; i++) {
        for(int j=0; j < i; j++) {
            t += i+96;
    cout << 42 + s.compare(t);

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.

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
  • Is it really impossible to remove any whitespace from this? – Esolanging Fruit May 31 '17 at 16:51
  • 1
    Condensed Version, 61 bytes - o="":For i=1To 26:o=o &String(i,Chr(i+96)):Next:?-42*([A1]=o) – Taylor Scott Sep 9 '17 at 19:20
  • @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. – 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

R, 60 58



Thanks for the suggestion by @giusppe

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

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
  • would save 6 chars if Clojure allowed nested #()s..... important feature request for Clojure 1.4 I think! – 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).

  • 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. – Wouter van Nifterick Mar 12 '11 at 13:56
  • @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!) – PatrickvL Mar 12 '11 at 16:23

Groovy - 64

print args[0]!=(1..26).collect{"${(char)it+96}"*it}.join()?'':42

Your Answer


By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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