# 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. – 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
• @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
• @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

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


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

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


print args[0]!=(1..26).collect{"${(char)it+96}"*it}.join()?'':42  # Q, 31 30 {$[x~(,/)(1+(!)26)#'.Q.a;42;]}


# Burlesque, 24

@azr@{J**96.-.*}ms==42.*


Pretty standard solution.

@az r@            creates range from 'a to 'z
{                 start mapping the code block to each element
J ** 96 .-    duplicates the current and gets it position in the alphabet (n)
.*            duplicates the element n times
}ms               end mapping, with the added flourish to concatenate the mapped block
==42.*            got this from isaacg above me.


Try it here. Note that Burlesque takes anything that's before the code as input, so mess up the "abb...zzz" string to see it fail.

# C++, 157 154

Compressed (headers included) [154 characters]:

#include<iostream>
#include<string>
int i,j;int main(){std::string h;std::cin>>h;for(;i<26;i++)while(j<=i+i*(i+1)/2)(h[j]=='a'+i)?j++:j;std::cout<<42;}


Compressed (headers and using namespace std assumed like in this answer) [100 characters]:

int i,j;int main(){string h;cin>>h;for(;i<26;i++)while(j<=i+i*(i+1)/2)(h[j]=='a'+i)?j++:j;cout<<42;}


Not compressed (with headers):

#include <iostream>
#include <string>
using namespace std;

int i, j;
int main()
{
string h;
cin >> h;
for(i = 0 ; i < 26 ; i++)
while(j <= i+i*(i+1)/2)
(h[j] == 'a'+i)?j++:j;
cout << 42;
}


Explanation:

• int i,j; int main(): i and j are initialized to 0 with 8 characters instead of 12 (int i=0,j=0;)
• j<=i+i*(i+1)/2: use of the triangular number formula
• (h[j]=='a'+i)?j++:j: endless loop trick when j is not incremented

Edit. Headers and using statements counted

• I think you are supposed to count the headers and using statements. – user10766 Nov 5 '14 at 2:33
• You're right. My solution is now 157 characters long. – Display_name Nov 5 '14 at 10:02

# J, 21 bytes

