This challenge is about printing the abacaba sequence of a specific depth.

Here is a diagram of the first 5 sequences (a(N) is the abacaba sequence of depth N, upper/lowercase is just to show the pattern, this is not needed in the output of your program):

a(0) = A
a(1) = aBa
a(2) = abaCaba
a(3) = abacabaDabacaba
a(4) = abacabadabacabaEabacabadabacaba
a(25) = abacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabahabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabaiabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabahabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabajabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabahabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabagabacabadabacabaeabacabadabacabafabacabadabacabaeabacabadabacabaia...

As you can probably tell, the n'th abacaba sequence is the last one with the n'th letter and itself again added to it. (a(n) = a(n - 1) + letter(n) + a(n - 1))

Your task is to make a program or function that takes an integer and prints the abacaba sequence of that depth. The output has to be correct at least for values up to and including 15.

  • 3
    \$\begingroup\$ Wouldn't the sequence be undefined after 𝑎₂₅? \$\endgroup\$ – LegionMammal978 Jan 9 '16 at 13:04
  • 3
    \$\begingroup\$ @nicael I know, I was just wondering how 𝑎(∞) would be defined. \$\endgroup\$ – LegionMammal978 Jan 9 '16 at 13:29
  • 2
    \$\begingroup\$ Also known as the ruler sequence (but with letters instead of numbers), for something more easily Google-able. \$\endgroup\$ – user253751 Jan 10 '16 at 6:00
  • 4
    \$\begingroup\$ For what it's worth, any valid solution to this problem is also the solution to the Towers of Hanoi puzzle for N disks. \$\endgroup\$ – Jeff Zeitlin Apr 2 '19 at 11:59
  • 3
    \$\begingroup\$ Can we use 1-based indexing instead of 0-based indexing? \$\endgroup\$ – Esolanging Fruit Apr 3 '19 at 17:21

45 Answers 45


Pyth, 11 bytes


Simple reduction.

  • 2
    \$\begingroup\$ @Loovjo Oh. Makes no sense, 0 should be the empty sequence IMO, but I'll conform to the question... \$\endgroup\$ – orlp Jan 9 '16 at 12:52
  • 4
    \$\begingroup\$ Yeah, simple. goes and bangs head on wall \$\endgroup\$ – J Atkin Feb 13 '16 at 20:07
  • \$\begingroup\$ @JAtkin Open up Pyth's rev-doc.txt next to this answer, and it should readily show itself to be simple. \$\endgroup\$ – orlp Feb 13 '16 at 20:19
  • \$\begingroup\$ Hehehe, not what I meant (I don't know pyth, so....) \$\endgroup\$ – J Atkin Feb 13 '16 at 20:22

Python, 44 bytes

f=lambda n:"a"[n:]or f(n-1)+chr(97+n)+f(n-1)

Looks suspiciously might-be-golfable.


Haskell, 39 37 bytes

a 0="a"
a n=a(n-1)++['a'..]!!n:a(n-1)

Usage example: a 3 -> "abacabadabacaba".

Edit: @Angs found two bytes to save. Thanks!

  • \$\begingroup\$ Wouldn't a n=a(n-1)++[97+n]++a(n-1) work? Can't test right now. \$\endgroup\$ – seequ Jan 9 '16 at 18:36
  • \$\begingroup\$ @Seeq: no, [97+n] is a list of Integer and a(n-1) is a list of Char (aka String). You cannot concatenate lists with different types. toEnum makes a Char out of the Integer. \$\endgroup\$ – nimi Jan 9 '16 at 18:57
  • \$\begingroup\$ Ah, I always thought Char was just a specialized integer in Haskell. \$\endgroup\$ – seequ Jan 9 '16 at 23:47
  • \$\begingroup\$ ['a'..]!!n is 2 bytes shorter than toEnum(97+n) \$\endgroup\$ – Angs Oct 6 '16 at 18:11
  • \$\begingroup\$ @Angs: Good catch! Thanks! \$\endgroup\$ – nimi Oct 6 '16 at 22:29

Pyth, 14 13 bytes

Thanks to Jakube for saving a byte!


A solution with 14 bytes: VhQ=ks[k@GNk;k.



               # Implicit: k = empty string
VhQ            # For N in range input + 1      
   =           # Assign k
      +@GNk    # Position N at alphabet + k
    +k         # k + above
           ;   # End loop
            k  # Print k

Try it here!

  • \$\begingroup\$ Shouldn't "N in range" be on the V line? hQ is just eval(input) + 1 \$\endgroup\$ – Loovjo Jan 9 '16 at 12:58
  • \$\begingroup\$ @Loovjo Yeah, that's better and less confusing :) \$\endgroup\$ – Adnan Jan 9 '16 at 13:00
  • \$\begingroup\$ You can shorten =k to =. Pyth will automatically assign the result to k, since k is the first variable in the expression +k+@GNk. \$\endgroup\$ – Jakube Jan 9 '16 at 14:00
  • \$\begingroup\$ @Jakube Thank you very much! :) \$\endgroup\$ – Adnan Jan 9 '16 at 14:10
  • \$\begingroup\$ I have a different answer for this challenge. It won't beat this solution, but it does illustrate a technique for giving the first n characters of the sequence: Vt^2Q=+k@Gx_.BhN`1)k (In this instance, it's set to give the first 2^Q-1 characters as the challenge requires, but you can see how to change that.) \$\endgroup\$ – quintopia Jan 9 '16 at 22:12

