Answer to life, the universe, and everything

46

8

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!

Mateen Ulhaq

Posted 2011-03-10T04:51:42.090

Reputation: 1 889

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 – 2011-03-10T10:30:13.170

@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 – 2011-03-10T13:22:54.790

@fR0DDY : There was no clear definition on how the rest of the input should be handled, so there's no 'wrong' here. – PatrickvL – 2011-03-10T15:46:48.440

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 – 2011-03-10T15:56:53.917

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 – 2011-03-10T16:10:31.447

Is the sample input supposed to contain invisible nonprintable characters? Because it does. – None – 2017-02-12T21:18:09.020

muntoo: How should a trailing line break in the input be handled (i.e. valid input vs. valid input with a line break appendded)? Would that be invalid already since the input is not exactly the specified one? Also, may 42 be part of the output for invalid input or may 42 only be printed if the input matched? – Joey – 2011-03-12T15:05:09.767

Can we use uppercase instead? – Adám – 2017-05-04T12:37:37.323

This question’s score should be left as is... – JayCe – 2018-08-01T21:59:42.723

@Joey Trailing line breaks don't have to count as input. – Mateen Ulhaq – 2011-07-01T02:38:11.607

Answers

20

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.

YOU

Posted 2011-03-10T04:51:42.090

Reputation: 4 321

326,{).[96+]*}%n+=42`* for 21 (inc newline). – Nabb – 2011-03-11T02:09:01.157

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 – 2011-03-12T04:46:26.933

@Nabb, heheh, I didn't realize newline made it different. – YOU – 2011-03-12T05:44:40.753

13

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.

Ventero

Posted 2011-03-10T04:51:42.090

Reputation: 9 842

What about the newline from gets? – steenslag – 2011-03-10T12:44:03.287

2@steenslag: The specs don't say anything the input being terminated by a newline, so this solution assumes there is none. – Ventero – 2011-03-10T12:48:03.383

11

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.

Joey Adams

Posted 2011-03-10T04:51:42.090

Reputation: 9 929

1This will print 42 if the string is longer than the desired string and the prefix matches with the desired string. – fR0DDY – 2011-03-10T08:37:50.077

8

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

sam hocevar

Posted 2011-03-10T04:51:42.090

Reputation: 581

+1 , that works ;) Umm could you please elaborate as how $s.=chr(96.5+sqrt($i+=2)); works ? – Clyde Lobo – 2011-03-10T12:24:33.350

Edited. I hope it makes sense :-) – sam hocevar – 2011-03-10T12:45:37.403

for(;$i<702;)$s.=chr(96.5+sqrt($i+=2));echo($s==$argv[1])*42; Only 61 chars, assuming stdin input – Viper_Sb – 2011-03-10T16:11:30.447

@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 – 2011-03-10T17:37:24.947

58 bytes in PHP 5.6 or later: for(;704>$i+=2;)$s.=chr(96.5+$i**.5);echo$s!=$argv[1]?:42; – Titus – 2017-02-11T17:49:25.343

just a doubt here, aren't php open and close tags necessary for this code to work? – th3pirat3 – 2017-12-11T00:41:56.503

Isn't there a space missing after the echo? – powtac – 2011-06-12T23:56:49.287

1@powtac the language syntax doesn’t require a space here – sam hocevar – 2011-12-31T04:49:33.737

7

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

J B

Posted 2011-03-10T04:51:42.090

Reputation: 9 638

Excellent. I tried hard to beat this w/recursive regex but couldn't get below 43c. :-(( – rubber boots – 2011-03-10T11:04:17.283

Why is it necessary to say $a++."{$b}" instead of just $a++.$b? – Timwi – 2011-03-14T00:11:13.130

@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 – 2011-03-14T06:55:11.363

Of course. Thanks for explaining! – Timwi – 2011-03-18T15:07:59.883

Came up with a 33 byte solution for this! Try it online!

– Dom Hastings – 2017-12-10T19:52:43.583

7

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? :)

Cinari

Posted 2011-03-10T04:51:42.090

Reputation: 81

3Welcome to PPCG! – Steadybox – 2017-11-10T14:57:08.613

6

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

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


$

Joey Adams

Posted 2011-03-10T04:51:42.090

Reputation: 9 929

1fwiw this code is also still very readable. – Dan Burton – 2011-03-11T05:13:02.090

1Since zipWith stops when it reaches the end of the shorter list, you can replace ['a'..'z'] with ['a'..] and save 3 characters. – hammar – 2011-06-09T19:29:38.923

@hammar: Thanks. I saved 1 more char by using >>= (concatMap) in lieu of concat and zipWith. – Joey Adams – 2011-06-10T00:16:28.503

@hammar: Saved even more by using do notation instead of >>= and lambda :-) – Joey Adams – 2011-06-10T00:22:18.557

@Joey: Another improvement: do n<-[1..26];replicate n$['`'..]!!n can be shortened by another 4 characters to do c<-['a'..'z'];[c|_<-['a'..c]] – hammar – 2011-06-10T00:41:55.137