Program:

   42*(u:96+(]#])i.27)-:


Usage:

   42*(u:96+(]#])i.27)-: 'abbcccddddeeeeeffffffggggggghhhhhhhhiiiiiiiiijjjjjjjjjjkkkkkkkkkkkllllllllllllmmmmmmmmmmmmmnnnnnnnnnnnnnnoooooooooooooooppppppppppppppppqqqqqqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrsssssssssssssssssssttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuvvvvvvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzzzzzzzzz'
42


Explanation:

   42*                    NB. Multiply 42 to
(
u:                 NB. Convert all to characters
96+              NB. Add 96 to all
(]#])         NB. "]" copies the i.27, and 1 4 # 1 2 gives 1 2 2 2 2 for example
i.27     NB. 0 1 2 3 ... 26 (not 27)
)
-:  NB. matches the right hand side (return 1 if matches, 0 otherwise)


# Reng v.3.2, 88 bytes

(Noncompeting, postdates question.)

2#y2#z"a"1Ø         Ø3r1\
:1+>y1-?!v$z1+:#y#zRzeq!^ ^ :y#< i sve(*?v) ?~n>$ 2.>076**


This is one heckuvan answer.

## Initial

2#y2#z"a"1Ø


Stores 2 to y (the temporary counter) and z (the overall counter), and initiates the stack with "a" then goes to the next line.

## Loop

:1+>y1-?!v$z1+:#y#zRzeq!^ ^ :y#<  First, :1+ duplicates the previously made run of characters and increments it to work with the next one. Then... ### Generating N copies of a number  >y1-?!v ^ :y#<  This loops until y == 0. Once y is zero, we exit the loop. Otherwise, we put y - 1 back into y and duplicate the character being worked with it. ### Breaking out of this loop $z1+:#y#zRzeq!^



This drops y from the conditional and increments and duplicates z, which is then put into y and z. Then, if R (26 + 1) is z, we go to the next part. Otherwise, the loop continues again.

## Transition

                    Ø3r1\
^


This goes out of the loop, pushes 1 (our equality counter), reverses the stack, and goes to the third line.

## Final

i sve(*?v)
?~n>$2.>076**  i sve(*?v) loops until (a) there is no input or (b) the equality counter is 0. In the first case, the first v is met, and we drop the -1 bit, skip over the >0 bit (2.), and output 42 (6*7*equality), skipping ~ with a conditional. Otherwise, the second v is encountered, and a zero is pushed before the 76**, so this makes it zero. The conditional activates the ~ (exit program) command because the TOS is falsey, and thus no output is given. ## Javascript, 145 bytes Only uses recursion ((function(i,k,l){return(String.fromCharCode(97+i)==l[k+i])&&((i<25)?arguments.callee(++i,k+i,l):l.length==k+i+1)}).call(this,0,0,line)==true)*42  This approach checks each character along the way instead of creating the valid string to compare against. So, is the 'g' actually in the correct position, then return true. Finally check that the length is what is expected. Any falses on the way cause a '0' to be returned. Thanks for the hint regarding the *42 at the end • Can save two chars by replacing ?42:0 with *42 – mellamokb Mar 12 '11 at 5:43 # Jelly, 13 bytes in Jelly's codepage, language postdates challenge 26RØa,ZŒṙ⁼×42  Try it online! ## Explanation 26RØa,ZŒṙ⁼×42 , Start with a pair of: Øa the lowercase alphabet (['a', 'b', …, 'y', 'z']) 26R and the list [1, 2, 3, 4, …, 25, 26] Z Swap rows and columns (yielding [['a', 1], ['b', 2], …, ['z', 26]]) Œṙ Run-length decode (yielding the string in the original question) ⁼ 1 if equal to {the original input}, 0 otherwise ×42 Multiply by 42  So we end up outputting 42 if the string is the special-cased string, or 0 otherwise. # 05AB1E, 14 13 bytes, non-competing AvyN>×}JIQi42  Try it online! Edit: Saved 1 byte thanks to @Okx. My first official PPCG submission! Explanation: AvyN>×}JIQi42 A # push alphabet to stack v } # foreach in ToS, element = y, index = N y # push letter to stack N> # increment index by 1 × # repeat the letter (index + 1) times, push to stack J # join stack together I # push input to stack Q # check if string == input i42 # if so, push 42 to stack, implicitly print  • Welcome to PPCG! – Wheat Wizard Feb 12 '17 at 4:20 • @WheatWizard :D – Nick Clifford Feb 12 '17 at 4:21 • Save 1 byte by using AvyN>×}JIQi42 (you can save another byte by removing the I, but you must include the I otherwise this will happen with no input: tio.run/nexus/05ab1e#@@9Y5liZbVd5eHqtV2CmidH//1/z8nWTE5MzUgE) – Okx Feb 12 '17 at 23:46 • Unfortunately, this isn't competing as 05AB1E was created after this question was posted. – Okx Feb 12 '17 at 23:48 • @Okx Thank you, and I know, I was just practicing. – Nick Clifford Feb 13 '17 at 2:52 ### Pyth, 10 bytes (non-competing) *42qSs.__G  Explanation: *42qSs.__G _G Reversed alphabet "zyx...a" ._ Prefixes ["z", "zy", ..., "zyx...a"] Ss Concatenated and sorted "abbccc...zzz" q Q Compare with implicit input *42 42 if the input matches, 0 otherwise  • The input being a string, the implicit input would better be z or w instead of Q. Nice shot though! – Jim Jun 2 '17 at 7:36 ## Python, 56 bytes lambda s:s=="".join(c*chr(c+96)for c in range(27))and 42  I know I'm late to the party, but both of the existing Python answers were full programs, which seemed suboptimal. Returns 42 for the specified input, False for everything else. • Multiplying saves a byte over and – squid Sep 10 '19 at 11:36 # 05AB1E, 9 bytes (non-competing) ASā×JQi42  Try it online! ### Explanation ASā×JQi42 Argument: s AS Push alphabet as array ā×J Each character as many times as its index Q Compare with s i42 If true, output 42  # Perl 6, 32 bytes {42 if$_ eq[~] 'a'..'z'Zx 1..*}


# C (gcc), 86 bytes

i,c;main(a){for(i=0;i++<a&&(c=getchar())==a+96;);a>26&&c<0?puts("42"):i>a&&main(a+1);}


Try it online!

# Lua 98

i=io.read()e=0 for k=1,26 do s,e=i:find(string.char(96+k):rep(k),e+1)_=e or os.exit()end print(42)


# Husk, 12 10 bytes

&42=ṘN…"az


-2 bytes thanks @Zgarb!

Try it online!

       "az  -- constant string: "az"
…     -- fill the range 'a'..'z': "abc...xyz"
ṘN      -- replicate each character [1..] times: "abbccc...zzz..z"
=        -- is input equal to that string?
&42         -- if it is then 42 else 0

• ΣzR can be Ṙ. – Zgarb Dec 11 '17 at 7:49

# Excel VBA, 50 Bytes

Anonymous VBE immediate window function that takes input from cell [A1] and outputs 42 iff the input is equal to the expected output, else 0

For i=1To 26:s=s+String(i,i+96):Next:?([A1]=s)*-42


# Japt, 11 bytes

;¶CËpEÄ
*42


Try it

for c in {a..z};{ for ((i=++j;i--;)){ s+=$c;};} [$s = $1 ]&&echo 42  Build the string, compare and print. If the input string has spaces in it, the [ comparison ] will break, but return falsy anyway. Try it online! # Zsh, 975652 51 bytes Builds the string then compares $1. If the input doesn't match the magic string, some integer other than 42 (or an error message) is printed. Try it online!!

for c ({a..z})repeat $[++i];s+=$c
<<<$[${#s#$1}+42]  My original solution: 97bytes (ascii evaluate input) @GammaFunction's solutions: 56bytes 52 bytes 51 bytes (main solution) Example: for c ({a..z})s+=${${(l:++i:)}//?/$c};[ $s =$1 ]&&<<<42

• False positive on abbccc...zzzzz[something else]. – GammaFunction Sep 9 '19 at 8:04
• I found a 56 byte solution. Hint: ${(l:++i:)} – GammaFunction Sep 9 '19 at 8:18 • Unfortunately, I found a more boring answer at 53 bytes.. I'd leave the 56 byte answer up too, the (l) flag is a neat language feature. – GammaFunction Sep 9 '19 at 8:35 • Hey, I found something clever which saved another byte! Takes advantage of outputting something else (in this case some number larger than 42) if it doesn't match. – GammaFunction Sep 9 '19 at 9:19 • Whoops, swap the variables and it should work: ${#s#$1}. Thankfully, $1 is not treated like a glob (this strategy wouldn't work in bash for this reason). – GammaFunction Sep 9 '19 at 9:46

## Groovy, 70

a=[];(1..26).each{a+=[(char)it+96]*it};if(args[0]==a.join(''))print 42

• An anonymous user proposed saving two characters as a=[];(1..26).each{a+=[(char)it+96]*it};print args[0]!=a.join()?'':42 – Peter Taylor Sep 28 '11 at 8:04

## C++

$cat main.cpp | wc -m -l 16 269  Not compressed Recursive ok routine checks string for abbcccdddd.... #include <iostream> bool ok(char *c) { char *s = c; while(*c && *c == *s) c++; return (c - s == *s - 'a' + 1) && ((*c == 0 && *s == 'z') || ok(c)); } int main(int c, char **v) { if(c > 1 && ok(v[1])) std::cout << 42 << std::endl; return 0; }  Second version $ cat main.cpp | wc -m -l
15     239


Without recursion

#include <stdio.h>

bool ok(char *c)
{
char i,j;
for(i = 'a'; i <= 'z'; ++i)
for(j = 'a'; j <= i; ++j)
if(*c++ != i) return 0;
return !*c;
}

int main(int c, char **v)
{
return c > 1 && ok(v[1]) && printf("42"), 0;
}

• Since this is code golf, you should post your score and your golfed code, i.e. with no unnecessary whitespace – FryAmTheEggman Sep 29 '15 at 19:38

# JavaScript (1.8), 103 characters

function f(s,i)i===+i?s.length-i-1||s.charCodeAt()-i-97:s&&s.match(/(.)\1*/g).some(f)+s.length!=351|42


Here's my rather long attempt in JavaScript... returns 42 if the string is the valid string, 43 otherwise.

Here's a prettier, earlier version with whitespace:

function f(s) {
return s && s.match(/(.)\1*/g).some(function(x,i) {
return x.length-i-1 || x.charCodeAt()-i-97
})+s.length==351 && 42
}


and another version, closer to the final version (modulo whitespace removal)

function f(s,i) {
return i===+i
? s.length-i-1 || s.charCodeAt()-i-97
: s&&s.match(/(.)\1*/g).some(f)+s.length!=351 | 42
}


## R, 99

f=function(x){s="";for(i in 1:26)s=c(s,(rep(letters[i],each=i)));s=paste(s,collapse="");if(x==s)42}


Usage:

f("test")
[1] 42


# Javascript, 104

function f(x){var a="";for(b=97;b<123;b++)a+=Array(b-95).join(String.fromCharCode(b));if(x==a)return 42}


Should be pretty obvious, but it creates the string and then tests it against the input.

If I can golf this down any further, please let me know.

# Oracle SQL 11.2, 148 bytes

SELECT 42 FROM(SELECT MAX(TRANSLATE(SYS_CONNECT_BY_PATH(LPAD(' ',LEVEL+1,CHR(64+LEVEL)),';'),'A; ','A'))s FROM DUAL CONNECT BY LEVEL<27)v WHERE:1=s;


# Haskell, 45 51 bytes

f x|x==zip[1..]['a'..'z']>>=uncurry replicate->"42"


zip [1..] ['a'..'z'] produces the list [(1,'a'), (2,'b'), ...].

uncurry replicate has the type (Int, a) -> [a], and uncurry replicate (n, v) produces a list of n copies of v.

>>= applies uncurry replicate to the zipped list, and concatenates the results.

Finally, that string compared to the argument and returns "42" if it is equal, or crashes.

(edited b/c I'm dumb and didn't notice the return requirement)

• Your code does not compile. You need to change -> to = (f is a function, not a lambda) and put the >>= expression into parenthesis (otherwise its parsed as (x==zip[1..]['a'..'c'])>>=(uncurry replicate)). – Laikoni Feb 27 '17 at 8:26

# Pylongolf2, 21 bytes

con1968701440=?42~¿


Explanations:

con1968701440=?42~¿