Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Given N (2 <= N), print N lines of the letter Fibonacci series like this (i.e. N = 5) First, start with a and b:

a
b

Next, add the two lines.

a
b
ab

Keep adding the last two lines.

a
b
ab
bab

Keep going...

a
b
ab
bab
abbab

And we're done.

Remmeber, this is , so the code with the fewest bytes wins.

share|improve this question
4  
Related – TimmyD 2 days ago
    
Can it be a function which returns a list of terms up to N? – Flp.Tkc 2 days ago
    
Do we have to print the result or can we return a list of strings from a function? – nimi 2 days ago
    
Wait, so it doesn't have to work for n=1? – Socratic Phoenix 2 days ago
    
Also, can we use 0-based indexing? – Socratic Phoenix 2 days ago

32 Answers 32

Python 2, 41 bytes

Saved 3 bytes thanks to @xnor

a,b="ab";exec"print a;a,b=b,a+b;"*input()

Test on Ideone

Simply follows the recursive definition.

share|improve this answer
    
This is shorter as a program: a,b="ab";exec"print a;a,b=b,a+b;"*input(). – xnor 2 days ago
    
@xnor So it is, thanks! – ETHproductions 2 days ago
1  
Might want to specify python 2 :) – Flp.Tkc yesterday

Haskell, 29 35 32 bytes

a%b=a:b%(a++b)
(`take`("a"%"b"))

Simple recursion.

For reference: the old version (an adaption of this answer), concatenated the strings in the wrong order, so I had to add a flip(...) which made it too long (35 bytes).

f="a":scanl(flip(++))"b"f
(`take`f)
share|improve this answer
    
The output is different from the example (different order in concatenation): ["b","a","ab","aba","abaab"] – Angs 2 days ago
    
@Angs: Oops what a mistake! Fixed. – nimi 2 days ago

05AB1E, 12 11 bytes

Thanks to Emigna for saving a byte!

'a='b¹GD=Š«

Uses the CP-1252 encoding. Try it online!

share|improve this answer
1  
̓ could just as well be G as you're not using N :) – Emigna 2 days ago
    
@Emigna Oh yeah, you're right! Thanks :)! – Adnan yesterday

Jelly, 11 10 bytes

”a”bṄ;¥@¡f

Try it online!

How it works

”a”bṄ;¥@¡f  Main link. Argument: n

”a          Set the return value to 'a'.
  ”b    ¡   Call the link to the left n times, with left argument 'b' and right
            argument 'a'. After each call, the right argument is replaced with the
            left one, and the left argument with the return value. The final
            return value is yielded by the quicklink.
      ¥       Combine the two atoms to the left into a dyadic chain.
    Ṅ           Print the left argument of the chain, followed by a linefeed.
     ;          Concatenate the left and right argument of the chain.
       @      Call the chain with reversed argument order.
         f  Filter the result by presence in n. This yields an empty string
            and thus suppresses the implicit output.
share|improve this answer
    
I had the ”a”b;@Ṅ part down, but I couldn't figure out where to go from there... now I know :-) – ETHproductions 2 days ago

Java 7, 69 bytes

String c(int n,String a,String b){return n--<1?"":a+"\n"+c(n,b,a+b);}

ungolfed

 class fibb {


public static void main(String[] args) {
    System.out.println( c( 7, "a" , "b" ) );

}
static String c(int n,String a,String b) {

    return n-- < 1  ? "" : a + "\n" + c(n,b,a + b);

}
}
share|improve this answer
    
You really need to format your ungolfed code a bit more in your answers.. xD +1 though, and it even works for any other starting strings different than just a and b. I'm not sure if the "a" and "b" parameters should be counted towards the byte-count though, since the question specifically states it should use a and b. Not that Java will ever win anyway. ;) – Kevin Cruijssen yesterday
    
@KevinCruijssen the string parameters are required because their values change each time the method is invoked. – Snowman yesterday
    
@Snowman I know they are required.. I'm just saying that the byte-count should maybe be 75 bytes (+6 for "a" and "b") instead of 69 because the challenge specifically asked for a and b, and the code-snipped/method currently uses a variable input. Not sure what the rules are regarding something like this, but I personally think it should be counted. Otherwise you could in some languages have a function that executes a parameter function, and then simply give the entire challenge-function in the parameter without counting its bytes. Sounds like a standard-loophole type of rule. – Kevin Cruijssen yesterday
1  
I love Java answers. They stand out so nice - 12 bytes here, 5 there, 17 here... 70 bytes there... wait, what? Oh, it's Java again... +1 – Rudolf L. Jelínek yesterday