2@Joey: Or even better: [c|c<-['a'..'z'],_<-['a'..c]] – hammar – 2011-06-10T00:44:28.210

4

J, 29

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

example:

f 'oasijfiojasef'

f 23841235

f 'abbccc...'
42

Eelvex

Posted 2011-03-10T04:51:42.090

Reputation: 5 204

I like J. And I find it ugly and horrible. And I like it. – seequ – 2014-11-03T16:40:49.817

4

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

Jonathan M Davis

Posted 2011-03-10T04:51:42.090

Reputation: 705

3

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}

user62131

Posted 2011-03-10T04:51:42.090

Reputation:

3

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

Kun Ren

Posted 2011-03-10T04:51:42.090

Reputation: 181

I think just paste is fine here, and you can use scan(,"") instead of readline(). – Giuseppe – 2017-12-11T17:10:23.900

3

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

PatrickvL

Posted 2011-03-10T04:51:42.090

Reputation: 641

3

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

HoLyVieR

Posted 2011-03-10T04:51:42.090

Reputation: 839

2Clever! 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 – 2011-06-10T03:50:25.500

3

Scala 79

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

Lalith

Posted 2011-03-10T04:51:42.090

Reputation: 251

3

Pyth, 14

*42qzsm*dhxGdG

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

isaacg

Posted 2011-03-10T04:51:42.090

Reputation: 39 268

Argh, I came too late. Can you explain how it works? The function m cause me trouble… – Jim – 2017-05-31T16:36:46.677

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 – 2017-05-31T22:11:13.723

'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 – 2014-11-04T21:43:55.990

2

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

Chromozorz

Posted 2011-03-10T04:51:42.090

Reputation: 338

{$[x~.Q.a@&1+!26;42;]} for 22 bytes. – streetster – 2017-12-11T12:20:26.537

142*(&!27)~-96+"j"$ for 18 bytes (porting my oK answer). – streetster – 2018-01-15T22:33:50.583

2

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

Adám

Posted 2011-03-10T04:51:42.090

Reputation: 37 779

2

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

Hoa Long Tam

Posted 2011-03-10T04:51:42.090

Reputation: 1 902

1Why not use raw_input instead sys.stdin.read? – Juan – 2011-03-10T11:33:09.200

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 – 2011-03-10T15:42:30.567

2

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}

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

mellamokb

Posted 2011-03-10T04:51:42.090

Reputation: 5 544

Well you can reduce another 12 chars if you dont use var to declare variables ;) – Clyde Lobo – 2011-03-10T06:03:31.447

@Clyde: Thanks! Also found I could remove space between for (. – mellamokb – 2011-03-10T06:16:46.877

Yeah , was about to suggest the same ;) Oh and I coded a solution in PHP using the same logic as yours – Clyde Lobo – 2011-03-10T06:18:17.723

You can save another 2 chars by replacing

return(z==r)?42:0; with return z==r?42:0 – Clyde Lobo – 2011-03-10T06:22:39.637

j>0 could be just j I think. – YOU – 2011-03-10T06:25:03.303

@S.Mark : yeah , and then the solution would be at 98 chars – Clyde Lobo – 2011-03-10T06:29:11.333

@Clyde, @S.Mark: Thanks. Updated. – mellamokb – 2011-03-10T06:38:59.510

You can save another char doing return(z==r)*42 – Juan – 2011-03-10T11:36:12.223

@Juan: Thanks. Updated. – mellamokb – 2011-03-10T12:53:33.097

