50
\$\begingroup\$

Task

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!

\$\endgroup\$
10
  • 1
    \$\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, 2011 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, 2011 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, 2011 at 15:46
  • 4
    \$\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, 2011 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, 2011 at 16:10

80 Answers 80

1
\$\begingroup\$

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

\$\endgroup\$
2
  • \$\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\$ Mar 12, 2011 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, 2011 at 16:23
1
\$\begingroup\$

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);
}
\$\endgroup\$
1
\$\begingroup\$

Groovy - 64

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

Q, 31 30

{$[x~(,/)(1+(!)26)#'.Q.a;42;]}
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
2
  • \$\begingroup\$ I think you are supposed to count the headers and using statements. \$\endgroup\$
    – user10766
    Nov 5, 2014 at 2:33
  • \$\begingroup\$ You're right. My solution is now 157 characters long. \$\endgroup\$ Nov 5, 2014 at 10:02
1
\$\begingroup\$

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)
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
1
  • \$\begingroup\$ Can save two chars by replacing ?42:0 with *42 \$\endgroup\$
    – mellamokb
    Mar 12, 2011 at 5:43
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Multiplying saves a byte over and \$\endgroup\$
    – squid
    Sep 10, 2019 at 11:36
1
\$\begingroup\$

Perl 6, 32 bytes

{42 if $_ eq[~] 'a'..'z'Zx 1..*}
\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

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)
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
  • 1
    \$\begingroup\$ ΣzR can be . \$\endgroup\$
    – Zgarb
    Dec 11, 2017 at 7:49
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

Sinclair ZX81/Timex TS1000/1500 BASIC, ~138 tokenized BASIC bytes

 1 LET A$="A"
 2 LET C=NOT PI
 3 FOR I=SGN PI TO VAL "25"
 4 LET A$=A$+CHR$ (CODE "A"+I)
 5 LET C=C+SGN PI
 6 IF C<=I THEN GOTO VAL "4"
 7 LET C=NOT PI
 8 NEXT I
 9 INPUT B$
10 IF A$=B$ THEN PRINT "42"

This is the most byte efficient solution I could think of for the technology in question (whilst retaining readability, of course), however, building the string A$ does take a while so be patient (or set an emulator to a decent speed above 3.5Mhz).

\$\endgroup\$
1
\$\begingroup\$

Japt, 11 bytes

;¶CËpEÄ
*42

Try it

\$\endgroup\$
1
\$\begingroup\$

Bash, 68 bytes

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!

\$\endgroup\$
1
\$\begingroup\$

Zsh, 97 56 52 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

\$\endgroup\$
8
  • 1
    \$\begingroup\$ False positive on abbccc...zzzzz[something else]. \$\endgroup\$ Sep 9, 2019 at 8:04
  • 1
    \$\begingroup\$ I found a 56 byte solution. Hint: ${(l:++i:)} \$\endgroup\$ Sep 9, 2019 at 8:18
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Sep 9, 2019 at 8:35
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Sep 9, 2019 at 9:19
  • 1
    \$\begingroup\$ 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). \$\endgroup\$ Sep 9, 2019 at 9:46
1
\$\begingroup\$

Vyxal, 11 bytes

kaf₄ɾ*∑=42*

Try it Online!

kaf         # lowercase alphabet, flattened into char list
   ₄ɾ*      # Repeat by 1..26
      ∑=    # Concatenate all, 1 if input is equal to string, 0 if not
        42* # Multiply by 42
\$\endgroup\$
1
\$\begingroup\$

Pyth, 10 bytes

*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
\$\endgroup\$
1
  • \$\begingroup\$ The input being a string, the implicit input would better be z or w instead of Q. Nice shot though! \$\endgroup\$
    – Jim
    Jun 2, 2017 at 7:36
1
\$\begingroup\$

05AB1E, 9 bytes

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
\$\endgroup\$
1
\$\begingroup\$

05AB1E, 14 13 bytes

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
\$\endgroup\$
5
  • \$\begingroup\$ Welcome to PPCG! \$\endgroup\$
    – Wheat Wizard
    Feb 12, 2017 at 4:20
  • \$\begingroup\$ @WheatWizard :D \$\endgroup\$ Feb 12, 2017 at 4:21
  • \$\begingroup\$ 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) \$\endgroup\$
    – Okx
    Feb 12, 2017 at 23:46
  • \$\begingroup\$ Unfortunately, this isn't competing as 05AB1E was created after this question was posted. \$\endgroup\$
    – Okx
    Feb 12, 2017 at 23:48
  • \$\begingroup\$ @Okx Thank you, and I know, I was just practicing. \$\endgroup\$ Feb 13, 2017 at 2:52
0
\$\begingroup\$

Groovy, 70

a=[];(1..26).each{a+=[(char)it+96]*it};if(args[0]==a.join(''))print 42
\$\endgroup\$
1
  • \$\begingroup\$ An anonymous user proposed saving two characters as a=[];(1..26).each{a+=[(char)it+96]*it};print args[0]!=a.join()?'':42 \$\endgroup\$ Sep 28, 2011 at 8:04
0
\$\begingroup\$

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;
}
\$\endgroup\$
1
  • \$\begingroup\$ Since this is code golf, you should post your score and your golfed code, i.e. with no unnecessary whitespace \$\endgroup\$ Sep 29, 2015 at 19:38
0
\$\begingroup\$

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
 }
\$\endgroup\$
0
\$\begingroup\$

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")
f("abbcccddddeeeeeffffffggggggghhhhhhhhiiiiiiiiijjjjjjjjjjkkkkkkkkkkkllllllllllllmmmmmmmmmmmmmnnnnnnnnnnnnnnoooooooooooooooppppppppppppppppqqqqqqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrsssssssssssssssssssttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuvvvvvvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzzzzzzzzz")
[1] 42
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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;
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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