JavaScript (ES6), 43 42 bytes

Saved a byte thanks to @Arnauld

f=(n,a="a",b="b")=>n&&f(n-!alert(a),b,a+b)
share|improve this answer

Emacs, 26, 25-ish keystrokes

Program

#n to be read as key with digit(s) n:

ARETBRETF3UPUPC-SPACEC-EM-WDOWNDOWNC-Y UPC-AC-SPACEC-EM-WDOWNC-EC-YRETF4C-#(n-2)F4

Explanation

command(s)               explanation                      buffer reads (| = cursor aka point)
-----------------------------------------------------------------------------------------------
A<RET> B<RET>            input starting points            "a\nb\n|"
<F3>                     start new macro                  "a\nb\n|"
<UP><UP>                 move point two lines up          "|a\nb\n"
C-<SPACE> C-E M-W        copy line at point               "a|\nb\n"
<DOWN><DOWN>             move point two lines down        "a\nb\n|"
C-Y                      yank (paste)                     "a\nb\na|"
<UP>                     move point one line up           "a\nb|\na"
C-A C-<SPACE> C-E M-W    copy line at point               "a\nb|\na"
<DOWN>                   move point one line down         "a\nb|\na|"
C-E C-Y <RET>            yank (paste) and add new line    "a\nb|\nab\n|"
<F4>                     stop macro recording             "a\nb|\nab\n|"
C-#(n-3) <F4>            apply macro n-3 times            "a\nb|\nab\nbab\nabbab\n|"

With n=10

a
b
ab
bab
abbab
bababbab
abbabbababbab
bababbababbabbababbab
abbabbababbabbababbababbabbababbab
bababbababbabbababbababbabbababbabbababbababbabbababbab
share|improve this answer
    
I'm torn. On one hand, I always upvote editor-golf, but on the other hand I use vim. Oh well, +1 anyway. :) – DrMcMoylex yesterday
    
@DrMcMoylex just convert it to vim with C-u M-x convert-to-vim – YSC yesterday

CJam, 19 17 bytes

'a'b{_@_n\+}ri*;;

explanation

"a": Push character literal "a" onto the stack.
"b": Push character literal "b" onto the stack.
{_@_p\+}
    {: Block begin.
    _: duplicate top element on the stack
    @: rotate top 3 elements on the stack
    _: duplicate top element on the stack
    n: print string representation
    \: swap top 2 elements on the stack
    +: add, concat
    }: Block end.
r: read token (whitespace-separated)
i: convert to integer
*: multiply, join, repeat, fold (reduce)
;: pop and discard
;: pop and discard
share|improve this answer
    
By the way, the number of strings is currently off by one; the last p should be a ;. You can get rid of the quotes around the output if you use n instead of p. Finally, 'a'b saves two bytes over "a""b". – Dennis 2 days ago

V, 18 bytes

ia
bkÀñyjGpgJkñdj

Try it online!

Or, the more readable version:

ia
b<esc>kÀñyjGpgJkñdj

Explanation:

ia
b<esc>          " Insert the starting text and escape back to normal mode
k               " Move up a line
 Àñ       ñ     " Arg1 times:
   yj           "   Yank the current line and the line below
     G          "   Move to the end of the buffer
      p         "   Paste what we just yanked
       gJ       "   Join these two lines
         k      "   Move up one line
           dj   " Delete the last two lines
share|improve this answer

MATL, 14 bytes

97c98ci2-:"yyh

Try it online!

97c     % Push 'a'
98c     % Push 'b'
i2-     % Input number. Subtract 2
:"      % Repeat that many times
  yy    %   Duplicate the top two elements
  h     %   Concatenate them
share|improve this answer

Python 2, 55 bytes

def f(n):m='a','b';exec'print m[-2];m+=m[-2]+m[-1],;'*n
share|improve this answer

Retina, 33 bytes

.+
$*
^11
a¶b
+`¶(.+?)1
¶$1¶$%`$1

Try it online!

Saved 10 (!) bytes thanks to @MartinEnder!

Explanation

Converts the input to unary, subtracts 2 and adds the a and the b, then recursively replaces the remaining 1s with the concatenation of the two previous strings.

share|improve this answer
    
Saved a few bytes by avoiding unnecessary captures: retina.tryitonline.net/… – Martin Ender yesterday
    
@MartinEnder Nice! Didn't quite see the power of $%` ! and that other capture was just bad planning... Amazing, thank you! – Dom Hastings 21 hours ago

Batch, 102 93 bytes