Save 1 more with while(i++<26) – gnarf – 2011-03-11T12:32:30.383

@gnarf: Thanks. Updated. – mellamokb – 2011-03-11T16:02:30.030

I shortened this by another two characters by changing i=r='';while(i++<26) to for(i=r='';i++<26;) (first one) and for(j=i;j;j--) to for(j=i;j--;) (second one) – Timwi – 2011-03-14T01:34:49.423

You can reduce your code to 83 bytes thanks to arrow functions : a=z=>{for(i=r='';i++<26;)for(j=i;j--;)r+=String.fromCharCode(i+96);return(z==r)*42} Then you can a('abbccc..........z'); – ClementNerma – 2017-11-09T10:25:51.683

You could use a=z=>{yourfunctionbody}. – flawr – 2014-11-05T15:52:28.760

2

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;

Clyde Lobo

Posted 2011-03-10T04:51:42.090

Reputation: 1 395

2Could be 80 chars if it weren't for all the freaking dollar signs. – Joey Adams – 2011-03-10T06:41:41.400

Also see my entry for a single-loop solution. – sam hocevar – 2011-03-10T12:17:53.460

2

Python - 62 chars

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

gnibbler

Posted 2011-03-10T04:51:42.090

Reputation: 14 170

2Could be shorter in Python 3: print("".join(x*chr(x+96)for x in range(27))==input())*42. – mbomb007 – 2015-03-03T14:46:10.417

2

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

rubber boots

Posted 2011-03-10T04:51:42.090

Reputation: 1 014

2

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

coredump

Posted 2011-03-10T04:51:42.090

Reputation: 6 292

2

05AB1E, 7 bytes

AƶJQ42*

Try it online!


Wellp, 05AB1E keeps evolving.

Magic Octopus Urn

Posted 2011-03-10T04:51:42.090

Reputation: 19 422

2

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

Casey Chu

Posted 2011-03-10T04:51:42.090

Reputation: 1 661

2

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.

syntaqx

Posted 2011-03-10T04:51:42.090

Reputation: 131

2

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

OSG

Posted 2011-03-10T04:51:42.090

Reputation: 21

Is it really impossible to remove any whitespace from this? – Esolanging Fruit – 2017-05-31T16:51:05.800

1Condensed Version, 61 bytes - o="":For i=1To 26:o=o &String(i,Chr(i+96)):Next:?-42*([A1]=o) – Taylor Scott – 2017-09-09T19:20:33.807

@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 – 2017-11-10T21:21:56.387

2

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.

AdmBorkBork

Posted 2011-03-10T04:51:42.090

Reputation: 41 581

you could save a byte :) Try it online!

– mazzy – 2019-04-04T08:45:12.957

1

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

Nick Clifford

Posted 2011-03-10T04:51:42.090

Reputation: 1 184

Welcome to PPCG! – Post Rock Garf Hunter – 2017-02-12T04:20:16.753

@WheatWizard :D – Nick Clifford – 2017-02-12T04:21:22.143

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: https://tio.run/nexus/05ab1e#@@9Y5liZbVd5eHqtV2CmidH//1/z8nWTE5MzUgE)

– Okx – 2017-02-12T23:46:23.487

Unfortunately, this isn't competing as 05AB1E was created after this question was posted. – Okx – 2017-02-12T23:48:04.773

@Okx Thank you, and I know, I was just practicing. – Nick Clifford – 2017-02-13T02:52:05.793

1

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.

user62131

Posted 2011-03-10T04:51:42.090

Reputation:

1

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

user48543

Posted 2011-03-10T04:51:42.090

Reputation:

The input being a string, the implicit input would better be z or w instead of Q. Nice shot though! – Jim – 2017-06-02T07:36:14.940

1

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

Taylor Scott

Posted 2011-03-10T04:51:42.090

Reputation: 6 709

1

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.

Julian Wolf

Posted 2011-03-10T04:51:42.090

Reputation: 1 139

1

Multiplying saves a byte over and

– Reinstate Monica – 2019-09-10T11:36:41.720

1

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

kalsowerus

Posted 2011-03-10T04:51:42.090

Reputation: 1 894

1

Perl 6, 32 bytes

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

Sean

Posted 2011-03-10T04:51:42.090

Reputation: 4 136