Retina, 37 32 bytes


The trailing linefeed is significant. Input is taken in unary.

Try it online!

  • \$\begingroup\$ It does not work. \$\endgroup\$ – Leaky Nun Mar 31 '16 at 4:47
  • \$\begingroup\$ @KennyLau yes, because Retina changed since I posted this answer. If you check out the release that was most recent when this was posted directly from GitHub, it will work with that. \$\endgroup\$ – Martin Ender Mar 31 '16 at 5:25

Brainfuck, 157 bytes


Input is given in binary.

The basic idea is to repeatedly duplicate the current sequence (starting with "a") and to increment the last element after each iteration:

  1. a → aa → ab

  2. ab → abab → abac

  3. abac → abacabac → abacabac

  4. ...

When all of this has been done the specified amount of times, the result gets printed excluding the last element.

In-depth explanation

The memory is arranged in the following way:


            |--Element 1---|--Element 2---|

Countdown holds the number of copy cycles that are yet to be executed. The ABACABA sequence is stored in adjecent blocks, each made up of 3 cells. Value holds the character of the element (i.e. "A","B","C"...). The Copy flag indicates whether or not the corresponding element needs to be copied within the current copying cycle (0=copy, 1=don't). The End flag is set to 0 for the last element while it is being copied (it's 1 in all other cases).

Now to the actual (slightly ungolfed) program:

,                       read Countdown from input
+                       add 1 to avoid off-by-one error
>-[>++<-----]>-----     initialize value cell of first element to 97 ("a")
>>+                     set End flag of first element to 1
<<<<                    move to Countdown
[                       loop until Countdown hits 0 (main loop)
    -                   decrement Countdown
    >>                  move to Value cell of first element
    [                   copying loop
        [               duplication sub-loop
            -           decrement Value cell of the element to copy
            >>          move to End flag
            [>>>]       move to End flag of the last element
            <+<+        increment Copy and Value cell of last element (Copy cell is temporarily abused)
            <           move to End flag of second to last element
            [<<<]>>     move back to Copy cell of first element
            [>>>]<      move to Value cell of the first element where the Copy flag is 0
        >>[>>>]<        move to (abused) Copy flag of the last element
        [               "copy back" sub-loop
            -           decrement Copy flag
            <<          move to End flag of second to last element
            [<<<]>>     move back to Copy cell of first element
            [>>>]<      move to Value cell of the first element where the Copy flag is 0
            +           increment Value cell
            >>[>>>]<    move back to Copy flag of the last element
        +>+             set Copy and End flag to 1
        <<<             move to End flag of second to last element
        [<<<]>>         move back to Copy cell of first element
        [>>>]<          move to Value cell of the first element where the Copy flag is 0
        >+<             set Copy flag to 1
        >[>>>]<         move to Value cell of the next element to copy
    ]                   loop ends three cells behind the last "valid" Value cell
    <<<+                increment Value cell of last element
    >>                  move to End flag
    [<-<<]              reset all Copy flag
    <                   move to Countdown
>>>>                    move to End flag of first element
[>>>]<<<                move to End flag of last element                
<<<                     skip the last element
[<<.<]                  output Value cells (in reverse order, but that doesn't matter)
  • 2
    \$\begingroup\$ Welcome to the site! I'd be interested in a more detailed breakdown! \$\endgroup\$ – Post Rock Garf Hunter Apr 3 '19 at 14:15
  • 1
    \$\begingroup\$ @SriotchilismO'Zaic Thanks for your reply :) I have now added a detailed explanation. \$\endgroup\$ – orthoplex Apr 3 '19 at 20:46

Haskell, 36 bytes


Try it online!

This uses a different recursive method from most of the other answers. To get the next string in the sequence, we don't join two copies in the previous string with a new letter in between, but instead increment every letter and intersperse a's.

aba -> bcb -> abacaba
  • 1
    \$\begingroup\$ Do you mean bcb instead of cbc? \$\endgroup\$ – Jo King Sep 30 '19 at 2:29

05AB1E, 12 bytes (non-competitive)



I'll be damned. I fixed a lot of bugs thanks to this challenge haha.



'a             # Push the character 'a'
  I            # User input
   G           # For N in range(1, input)
    D          # Duplicate the stack
     N         # Push N
      >        # Increment
       .b      # Convert to alphabetic character (1 = A, 2 = B, etc.)
         s     # Swap the last two elements
          J    # push ''.join(stack)
           l   # Convert to lowercase
               # Implicit: print the last item of the stack
  • \$\begingroup\$ Why is it non-competitive? \$\endgroup\$ – Loovjo Jan 9 '16 at 13:31
  • \$\begingroup\$ @Loovjo I fixed the bugs after the challenge was posted, therefore it's non-competitive :( \$\endgroup\$ – Adnan Jan 9 '16 at 13:32

JavaScript (ES6), 43 42 bytes


A byte saved thanks to @Neil!

Yet another simple recursive solution...

  • \$\begingroup\$ (n+11).toString(36) saves you 1 byte, and works for up to a(25)! \$\endgroup\$ – Neil Jan 9 '16 at 18:08
  • \$\begingroup\$ @Neil Implemented. Thanks! \$\endgroup\$ – user81655 Jan 10 '16 at 2:24

CJam (14 bytes)


Online demo


Ruby (1.9 and up), 38 bytes

?a is a golfier way to write "a" but looks weird when mixed with ternary ?:


R, 48 bytes


Try it online!

Simple recursion.

  • \$\begingroup\$ Uh, what is paste0??? \$\endgroup\$ – Xi'an Apr 23 '19 at 20:34
  • \$\begingroup\$ @Xi'an paste0 is equivalent to paste with sep="", so you avoid the spaces between letters that paste would add by default. \$\endgroup\$ – Robin Ryder Apr 24 '19 at 10:48

C#, 59 bytes

string a(int n){return n<1?"a":a(n-1)+(char)(97+n)+a(n-1);}

Just another C# solution...


Perl, 33 bytes


No real need for un-golfing. Builds the string up by iteratively appending the next character in sequence plus the reverse of the string so far, using the ASCII value of 'a' as its starting point. Uses $\ to save a few strokes, but that's about as tricky as it gets.

Works for a(0) through a(25) and even beyond. Although you get into extended ASCII after a(29), you'll run out of memory long before you run out of character codes:

a(25) is ~64MiB. a(29) is ~1GiB.

To store the result of a(255) (untested!), one would need 2^256 - 1 = 1.15x10^77 bytes, or roughly 1.15x10^65 1-terabyte drives.

  • 1
    \$\begingroup\$ We need those atom-shudder yottabyte drives, now! \$\endgroup\$ – CalculatorFeline Mar 10 '16 at 20:10

Java 7, 158 bytes

class B{public static void main(String[]a){a('a',Byte.valueOf(a[0]));}static void a(char a,int c){if(c>=0){a(a,c-1);System.out.print((char)(a+c));a(a,c-1);}}}

I like to lurk around PPCG and I would enjoy being able to vote/comment on other answers.

Input is given as program parameters. This follows the same format as many other answers here in that it's a straight forward recursive implementation. I would have commented on the other answer but I don't have the rep to comment yet. It's also slightly different in that the recursive call is done twice rather than building a string and passing it along.

  • \$\begingroup\$ Welcome to PPCG then! I hope you'll do some more than voting and commenting in the future (but don't feel like you have to). :) \$\endgroup\$ – Martin Ender Apr 11 '16 at 19:47

Mathematica, 36 32 bytes


Have you ever watched TWOW 11B?

  • \$\begingroup\$ There is no need for the "", and then you can use infix notation for Fold. \$\endgroup\$ – Martin Ender Sep 22 '16 at 17:24
  • \$\begingroup\$ #1 causes null <>s, and #2 only works for binary functions. \$\endgroup\$ – CalculatorFeline Oct 15 '16 at 15:36
  • \$\begingroup\$ Did you post this comment on the answer you intended? Because I have no idea what you mean. :) \$\endgroup\$ – Martin Ender Oct 15 '16 at 15:39
  • \$\begingroup\$ *#1 causes StringJoin to join nulls, and #2 only works for binary or associative functions. (x~Fold~y~Fold~z=Fold[x,Fold[y,z]] instead of Fold[x,y,z]) \$\endgroup\$ – CalculatorFeline Oct 15 '16 at 15:42
  • \$\begingroup\$ Oh you mean "suggestion #1". No it doesn't cause Nulls. Why would it? \$\endgroup\$ – Martin Ender Oct 15 '16 at 15:44

Python, 62 54 46 45 bytes

I would like to think that this code can still be golfed down somehow.

Edit: Bug fix thanks to Lynn. -1 byte thanks to squid.

a=lambda n:n and a(n-1)+chr(97+n)+a(n-1)or'a'

Try it online!

  • \$\begingroup\$ Output should be in all-lowercase. The uppercase in the question is just for clarity about the repetition. \$\endgroup\$ – Loovjo Jan 9 '16 at 12:56
  • \$\begingroup\$ Whoops. Thanks for the clarification. \$\endgroup\$ – Sherlock9 Jan 9 '16 at 12:58
  • \$\begingroup\$ Blargle. Thanks @user81655 \$\endgroup\$ – Sherlock9 Jan 9 '16 at 13:20
  • \$\begingroup\$ This is invalid (it never terminates — try it). Even in the base case, the recursive part of the expression is evaluated. \$\endgroup\$ – Lynn Apr 2 '19 at 22:21
  • \$\begingroup\$ Fixed. Thanks @Lynn! \$\endgroup\$ – Sherlock9 Apr 3 '19 at 5:29

Mathematica, 46 bytes


Simple recursive function. Another solution:


K5, 18 bytes


Repeatedly apply a function to a carried value ("A") and each element of a sequence. The sequence is the alphabetic characters from B up to some number N (`c$66+!). The function joins the left argument on either side of the right argument ({x,y,x}).

In action:

  • \$\begingroup\$ I think the sequence should be lowercase, but that costs no bytes. \$\endgroup\$ – user48538 Jan 9 '16 at 18:05

JavaScript, 65 571 bytes



function a(n){
  return eval('s="a";for(i=0;i<n;i++)s+=(i+11).toString(36)+s')

1 - thanks Neil for saving 8 bytes

  • \$\begingroup\$ (i+11).toString(36) saves you 6 bytes. \$\endgroup\$ – Neil Jan 9 '16 at 18:14
  • \$\begingroup\$ @Neil Haha, that's a clever hack \$\endgroup\$ – nicael Jan 9 '16 at 18:16
  • \$\begingroup\$ Oh, and if you move the assignment s="a"; to before the for then it becomes the default return value and you can drop the trailing ;s for another 2 byte saving. \$\endgroup\$ – Neil Jan 9 '16 at 18:18
  • \$\begingroup\$ @Neil Nice, didn't know about that. \$\endgroup\$ – nicael Jan 9 '16 at 18:19
  • \$\begingroup\$ I think you can save a byte by incrementing i inline and dropping the increment in the for loop. So... for(i=0;i<n;)s+=(i+++11)... \$\endgroup\$ – Not that Charles Mar 11 '16 at 4:46

Japt, 20 17 bytes

97oU+98 r@X+Yd +X

Test it online!

How it works

         // Implicit: U = input integer
65oU+66  // Generate a range from 65 to U+66.
r@       // Reduce each item Y and previous value X in this range with this function:
X+Yd     // return X, plus the character with char code Y,
+X       // plus X.

         // Implicit: output last expression

Non-competing version, 14 bytes

97ôU r@X+Yd +X

The ô function is like o, but creates the range [X..X+Y] instead of [X..Y). Test it online!

I much prefer changing the 97 to 94, in which case the output for 5 looks like so:


Java, 219 bytes

My first code golf attempt. Probably can be golf'd further, but I'm hungry and going out to lunch.

public class a{public static void main(String[]a){String b=j("a",Integer.parseInt(a[0]),1);System.out.println(b);}public static String j(String c,int d,int e){if(d>=e){c+=(char)(97+e)+c;int f=e+1;c=j(c,d,f);}return c;}}


public class a {
    public static void main(String[] a) {
        String string = addLetter("a", Integer.parseInt(a[0]), 1);

    public static String addLetter(String string, int count, int counter) {
        if (count >= counter) {
            string += (char) (97 + counter) + string;
            int f = counter + 1;
            string = addLetter(string, count, f);
        return string;

Pretty straightforward brute force recursive algorithm, uses char manipulation.

  • \$\begingroup\$ You can omit the public keyword from a and addLetter/j. \$\endgroup\$ – user8397947 Jun 9 '16 at 21:51

MATL, 14 bytes


This uses version 8.0.0 of the language/compiler, which is earlier than the challenge.


>> matl
 > 0i:"t@whh]97+c
> 3


The secuence is created first with numbers 0, 1, 2, ... These are converted to letters 'a', 'b', 'c' at the end.

0         % initiallize: a(0)
i:        % input "N" and create vector [1, 2, ... N]
"         % for each element of that vector
  t       % duplicate current sequence
  @       % push new value of the sequence
  whh     % build new sequence from two copies of old sequence and new value
]         % end for
97+c      % convert 0, 1, 2, ... to 'a', 'b', 'c'. Implicitly print


Try it online!


Powershell, 53,46,44,41 Bytes


Pasting into console will generate erronous output on the second run since $d is not re-initialized.

Save 2 bytes by using += Save 3 bytes thanks to @TimmyD

  • \$\begingroup\$ @TimmyD Actually gets it down to 41 since I won't need the (,). \$\endgroup\$ – Jonathan Leech-Pepin Apr 6 '16 at 16:31
  • \$\begingroup\$ No, that was my fault, I actually forgot to update it even though I said I did. \$\endgroup\$ – Jonathan Leech-Pepin Apr 6 '16 at 19:42
  • \$\begingroup\$ the script does not wirk with 0 and does not generate a uppercase letter \$\endgroup\$ – mazzy Apr 2 '19 at 8:02

Gaia, 14 bytes


Try it online!

₵a		| Push lowercase alphabet
  Ø		| push lowercase string
   @         ₓ	| push the input and do everything between ⟪⟫ that many times
    ⟪¤		| swap
      ṇ		| take the last (first) character
       3ṁ	| push the 3rd item on the stack
         ¤+	| swap and concatenate
           ṫ⟫	| and palindromize

PowerShell, 54 bytes


Try it online!


Japt, 8 bytes


Try it

;gCåÈ+iY     :Implicit input of integer
 g           :Index into
; C          :  Lowercase alphabet
   å         :  Cumulatively reduce, with an initial value of an empty string
    +        :    Append a copy of the current value
     i       :    Prepended with
      Y      :    The current letter

Husk, 12 bytes


Try it online!

Uses 1-based indexing, which I hope is OK.


!             (                                          !!)
 ¡             iterate(                              )
  S                        <*>
   +                   (++)
    o                         (                     )
     Ṡ                         join$   .
      :                             (:)
       o                                    .
        →                               succ
         ▲                                   maximum
          "a                                          "a"


APL(NARS), 24 chars, 48 bytes



  f 0
  f 1
  f 2
  f 3
  f 4
  • 1
    \$\begingroup\$ Doesn’t APL use it’s own code page with every character one byte, making this 24 bytes? \$\endgroup\$ – Loovjo Jun 25 '19 at 7:40
  • \$\begingroup\$ @Loovjo for what I know Nars Apl has character set 2 bytes for character \$\endgroup\$ – RosLuP Jun 25 '19 at 7:43

PHP -r, 43 bytes

register_argc_argv must be enabled for this to work.


Try it online!

PHP, 51 bytes

An anonymous function that prints the output directly.


Try it online!


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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