@set a=a
@set b=b
@for /l %%i in (2,1,%1)do @call:l
:l
@echo %a%
@set a=%b%&set b=%a%%b%

Fortunately variables are expanded for every line before assignments take effect, so I can set both a and b using their old values without needing a temporary. Edit: Saved 9 bytes thanks to @nephi12.

share|improve this answer
    
I was about to do this ;) By the way, you can save 8 bytes by removing the "exit/b" and starting your loop from 2: for /l %%i in (2,1,%1) etc.. – nephi12 2 days ago
    
One more (the newline) by putting the set commands on the same line @set a=a&set b=b like you did with the last one. though techncally they could all be on the same line... but that would be ugly... hmm... – nephi12 2 days ago

Swift 3, 76 Bytes

func f(_ n:Int,_ x:String="a",_ y:String="b"){if n>1{print(x);f(n-1,y,x+y)}}
share|improve this answer

Perl, 45 +1 = 46 bytes

+1 byte for -n flag

$a=a,$b=b;say($a),($a,$b)=($b,$a.$b)for 1..$_

Slight improvement over the existing 49-byte solution, but developed separately. The parentheses for say($a) are necessary because otherwise, it interprets $a,($a,$b)=($b,$a.$b) as the argument of say which outputs more junk than we need.

share|improve this answer

Perl, 48 bytes

47 bytes code + 1 for -n.

Simple approach. Try using an array slice originally $a[@a]="@a[-2,-1]" but that necessitates $"="" or similar :(. Save 1 byte thanks to @Dada!

@;=(a,b);$;[@;]=$;[-2].$;[-1]for 3..$_;say for@

Usage

perl -nE '@;=(a,b);$;[@;]=$;[-2].$;[-1]for 3..$_;say for@' <<< 5
a
b
ab
bab
abbab
share|improve this answer
    
You can save one byte by using @; instead of @a so you can omit the final semicolon (see what I mean?). (I know, one byte is pretty cheap but I didn't have any better idea..) – Dada yesterday
    
@Dada Yeah, I tried that, but it wound't compile on my machine, so I thought perhaps there's something odd going on with mine: perl -pe '@;=(a,b);$;[@;]=$;[-2].$;[-1]for 3..$_;say for@' <<< 5 syntax error at -e line 1, at EOF Execution of -e aborted due to compilation errors. but didn't think it'd be fair to add as an answer if I couldn't get it working! – Dom Hastings yesterday
    
Sure this isn't related to the -pe instead of -nE ? Any way, it works on mine, so it's probably related to your perl version or system... But trust me, I tested it and it works! ;) – Dada yesterday
    