1

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

Stephen Perelson

Posted 2011-03-10T04:51:42.090

Reputation: 151

Can save two chars by replacing ?42:0 with *42 – mellamokb – 2011-03-12T05:43:26.367

1

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)

jpjacobs

Posted 2011-03-10T04:51:42.090

Reputation: 3 440

1

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

mikera

Posted 2011-03-10T04:51:42.090

Reputation: 1 233

would save 6 chars if Clojure allowed nested #()s..... important feature request for Clojure 1.4 I think! – mikera – 2011-03-10T13:58:29.723

1

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

PatrickvL

Posted 2011-03-10T04:51:42.090

Reputation: 641

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 – 2011-03-12T13:56:26.160

@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 – 2011-03-12T16:23:33.823

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!

gastropner

Posted 2011-03-10T04:51:42.090

Reputation: 3 264

1

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

Matthew Read

Posted 2011-03-10T04:51:42.090

Reputation: 521

1

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

ბიმო

Posted 2011-03-10T04:51:42.090

Reputation: 15 345

1ΣzR can be . – Zgarb – 2017-12-11T07:49:17.623

1

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

alert(q("rgrg"));

Tom Gullen

Posted 2011-03-10T04:51:42.090

Reputation: 1 159

1

Japt, 11 bytes

;¶CËpEÄ
*42

Try it

Embodiment of Ignorance

Posted 2011-03-10T04:51:42.090

Reputation: 7 014

1

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

roblogic

Posted 2011-03-10T04:51:42.090

Reputation: 554

1False positive on abbccc...zzzzz[something else]. – GammaFunction – 2019-09-09T08:04:25.533

1I found a 56 byte solution. Hint: ${(l:++i:)} – GammaFunction – 2019-09-09T08:18:12.260

Nice, my early attempts to use {a..z} never worked :P – roblogic – 2019-09-09T08:24:00.397

1Unfortunately, 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 – 2019-09-09T08:35:02.530

1Hey, 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 – 2019-09-09T09:19:36.377

interesting, but incorrectly prints 42 given empty input – roblogic – 2019-09-09T09:43:59.523

1Whoops, 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 – 2019-09-09T09:46:22.193

1There are two # in there, they are doing two different things: prefix removal and string length. If it is a perfect match, we get $[0+42]. Otherwise, the string is not empty, and we get $[N+42]. – GammaFunction – 2019-09-09T11:06:18.280

1

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!

GammaFunction

Posted 2011-03-10T04:51:42.090

Reputation: 2 838

1

Groovy - 64

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

TheBigS

Posted 2011-03-10T04:51:42.090

Reputation: 151

1

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.

AndoDaan

Posted 2011-03-10T04:51:42.090

Reputation: 2 232

1

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

Display_name

Posted 2011-03-10T04:51:42.090

Reputation: 330

I think you are supposed to count the headers and using statements. – None – 2014-11-05T02:33:52.043

You're right. My solution is now 157 characters long. – Display_name – 2014-11-05T10:02:39.050

1

Q, 31 30

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

tmartin

Posted 2011-03-10T04:51:42.090

Reputation: 3 917

1

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)

Leaky Nun

Posted 2011-03-10T04:51:42.090

Reputation: 45 011

1

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.

Conor O'Brien

Posted 2011-03-10T04:51:42.090

Reputation: 36 228

0

SmileBASIC, 58 bytes

DEF F S
FOR I=1TO 26C$=C$+CHR$(I+64)*I
NEXT?42OR C$!=S
END

I had to make it a function since the maximum INPUT length is 128 characters.

12Me21

Posted 2011-03-10T04:51:42.090

Reputation: 6 110

0

R, 74 bytes

g=function(x){if(x==paste(rep(rep(letters[1:26]),(1:26)),collapse=""))42}

Zahiro Mor

Posted 2011-03-10T04:51:42.090

Reputation: 371

0

Java 8, 103 101 87 bytes

s->{String r="";for(char c=96,i;++c<123;)for(i=96;i++<c;)r+=c;return r.equals(s)?42:0;}

Returns 0 for everything that doesn't match the expected input.

Explanation:

Try it here.

