# Answer to life, the universe, and everything

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

abbcccddddeeeeeffffffggggggghhhhhhhhiiiiiiiiijjjjjjjjjjkkkkkkkkkkkllllllllllllmmmmmmmmmmmmmnnnnnnnnnnnnnnoooooooooooooooppppppppppppppppqqqqqqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrsssssssssssssssssssttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuvvvvvvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzzzzzzzzz


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. 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. Mar 10 '11 at 15:46
• @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. Mar 10 '11 at 15:56
• @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. Mar 10 '11 at 16:10

## Golfscript, 20

26,{.97+\{.}*}%=42*


with new line, 21 chars (by Nabb)

26,{).[96+]*}%n+=42*


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

26,{.97+\{.}*}%n+=42*


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

• 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

p (?a..?z).map{|a|a*$.+=1}*""==gets&&42  Assumes the input isn't terminated with a newline. • What about the newline from gets? Mar 10 '11 at 12:44 • @steenslag: The specs don't say anything the input being terminated by a newline, so this solution assumes there is none. 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. main(i,j){for(i=1;i<27;i++)for(j=i;j--;getchar()==96+i?0:exit(1));puts("42"+!!gets(&i));}  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. • This will print 42 if the string is longer than the desired string and the prefix matches with the desired string. Mar 10 '11 at 8:37 ## PHP (60) Assuming the input is provided in the commandline: for(;$i<702;)$s.=chr(96.5+sqrt($i+=2));echo$s!=$argv[1]?:42;


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 ? Mar 10 '11 at 12:24
• Edited. I hope it makes sense :-) 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 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. Mar 10 '11 at 17:37 • @powtac the language syntax doesn’t require a space here 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. $a=a;$_=/^(??{$b++;$a++."{$b}"}){26}$/&&42  • Excellent. I tried hard to beat this w/recursive regex but couldn't get below 43c. :-(( Mar 10 '11 at 11:04 • Why is it necessary to say $a++."{$b}" instead of just $a++.$b? 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! Mar 18 '11 at 15:07 • Came up with a 33 byte solution for this! Try it online! Dec 10 '17 at 19:52 # 05AB1E, 7 bytes (non-competing) AƶJQi42  Try it online! ### Explanation 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? :) • Welcome to PPCG! Nov 10 '17 at 14:57 ## Haskell program - 716764 57 Assumes no trailing newline, and does not output one either. f x|x==[c|c<-['a'..'z'],_<-['a'..c]]="42" main=interact f  Usage: $ echo -n 'abbcccddddeeeeeffffffggggggghhhhhhhhiiiiiiiiijjjjjjjjjjkkkkkkkkkkkllllllllllllmmmmmmmmmmmmmnnnnnnnnnnnnnnoooooooooooooooppppppppppppppppqqqqqqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrsssssssssssssssssssttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuvvvvvvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzzzzzzzzz' | { ./42; echo; }
42
$echo -n 'something else' | { ./42; echo; } 42: 42.hs:1:0-54: Non-exhaustive patterns in function f$

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

## J, 29

f=:42#~((>:#a.{~97+])i.26)-:]


example:

f 'oasijfiojasef'

f 23841235

f 'abbccc...'
42

• I like J. And I find it ugly and horrible. And I like it. 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 :

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

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

*42qzsm*dhxGdG


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. 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
• @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. May 31 '17 at 22:11

# Brachylog (2), 15 bytes, language postdates challenge

⊇Ạ∧?o?ọtᵐ~⟦₁+₁₆


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

## Explanation

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:

⊇Ạ∧?o?ọtᵐ~⟦₁+₁₆
⊇Ạ               {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

if(readline()==paste0(rep(letters,1:26),collapse=""))cat(42)


if(scan(,"")==paste(rep(letters,1:26),collapse=""))cat(42)

Thanks for the suggestion by @giusppe

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

## Python (84)

Assumes a trailing newline at the end of the input.

import sys

• Why not use raw_input instead sys.stdin.read?
– Juan
Mar 10 '11 at 11:33
• @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. Mar 10 '11 at 15:42

## Python - 62 chars

print("".join(x*chr(x+96) for x in range(27))==raw_input())*42

• Could be shorter in Python 3: print("".join(x*chr(x+96)for x in range(27))==input())*42. 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'


Regards

rbo

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


EDIT

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;

• Could be 80 chars if it weren't for all the freaking dollar signs. Mar 10 '11 at 6:41
• Also see my entry for a single-loop solution. 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 939498102116)

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}


http://jsfiddle.net/g25M3/6/

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 ;) Mar 10 '11 at 6:03
• @Clyde: Thanks! Also found I could remove space between for (. 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 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 Mar 10 '11 at 6:22
• j>0 could be just j I think.
– 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 42*(-join(1..26|%{,[char]($_+96)*$_})-ceq$args)


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. • you could save a byte :) Try it online! Apr 4 '19 at 8:45 ### K, 26 Bytes {(::;42)x~,/(1+!26)#'.Q.a} {(::;42)x~,/(1+!26)#'.Q.a}"hello" {(::;42)x~,/(1+!26)#'.Q.a}"abbcccddddeeeeeffffffggggggghhhhhhhhiiiiiiiiijjjjjjjjjjkkkkkkkkkkkllllllllllllmmmmmmmmmmmmmnnnnnnnnnnnnnnoooooooooooooooppppppppppppppppqqqqqqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrsssssssssssssssssssttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuvvvvvvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzzzzzzzzz" 42  Thanks • {$[x~.Q.a@&1+!26;42;]} for 22 bytes.
– mkst
Dec 11 '17 at 12:20
• 42*(&!27)~-96+"j"\$ for 18 bytes (porting my oK answer).
– mkst
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))
Next
f = -42 * (t = o)
End Function

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

# APL (Dyalog), 18 17 bytes

42/⍨⍞≡819⌶⎕A/⍨⍳26


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

⎕AAlphabet

/⍨ replicated by

⍳ one through

26 26

# 05AB1E, 7 bytes

AƶJQ42*


Try it online!

Wellp, 05AB1E keeps evolving.

# 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! Mar 10 '11 at 13:58

## Javascript 144

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

Compressed

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