@Dada I get the same with -nE as well (don't know where -pe came from! Must be Friday...) I'll update that when I get a mo! Thanks for sharing! – Dom Hastings yesterday

Stack my Golf, 63 bytes

Get my language here: https://github.com/cheertarts/Stack-My-Golf.

($1=(_(a))($2=(_(b))($2-f:1-f,)?)?)f\($1=(f)($1-p(\n),:f,)?)p\p

There is probably a shorter way but this is the most obvious.

share|improve this answer

Pyth, 17 bytes

J,\a\bjP.U=+Js>2J

A program that takes input of an integer and prints the result.

Try it online!

How it works

J,\a\bjP.U=+Js>2J  Program. Input: Q
 ,\a\b             Yield the two element list ['a', 'b']
J                  Assign to J
        .U         Reduce over [0, 1, 2, 3, ..., Q] (implicit input):
          =J+        J = J +
              >2J     the last two elements of J
             s        concatenated
       P           All of that except the last element
      j            Join on newlines
                   Implicitly print
share|improve this answer

Pyth - 16 15 bytes

A"ab" m=H+
~GHH

Try it online here.

share|improve this answer

APL, 30 bytes.

⎕IO must be 1.

{⎕←⍵}¨{⍵∊⍳2:⍵⌷'ab'⋄∊∇¨⍵-⌽⍳2}¨⍳
share|improve this answer

Mathematica, 49 bytes

f@1="a";f@2="b";f@n_:=f[n-2]<>f[n-1];g=f~Array~#&

Defines a function g taking the single numerical input; returns a list of strings. Straightforward recursive implementation, using the string-joining operator <>.

Mathematica, 56 bytes

NestList[#~StringReplace~{"a"->"b","b"->"ab"}&,"a",#-1]&

Unnamed function, same input/output format as above. This solution uses an alternate way to generate the strings: each string in the list is the result of simultaneously replacing, in the previous string, all occurrences of "a" with "b" and all occurrences of "b" with "ab".

share|improve this answer

PHP, 63 bytes

Recursive version:

function f($n,$a=a,$b=b){return $n--?"$a
".f($n,$b,$a.$b):'';}
share|improve this answer

Groovy, 79 Bytes

{println("a\nb");x=['a','b'];(it-2).times{println(y=x.sum());x[0]=x[1];x[1]=y}}
share|improve this answer

PHP, 53 bytes

for($a=b,$b=a;$argv[1]--;$a=($_=$b).$b=$a)echo$b.'
';
share|improve this answer

C, 168 bytes

#include<stdio.h>
int main(){char u[999]="a",v[999]="b",*a=u,*b=a+1,*c=v,*d=c+1,*e,i;for(i=0;i<5;++i){printf("%s\n",a);for(e=c;*e;*b++=*e++);e=a;a=c;c=e;e=b;b=d;d=e;}}

Two buffers (u & v) store the last two lines. The newest line (tracked with two pointers: start=c, end=d) is appended to the oldest one (start=a, end=b). Swap (a,b) and (c,d), and loop. Pay attention to buffer size before requesting too much lines. Not so short (as expected of a low-level language), but was fun to code.

share|improve this answer
    
You hardcoded the 5 but it should be user input – Karl Napf yesterday
    
Hmm... I do not see "user input" as a requirement in the puzzle... Following the same path as Perl, Python, C++, ... answers, replace "int main()" with "void f(int n)". – Phil yesterday
    
Given N (2 <= N), print N lines of the letter Fibonacci series like this (i.e. N = 5) – Karl Napf yesterday
    
Well, user input was a bad choice in term of words. I meant more like dynamic N and not fixed. Or the user might be somebody who uses your function/program. – Karl Napf yesterday

C++11, 89 98 bytes

+7 bytes for all lines, not only the last one. +2 bytes more for N being the number of lines printed, not some 0-based stuff.

#include<string>
using S=std::string;S f(int n,S a="a",S b="b"){return n-1?a+"\n"+f(n-1,b,a+b):a;}

Usage:

f(5)
share|improve this answer

PHP, 61 bytes

<?=$a=a;for($b=b;--$argv[1];$b=$c.$b){$c=$a;$a=$b;echo"
$b";}

come php 7.1 you can save 3 bytes by changing to:

<?=$a=a;for($b=b;--$argv[1];[$a,$b]=[$b,$a.$b])echo"
$b";

If a trailing new line is acceptable then:

for($b=b;$argv[1]--;$b=$c.$b){$c=$a?:a;$a=$b;echo"$c
";}

is only 56 bytes.

share|improve this answer
    
You do not have to use open tags unless there's a full program requirement :) – chocochaos yesterday
    
@chocochaos I know, but i'm using it to print the first a and <?= is shorter than echo. I can do better if a trailing new line is fine and will edit the answer to that effect. – user59178 yesterday

Ruby (1.9+) 46 bytes

a,b=?a,?b;ARGV[0].to_i.times{puts a;a,b=b,a+b}
share|improve this answer

Pyth - 14 bytes

(yeah, another pyth answer)

A<G2VQG=H+~GHH

Try it online

Explanation

A<G2              - take "ab" from the var G, dump "a" into G and "b" into H.
    VQ            - for N in range(Q)
      G           - print G
          ~GH     - like =GH but returns the previous G
         +   H    - concatenate the old G with the current H
       =H         - put that value back into H
share|improve this answer

Actually, 16 bytes

There might be a shorter way to duplicate the top two elements of the stack in Actually, but I'm not sure what that way is. Golfing suggestions welcome. Try it online!

'a'b,¬`2╟2αio`na

Ungolfing

'a'b     Push "a" then "b" to the stack.
,        Explicitly take input n.
¬        Push n-2.
`...`n   Run the following function n-2 times.
  2╟2α     Push a list that repeats the top two elements of the stack twice.
  i        Flatten that list to the stack. Stack: b, a, b, a, prev_iterations
  o        Append b to the end of a. Stack: ab, b, a, prev_iterations
a        Reverse the stack so that the strings will print in the correct order.
         Implicit print all of the elements in the stack.

A different approach

This is also 16 bytes. Try it online!

'a'b,¬`│ok╔Ri`na

Ungolfing

The main difference is the function in the middle, so I'll only ungolf that here.

`...`n   Run the following function n-2 times.
  │        Duplicate the stack.
  o        Append the last item to the end of the second-to-last item.
  k╔       Uniquify the stack by wrapping the stack in a list and then calling uniquify().
  Ri       Reverse that list before returning everything to the stack
            so that the last items are at TOS again.
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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