s->{                       // Method with String parameter and integer return-type
  String r="";             //  String starting empty
  for(char c=96,i;++c<123;)//  Loop (1) over the lowercase alphabet:
    for(i=96;i++<c;)       //   Inner loop (2) `c-i` amount of times:
      r+=c;                //    Append that many of the current letter to the String
                           //   End of inner loop (2) (implicit / single-line body)
                           //  End of loop (1) (implicit / single-line body)
  return r.equals(s)?      //  If the input equals the String:
    42                     //   Return 42
   :                       //  Else:
    0;                     //   Return 0
}                          // End of method

Kevin Cruijssen

Posted 2011-03-10T04:51:42.090

Reputation: 67 575

1I think you can remove the braces around that for-loop – user41805 – 2017-02-13T15:58:14.717

0

Axiom, 141 bytes

f(x:String):NNI==(c:=96;i:=0;k:=1;repeat(c:=c+1;i:=i+1;for j in 1..i repeat(k>#x or ord(x.k)~=c=>return 0;k:=k+1);c=122=>break);k=#x+1=>42;0)

ungolf

--It would return 42 if the string in input it is as string above this codegolf question 
--it would return 0 in other cases; suppose Axiom ord() return 97..122 for a..z (ascii)
ff(x:String):NNI==
   c:=96;i:=0;k:=1
   repeat
      c:=c+1; i:=i+1           -- c='a'=97 i=1 k=1
      for j in 1..i repeat
               k>#x or ord(x.k)~=c=>return 0
               k:=k+1
      c=122=>break -- c==122 is 'z'
   k=#x+1=>42
   0

RosLuP

Posted 2011-03-10T04:51:42.090

Reputation: 3 036

0

Japt, 13 12 11 bytes

Outputs 42 or false.

;¶CËpEÄé#*

Try it online

Shaggy

Posted 2011-03-10T04:51:42.090

Reputation: 24 623

0

Python 3, 58 bytes

lambda s:[42][''.join([i*chr(i+96)for i in range(27)])!=s]

Try it online!

Six years late to the party?

golfed 4 bytes off when I realized I could've used != instead of 1- ==

osuka_

Posted 2011-03-10T04:51:42.090

Reputation: 391

0

JavaScript, 86 Bytes

c="";for(x=0;x<26;)c+=String.fromCharCode(x+97).repeat(++x);alert(prompt("")==c?42:0);

White spaced:

c="";
for(x=0;x<26;)
    c+=String.fromCharCode(x+97).repeat(++x);
alert(prompt("")==c?42:0);

I couldn't indent by 4 spaces for some reason. Not sure if using alert is allowed.

Edit: Fixed indent

xDest

Posted 2011-03-10T04:51:42.090

Reputation: 31

0

Jelly, 9 bytes

ØaxJ¤⁼×42

Try it online!

There is already a 13 byte Jelly answer, but the user had their account deleted, and it felt wrong to just edit in this code.

How it works

ØaxJ¤⁼×42 - Main link. Argument: s (string)   e.g. "abc"
Øa  ¤     - Yield the lowercase alphabet           "abc...xyz"   
   J      - Yield range(length)                    [1 2 ... 25 26]
  x       - Repeat (vectorising).                  "abbccc..."
     ⁼    - Equal to the input? Call the A         0
      ×42 - Multiply 42 by A                       0

caird coinheringaahing

Posted 2011-03-10T04:51:42.090

Reputation: 13 702

0

Pyth - 21 Bytes

V26=Y+Y*@GNhN;IqsYz42  

Explanation:

V26=Y+Y*@GNhN;IqsYz42  z is initialised to input and Y to empty list
V26                    For N from 0 to 25
   =Y                  Set Y to
      Y                Y
     +                 Plus
        @GN            Item N of the alphabet
      *                Times
           hN          N plus one
             ;         End For
              I        If
                sY     Concatenate all elements of Y       
               q       Equals
                  z    z  
                   42  Print 42   

Tornado547

Posted 2011-03-10T04:51:42.090

Reputation: 389

0

Javascript (ES6) 84 bytes

s=>[...Array(26)].map((_,i)=>String.fromCharCode(97+i).repeat(i+1)).join("")==s?42:0

I don't think an explanation is needed, but here's one anyway:

s=> // input
    [...Array(26)] // preparing alphabet array
    .map((_,i)=>String.fromCharCode(97+i).repeat(i+1)) // using the current index to get the corresponding letter and repeat it as many times as it's 1-index
    .join("")==s?42:0 // Join the array into a string and check if equal to input.

Brian H.

Posted 2011-03-10T04:51:42.090

Reputation: 513

0

APL NARS 14 chars

{⍵≡⎕a/⍨⍳26:42}

it return 42 for the request string, nothing if something else.

  f←{⍵≡⎕a/⍨⍳26:42}
  w←(⍳26)/⎕a
  f 2
  f w
42
  f 'str'

RosLuP

Posted 2011-03-10T04:51:42.090

Reputation: 3 036

0

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

Shaun Bebbers

Posted 2011-03-10T04:51:42.090

Reputation: 1 814

0

AWK, 65 bytes

{for(;i<26;)for(j=++i;j--;)L=L sprintf("%c",i+96);$0=L==$0?42:0}1

Try it online!

Maybe I should develop a golfing version of AWK, but until then, here is my AWK solution :)

Robert Benson

Posted 2011-03-10T04:51:42.090

Reputation: 1 339

0

K (oK), 14 bytes

Solution:

42*(&!27)~-96+

Try it online!

Explanation:

Returns 42 if the input matches the "abbccc..." otherwise 0.

42*(&!27)~-96+ / the solution
          -96+ / subtract 96 from the input (vectored)
         ~     / matches?
   (&!27)      / where (&) til (!) 27. Generates 1 2 2 3 3 3 4 4 4 4... sequence
42*            / multiply result (0 false or 1 true) by 42

streetster

Posted 2011-03-10T04:51:42.090

Reputation: 3 635

0

Python 2, 69 bytes

x=""
for i in range(26):x+=chr(97+i)*(i+1)
if raw_input()==x:print 42

Try it online!

FantaC

Posted 2011-03-10T04:51:42.090

Reputation: 1 425

0

Julia 0.6, 55 bytes

s->join("$c"^i for (i,c) in enumerate('a':'z'))==s?42:0

Try it online!

gggg

Posted 2011-03-10T04:51:42.090

Reputation: 1 715

0

Lua, 80 bytes

c=""for i=1,26 do c=c..string.char(i+96):rep(i)end print(c~=io.read()and""or 42)

Try it online!

Brief explanation: creates the string and then compares it with the input. Output is an empty string or 42.

Visckmart

Posted 2011-03-10T04:51:42.090

Reputation: 151

0

Wren, 72 bytes

Generate the range 'a'..'z'. Multiply the string-converted value by the value - 96. Join the list. Check whether the input is equal to this string.

Fn.new{|A|A==(1..26).map{|x|String.fromCodePoint(x+96)*(x)}.join()?42:0}

Try it online!

user85052

Posted 2011-03-10T04:51:42.090

Reputation:

0

Groovy, 70

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

Salesman

Posted 2011-03-10T04:51:42.090

Reputation: 121

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 – 2011-09-28T08:04:44.520

0

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

Stas

Posted 2011-03-10T04:51:42.090

Reputation: 31

Since this is code golf, you should post your score and your golfed code, i.e. with no unnecessary whitespace – FryAmTheEggman – 2015-09-29T19:38:07.390

0

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.

BobTheAwesome

Posted 2011-03-10T04:51:42.090

Reputation: 509

0

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
 }

FireFly

Posted 2011-03-10T04:51:42.090

Reputation: 7 107

0

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

Paolo

Posted 2011-03-10T04:51:42.090

Reputation: 696

0

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;

Jeto

Posted 2011-03-10T04:51:42.090

Reputation: 1 601

0

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)

Actorclavilis

Posted 2011-03-10T04:51:42.090

Reputation: 161

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 – 2017-02-27T08:26:02.690

0

Pylongolf2, 21 bytes

con1968701440=?42~¿

Explanations:

con1968701440=?42~¿
c                   read input
 on                 hash it and then convert into integer
   1968701440       push the (aaa.zz) thing (but hashed) into the stack
             =      compare them
              ?     if true,
               42~  output 42
                  ¿ end if statement.

That last inverted question mark messed me up by 2 bytes :|

user47018

Posted 2011-03-10T04:51:42.090

Reputation:

This is incorrect if more than one string can have that hash. – None – 2017-02-12T21:09:05.963