Hofstadter Q-sequence

25

2

Definition

  1. a(1) = 1
  2. a(2) = 1
  3. a(n) = a(n-a(n-1)) + a(n-a(n-2)) for n > 2 where n is an integer

Task

Given positive integer n, generate a(n).

Testcases

n  a(n)
1  1
2  1
3  2
4  3
5  3
6  4
7  5
8  5
9  6
10 6
11 6
12 8
13 8
14 8
15 10
16 9
17 10
18 11
19 11
20 12

Reference

Leaky Nun

Posted 2016-07-29T15:25:42.053

Reputation: 45 011

Related. – Leaky Nun – 2016-07-29T15:25:47.397

Related answer. – Martin Ender – 2016-07-29T15:45:46.003

1Can we return True in languages where it can be used as 1? – Dennis – 2016-07-29T15:53:13.013

1@Dennis If in that language true is equivalent to 1 then yes. – Leaky Nun – 2016-07-29T15:54:28.177

4Apart from the OEIS link it might be good to reference GEB where the sequence first appeared. – Martin Ender – 2016-07-29T16:16:55.873

Related – Luis Mendo – 2016-07-29T16:48:03.373

1Completing the list of GEB-related sequence challenges. – Martin Ender – 2016-07-29T17:39:46.057

You could probably translate the problem description into Haskell by only adding a few characters. – Carcigenicate – 2017-02-13T22:49:08.480

What input does it have to support up to? – Carcigenicate – 2017-02-13T22:51:57.133

That´s not Leonard Hofstadter, is it? – Titus – 2017-02-14T08:32:05.290

Answers

9

Retina, 84 83 79 74 bytes

Byte count assumes ISO 8859-1 encoding.

.+
$*;1¶1¶
+`;(?=(1)+¶(1)+)(?=(?<-1>(1+)¶)+)(?=(?<-2>(1+)¶)+)
$3$4¶
G3=`
1

Try it online! (The first line enables a linefeed-separated test suite.)

I'll have to golf this some more later.

Martin Ender

Posted 2016-07-29T15:25:42.053

Reputation: 184 808

9

Haskell, 35 33 bytes

a n|n<3=1|b<-a.(-)n=b(b 1)+b(b 2)

Defines a function a.

Anders Kaseorg

Posted 2016-07-29T15:25:42.053

Reputation: 29 242

2Nice trick with the bind! Wouldn't something like (b.b)1+(b.b)2 be shorter than the sum? – xnor – 2016-07-29T21:34:51.780

Why yes, thanks @xnor. – Anders Kaseorg – 2016-07-29T22:19:32.927

8

Julia, 29 bytes

!n=n<3||!(n-!~-n)+!(n-!~-~-n)

Try it online!

How it works

We redefine the unary operator ! for our purposes.

If n is 1 or 2, n<3 returns true and this is our return value.

If n larger than 2, n<3 returns false and the || branch gets executed. This is a straightforward implementation of the definition, where ~-n yields n - 1 and ~-~-n yields n - 2.

Dennis

Posted 2016-07-29T15:25:42.053

Reputation: 196 637

7

Sesos, 54 bytes

0000000: eefb5b 04f83a a75dc2 36f8d7 cf6dd0 af7b3b 3ef8d7  ..[..:.].6...m..{;>..
0000015: cfed12 f661f0 ae9d83 ee63e6 065df7 ce6183 af7383  ....a.....c..]..a..s.
000002a: 76ef3c 3f6383 7eff9c b9e37f                       v.<?c.~.....

Try it online

Disassembled

set numin
set numout
add 1
fwd 1
add 1
fwd 6
get
sub 1
jmp
    jmp
        sub 1
        fwd 1
        add 1
        rwd 1
    jnz
    fwd 1
    sub 1
    rwd 2
    add 2
    jmp
        rwd 4
        jmp
            sub 1
            fwd 3
            add 1
            rwd 3
        jnz
        fwd 4
        jmp
            sub 1
            rwd 3
            add 1
            rwd 1
            add 1
            fwd 4
        jnz
        rwd 3
        jmp
            sub 1
            fwd 3
            add 1
            rwd 3
        jnz
        fwd 4
        add 2
        jmp
            rwd 5
            jmp
                rwd 1
                jmp
                    sub 1
                    fwd 2
                    add 1
                    rwd 2
                jnz
                fwd 1
                jmp
                    sub 1
                    rwd 1
                    add 1
                    fwd 1
                jnz
                rwd 1
                sub 1
            jnz
            fwd 2
            jmp
                sub 1
                rwd 1
                add 1
                rwd 1
                add 1
                fwd 2
            jnz
            fwd 1
            jmp
                rwd 2
                jmp
                    sub 1
                    fwd 1
                    add 1
                    rwd 1
                jnz
                fwd 2
                jmp
                    sub 1
                    rwd 2
                    add 1
                    fwd 2
                jnz
                fwd 1
            jnz
            fwd 3
            sub 1
        jnz
        rwd 2
        jmp
            sub 1
            rwd 3
            add 1
            fwd 3
        jnz
        fwd 1
        sub 1
    jnz
    fwd 2
jnz
rwd 7
put

Or in Brainfuck notation:

+>+>>>>>>,-[[->+<]>-<<++[<<<<[->>>+<<<]>>>>[-<<<+<+>>>>]<<<[->>>+<<<]>>>>++[<<<<<[<
[->>+<<]>[-<+>]<-]>>[-<+<+>>]>[<<[->+<]>>[-<<+>>]>]>>>-]<<[-<<<+>>>]>-]>>]<<<<<<<.

Anders Kaseorg

Posted 2016-07-29T15:25:42.053

Reputation: 29 242

6

C, 43 42 bytes

Saved 1 byte thanks to @Dennis

Every answer is the same, I must do something different!

Try it online!

a(n){return n<3?:a(n-a(n-2))+a(n---a(n));}

Explanation: it's basically a(n-a(n-2))+a(n-a(n-1)) but with swaggyundefinedbehavior (works on my phone (gcc) and ideone).

betseg

Posted 2016-07-29T15:25:42.053

Reputation: 8 493

4>

  • You should also mention the compiler; your "swag" is undefined behavior. 2. With GCC, you don't need the 1 between ? and :.
  • < – Dennis – 2016-07-29T18:00:56.360

    @Dennis Interestingly, that same formulation works in my iterative PowerShell answer... $b+=$b[$_-$b[$_-2]]+$b[$_---$b[$_]] – AdmBorkBork – 2016-07-29T20:28:30.900

    @TimmyD some compilers may compile the a(n) before the n--, and there isn't a standart (or defined) behavior for that. Thus, undefined behavior. – betseg – 2016-07-29T20:56:08.080

    @betseg Yep, I agree. Just pointing out that it's not necessarily unique to C. – AdmBorkBork – 2016-07-29T21:01:41.027

    @TimmyD Oh I misunderstood that. I just wanted to change the function that everybody uses, so mine would be different and swaggy :D – betseg – 2016-07-29T21:16:15.183

    …If you just want to be different, you could use ~-n == n-1 rather than relying on undefined behavior. – Anders Kaseorg – 2016-07-29T21:18:36.817

    5

    Mathematica, 36 bytes

    Byte count assumes ISO 8859-1 encoding and Mathematica's $CharacterEncoding set to WindowsANSI (the default on Windows; other settings might work as well, but some like UTF-8 definitely don't).

    ±1=±2=1
    ±n_:=±(n-±(n-1))+±(n-±(n-2))
    

    Defines ± as a unary operator.

    I tried getting rid of the duplication, but ended up with the same byte count:

    ±1=±2=1
    ±n_:=Tr[±(n-±(n-#))&/@{1,2}]
    

    Martin Ender

    Posted 2016-07-29T15:25:42.053

    Reputation: 184 808

    I may give you a +200 bounty if you do it in Retina – Leaky Nun – 2016-07-29T15:44:26.723

    @LeakyNun okay? :) – Martin Ender – 2016-07-29T16:13:44.623

    Two days later. – Leaky Nun – 2016-07-29T16:18:02.490

    @LeakyNun Soon you're going to have no rep left if you give out bounties so easily. – mbomb007 – 2016-07-29T19:58:49.853

    Let us continue this discussion in chat.

    – LegionMammal978 – 2016-07-30T14:41:48.837

    4

    Jelly, 15 14 bytes

    2Rạ⁸߀$⁺Sµ1>?2
    

    Try it online! or verify all test cases (takes a few seconds).

    How it works

    2Rạ⁸߀$⁺Sµ1>?2  Main link. Argument: n (integer)
    
    2R              Yield [1, 2].
          $         Combine the previous three links into a monadic chain.
       ⁸                Yield n.
      ạ                 Take the absolute difference of the return value and n.
        ߀              Recursively call the main link on each result.
           ⁺            Duplicate the chain.
                        The first copy maps [1, 2] to [a(n - 1), a(n - 2)].
                        The second copy maps [a(n - 1), a(n - 2)] to
                        [a(n - a(n - 1)), a(n - a(n - 2))].
            S           Take the sum.
             µ          Combine all links to the left into a chain.
                ?       If...
               > 2          n is greater than 2, call the chain.
              1         Else, return 1.
    

    Dennis

    Posted 2016-07-29T15:25:42.053

    Reputation: 196 637

    I may give you a +400 bounty if you do it in Sesos. – Leaky Nun – 2016-07-29T15:50:05.317

    @LeakyNun There seems to be an Sesos answer. It came out one day after your comment. – Yytsi – 2017-02-14T05:48:45.693

    4

    Jelly, 14 12 11 bytes

    ịḣ2S;
    1Ç⁸¡2ị
    

    This is an iterative approach.

    Try it online! or verify all test cases.

    How it works

    1Ç¡2ị   Main link. Argument: n
    
    1       Set the return value to 1.
     Ç¡     Call the helper link n times, updating the return value after each call.
       2ị   Extract the second element of the resulting array.
    
    
    ịḣ2S;   Helper link. Argument: A (array)
    
    ị       At-index; retrieve the elements of A at the values of A.
     ḣ2     Head 2; extract the first two results.
        S   Take the sum of the result.
         ;  Prepend the sum to A.
    

    Dennis

    Posted 2016-07-29T15:25:42.053

    Reputation: 196 637

    3

    Python, 45 40 bytes

    a=lambda n:n<3or a(n-a(n-1))+a(n-a(n-2))
    

    Simple naïve interpretation of the challenge.

    Saved 5 bytes thanks to @LeakyNun!

    Copper

    Posted 2016-07-29T15:25:42.053

    Reputation: 3 684

    3

    Haskell, 39 37 Bytes

    h n|n<3=1|n>2=h(n-h(n-1))+h(n-h(n-2))
    

    exactly like described in the challenge, using guards

    KarlKastor

    Posted 2016-07-29T15:25:42.053

    Reputation: 2 352

    Sorry, I didn't saw your solution before posting my (identical) haskell solution. However isn't the byte count 38 as the new-line has to be taken into account? – Laikoni – 2016-07-29T15:49:42.637

    And the guard has to be n<3 for h 2 to be 1. – Laikoni – 2016-07-29T15:58:33.560

    @Laikoni It's 37 according to Pythons len feature with a multiline (""") string, unless you count newline as two bytes. Yeah, I noticed the other thing it's fixed now. – KarlKastor – 2016-07-29T16:05:15.593

    TIL notepad++ counts newline as two character. – Laikoni – 2016-07-29T16:18:19.763

    @Laikoni got rid of the newline it's indisputably 37 bytes now. – KarlKastor – 2016-07-29T16:18:53.247

    @Laikoni In windows a newline is quite often represented as \r\n, while \n is sufficient. – flawr – 2016-07-29T20:39:58.000

    @flawr Good to know. – Laikoni – 2016-07-30T08:12:33.710

    I thought we're allowed to count the newlines as singles always.

    – Will Ness – 2016-08-01T13:52:26.433

    3

    C#, 51 44 bytes

    int a(int n)=>n<3?1:a(n-a(n-1))+a(n-a(n-2));
    

    i wonder if this can be shortened by making it anonymous thanks pinkfloydx33!

    downrep_nation

    Posted 2016-07-29T15:25:42.053

    Reputation: 1 152

    1c# 6 expression bodied function int a(int n)=>n<3?1:a(n-a(n-a))+a(n-a(n-2)); – pinkfloydx33 – 2016-07-29T18:57:08.033

    Seems I typod while typing that on my phone. The inner most -a in the first set of parens should be -1 – pinkfloydx33 – 2016-07-30T10:16:30.247

    I didn't notice it either, ill fix it rq – downrep_nation – 2016-07-30T10:27:03.890

    3

    R, 50 bytes

    a=function(n)ifelse(n<3,1,a(n-a(n-1))+a(n-a(n-2)))
    

    Usage:

    > a(1)
      1
    > a(20)
      12
    

    DSkoog

    Posted 2016-07-29T15:25:42.053

    Reputation: 560

    3

    CJam, 19 18 bytes

    XXri{_($2$$+}*]-3=
    

    Try it online!

    Uses the iterative approach.

    Martin Ender

    Posted 2016-07-29T15:25:42.053

    Reputation: 184 808

    3

    JavaScript (ES6), 45 Bytes 34 Bytes

    A recursive solution in ES6. Any golfing tips much appreciated.

    a=n=>n>2?a(n-a(n-1))+a(n-a(n-2)):1
    

    Thank you to /u/ismillo for shortening even further.

    BugHunterUK

    Posted 2016-07-29T15:25:42.053

    Reputation: 131

    2

    Ruby, 36 bytes

    A direct implementation. Any golfing suggestions are welcome.

    a=->n{n<3?1:a[n-a[n-1]]+a[n-a[n-2]]}
    

    Sherlock9

    Posted 2016-07-29T15:25:42.053

    Reputation: 11 664

    Afaik, you can get rid of the a=. If you post it here, it suffices when your code starts with the ->. It counts as an anonymous function then. – Seims – 2016-08-03T10:08:00.623

    @Seims Unfortunately, as the function calls itself with a[n-1] and such, the function needs to be named. – Sherlock9 – 2016-08-03T11:04:37.423

    2

    Golfscript, 29 bytes

    ~[1 1]{..0=(=\..1=(=@+\+}@*2=
    

    Try it online!

    Leaky Nun

    Posted 2016-07-29T15:25:42.053

    Reputation: 45 011

    2

    Java 7, 68 61 51 bytes

    17 saved thanks to Leaky Nun.

    int a(int n){return n<3?1:a(n-a(n-1))+a(n-a(n-2));}
    

    Justin

    Posted 2016-07-29T15:25:42.053

    Reputation: 417

    Welcome to PPCG! – AdmBorkBork – 2016-07-29T17:45:24.967

    Welcome to PPCG! You might like Tips for Golfing in Java. An alternate form would be: int a(int n){return n<3?1:a(n-a(n-2))+a(n---a(n));}, but unfortunately it uses the same amount of bytes as the answer you already have.. Also, I would specify that your answer is in Java 7, since the Java 8 answer would be shorter: n->return n<3?1:a(n-a(n-1))+a(n-a(n-2)) (39 bytes).

    – Kevin Cruijssen – 2016-08-03T12:44:10.800

    Thanks for the welcomes guys, and thanks for the tip on Java8 - I didn't realize lambdas were allowed like that - although they're allowed like that in Python, so I guess I just never thought about it. Does the lambda need a semi-colon? – Justin – 2016-08-03T12:46:22.400

    @JustinTervay I don't use Java 8 a lot, but from what I've heard the semi-colon isn't counted on single-line expressions, according to a comment by @DavidConrad and @CAD97 in one of my own Java answers.

    – Kevin Cruijssen – 2016-08-03T12:50:46.223

    2

    05AB1E, 29 bytes

    An iterative solution.

    XˆXˆÍL>v¯¤ys-è¯y¯yÍè-è+ˆ}¯¹<è
    

    Try it online

    Emigna

    Posted 2016-07-29T15:25:42.053

    Reputation: 50 798

    2

    APL, 20 bytes

    {⍵≤2:1⋄+/∇¨⍵-∇¨⍵-⍳2}
    

    Explanation:

    {⍵≤2:1⋄+/∇¨⍵-∇¨⍵-⍳2}
     ⍵≤2:1               If argument is 2 or less, return 1
          ⋄              Otherwise:
                   ⍵-⍳2  Subtract [1, 2] from the argument
                 ∇¨      Recursive call on both
               ⍵-        Subtract both results from the argument     
             ∇¨          Recursive call on both again
           +/            Sum          
    

    marinus

    Posted 2016-07-29T15:25:42.053

    Reputation: 30 224

    2

    VBA Excel 87 bytes

    Non-recursive, since I want this to work for n=100000, say:

    Function A(N):ReDim B(N):For i=3 To N:B(i)=B(i-B(i-1)-1)+B(i-B(i-2)-1)+1:Next:A=B(N)+1
    

    ... and press return (byte #87) at the end of the line to get the End Function statement for "free". Note that B values are offset by -1 to avoid initializing for n=1 and 2.

    Invoke in spreadsheet as normal, eg =A(100000) to get 48157

    The recursive version, 61 bytes,

    Function Y(N):If N<3 Then Y=1 Else Y=Y(N-Y(N-1))+Y(N-Y(N-2))
    

    starts to get unreasonably slow for n>30, and couldn't be said to work at all for n>40.

    Joffan

    Posted 2016-07-29T15:25:42.053

    Reputation: 832

    We don't care about performance. We care about code length. You should move your shorter solution to the top of your answer. – mbomb007 – 2016-08-01T16:36:49.643

    1@mbomb007 Since I'm nowhere near winning the golf, I'll make my own choices on what constitutes a working program. Not able to handle even single byte integers is not good enough as far as I'm concerned, when there is a solution which can do so easily. – Joffan – 2016-08-01T16:57:03.800

    2

    Oasis, 9 7 5 bytes (non-competing)

    Non-competing, since the language postdates the challenge. Thanks to Kenny Lau for saving 4 bytes. Code:

    ece+V
    

    Expanded form (V is short for 11):

    a(n) = ece+
    a(0) = 1
    a(1) = 1
    

    Code:

    e        # Stack is empty, so a(n - 1) is used, and it calculates a(n - a(n - 1))
     c       # Calculate a(n - 2)
      e      # Calculate a(n - a(n - 2))
       +     # Add up
    

    Try it online!. Calculates n = 1000 in 0.1 seconds.

    Adnan

    Posted 2016-07-29T15:25:42.053

    Reputation: 41 965

    1

    PowerShell v2+, 85 79 69 bytes

    param($n)$b=1,1;2..$n|%{$b+=$b[$_-$b[$_-1]]+$b[$_-$b[$_-2]]};$b[$n-1]
    

    Takes input $n, sets $b to be an array of @(1, 1), then enters a loop from 2 .. $n. Each iteration we tack onto $b the latest calculation in the sequence with a simple += and the definition of the sequence. We then output the appropriate number from $b (with a -1 because arrays in PowerShell are zero-indexed). This works if $n is 1 or 2 because both of those values are pre-populated into the lower indices of $b from the start, so even if the loop tacks on junk, it's ignored anyway.


    Recursive solution 78 76 bytes

    $a={param($k)if($k-lt3){1}else{(&$a($k-(&$a($k-1))))+(&$a($k-(&$a($k-2))))}}
    

    First time I've used the equivalent of a lambda as the answer, as usually an iterative solution is shorter (as you can see from all the nested parens). But, in this case, the nested parens are almost duplicated in the iterative solution with the nested array calls, so the recursive solution is shorter. Nope, the iterative solution is indeed shorter (see above).

    Call it via the execution-operator, like &$a 20. Just a straight-up recursive call.

    AdmBorkBork

    Posted 2016-07-29T15:25:42.053

    Reputation: 41 581

    1

    Maple, 43 41 bytes

    a:=n->`if`(n>2,a(n-a(n-1))+a(n-a(n-2)),1)
    

    Usage:

    > a(1);
      1
    > a(20);
      12
    

    This problem is certainly a good candidate for memoization. Using option cache, the run times are cut down significantly:

    aC := proc(n) 
          option cache; 
          ifelse( n > 2, aC( n - aC(n-1) ) + aC( n - aC(n-2) ), 1 ); 
    end proc:
    

    This can be seen using:

    CodeTools:-Usage( aC(50) );
    

    DSkoog

    Posted 2016-07-29T15:25:42.053

    Reputation: 560

    1

    JavaScript (ES6), 66 bytes

    n=>[...Array(n+1)].reduce((p,_,i,a)=>a[i]=i<3||a[i-p]+a[i-a[i-2]])
    

    Non-recursive version for speed; recursive version is probably shorter but I'll leave it for someone else to write. I always like it when I get to use reduce. Note: 1 byte saved by returning true (which casts to 1 when used in an integer context) for of a(1) and a(2).

    Neil

    Posted 2016-07-29T15:25:42.053

    Reputation: 95 035

    1

    Pyth, 16 bytes

    L|<b3smy-bytdtBb
    
    L                  def y(b):
     |<b3                b < 3 or …
          m      tBb       map for d in [b - 1, b]:
           y-bytd            y(b - y(d - 1))
         s                 sum
    

    Defines a function y.

    Try it online (added yMS20 to print the first 20 values)

    Anders Kaseorg

    Posted 2016-07-29T15:25:42.053

    Reputation: 29 242

    1

    Forth, 76 bytes

    I finally got it working!

    : Q recursive dup dup 3 < if - 1+ else 2dup 2 - Q - Q -rot 1- Q - Q + then ;
    

    Try it online

    Explanation:

    : Q recursive                           \ Define a recursive function Q
        dup dup 3 <                         \ I moved a dup here to golf 2 bytes
        if                                  \ If n < 3, return 1
            - 1                             \ Golf: n-n is zero, add one. Same as 2drop 1+
        else
            2dup 2 - Q - Q                  \ Copy n until 4 on stack, find Q(n-Q(n-2))
            -rot                            \ Move the result below 2 copies of n
            1- Q - Q +                      \ Find Q(n-Q(n-2)), then add to previous ^
        then ;
    

    Try it online (slightly un-golfed from above)

    Unfortunately, mutual recursion is a bit too wordy to use for golfing.

    mbomb007

    Posted 2016-07-29T15:25:42.053

    Reputation: 21 944

    0

    Clojure, 86 bytes

    (defn a[n](cond(< 0 n 3)1 1(+(a(- n(a(dec n))))(a(- n(a(- n 2)))))))
    

    Very literal.

    (defn a [n]
      (cond
        (< 0 n 3) 1 ; Return 1 if n is 1 or 2
        :else (+ (a (- n (a (dec n)))) ; Else, recurse 4 times and do some math
                 (a (- n (a (- n 2)))))))
    
    (doseq [n (range 1 21)]
      (println n (a n)))
    
    1 1
    2 1
    3 2
    4 3
    5 3
    6 4
    7 5
    8 5
    9 6
    10 6
    11 6
    12 8
    13 8
    14 8
    15 10
    16 9
    17 10
    18 11
    19 11
    20 12
    

    Carcigenicate

    Posted 2016-07-29T15:25:42.053

    Reputation: 3 295

    I think you can get rid of the 0 in the < statement, because the challenge specs state that the input is a positive integer. – clismique – 2017-02-16T09:50:52.827

    @Qwerp-Derp ohh, thanks. I'll fix that when I get on my laptop. – Carcigenicate – 2017-02-16T11:21:44.607

    0

    Lithp, 70 bytes (non-competing)

    (def a #N::((if(<= N 2)(1)((+(a(- N(a(- N 1))))(a(- N(a(- N 2)))))))))
    

    Warning: incredibly slow. Very recursive. Implements the exact algorithm in challenge.

    Non-competing because language is newer than challenge.

    Try it online!

    An alternate solution that is much faster, using caching of results:

    Lithp, 166 bytes

    ((def a #N::((if(<= N 2)(1)((+(b(- N(b(- N 1))))(b(- N(b(- N 2)))))))))(var C(dict))
     (def b(scope #N::((if(!(dict-present C N))((dict-set C N(a N))))(dict-get C N)))))
    

    Try it online!

    Andrakis

    Posted 2016-07-29T15:25:42.053

    Reputation: 361

    Just curious, why did you make functions like (def a #N::(+ N 1)), where a is a successor? – clismique – 2017-02-16T09:27:58.517

    I'm sorry I don't quite understand you. What do you mean by successor? – Andrakis – 2017-02-16T09:39:41.657

    A successor function is a function that increments a number, but that's besides the point. I'm just curious about the way to define functions in Lithp - why did you choose to do #arg:: when defining functions? I haven't really seen that done in a Lisp-like before. – clismique – 2017-02-16T09:40:56.053

    Ah, thank you. Firstly, lowercase names are atoms. Names beginning with an uppercase are variables. It follow Erlang's design in this way. Next, I struggled to read most Lisp code, though I loved the elegance of it. The way I've designed my syntax is to be easy to read, and an anonymous function (format: #[Args,...] :: ( calls .. )) was easy to see what arguments are being passed. It's only sort-of Lisp-like really. I like the elegance of the braces, and it's easy to parse. – Andrakis – 2017-02-16T09:47:07.207

    1Oh, that's how it works, thanks! I was looking at the arguments and it seemed a bit weird, but now that you've explained it I can understand why it's like that. – clismique – 2017-02-16T09:49:17.897

    0

    PHP, 56 bytes

    function q($n){return$n<3?:q($n-q($n-1))+q($n-q($n-2));}
    

    recursive function; requires PHP 5.6 or later (or replace ?: with ?1:).

    Titus

    Posted 2016-07-29T15:25:42.053

    Reputation: 13 814

    0

    J, 29 28 bytes

    1:`(+&$:/@:-$:@-&1 2)@.(2&<)
    

    Uses the recursive definition.

    Usage

    Extra commands are used for formatting multiple input/output.

       f =: 1:`(+&$:/@:-$:@-&1 2)@.(2&<)
       (,:f"0) >: i. 20
    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
    1 1 2 3 3 4 5 5 6  6  6  8  8  8 10  9 10 11 11 12
    

    Explanation

    1:`(+&$:/@:-$:@-&1 2)@.(2&<)  Input: n
                            2&<   If n < 2
    1:                              Return 1
                                  Else
                   -&1 2            Subtract [1, 2] from n to get [n-1, n-2]
                $:@                 Call recursively on n-1 and n-2
               -                    Subtract each of the results from n
            /@:                     Reduce using
          $:                          A recursive call on each
        +&                            Then summation
                                    Return that value as the result
    

    miles

    Posted 2016-07-29T15:25:42.053

    Reputation: 15 654

    0

    dc, 62 bytes

    ?si2sa1dd2:a:a[la1+dsadd1-;a-;alad2-;a-;a+r:ali;a0=A]dsAxli;af
    

    This solution makes use of arrays and recursion.

    ?si          # Take input from stdin and store it in register `i'
    2sa          # Initialise register `a' with 2, since we'll be putting in the first
                 #   two values in the sequence
    1dd2         # Stack contents, top-down: 2 1 1 1
    :a           # Pop index, then pop value: Store 1 in a[2]
    :a           # Ditto:                     Store 1 in a[1]
    [            # Open macro definition
     la 1+ dsa   # Simple counter mechanism: Increment a and keep a copy on stack
    
    # The STACK-TRACKER(tm): Top of stack will be at top of each column, under the
    #   dashed line. Read commands from left to right, wrapping around to next line.
    #   This will be iteration number n.
      dd   1-    ;a       -          ;a            la            d          
    #-----------------------------------------------------------------------
    # n    n-1   a[n-1]   n-a[n-1]   a[n-a[n-1]]   n             n          
    # n    n     n        n          n             a[n-a[n-1]]   n          
    # n    n     n                                 n             a[n-a[n-1]]
    #                                                            n          
    #                                                                       
    
      2-            ;a            -             ;a            +      r    :a
    #-----------------------------------------------------------------------
    # n-2           a[n-2]        n-a[n-2]      a[n-a[n-2]]   a[n]   n      
    # n             n             a[n-a[n-1]]   a[n-a[n-1]]   n      a[n]   
    # a[n-a[n-1]]   a[n-a[n-1]]   n             n                           
    # n             n                                                       
    
     li;a        # Load index of target element, and fetch that element's current value
                 #    Uninitialised values are zero
     0=A         # If a[i]==0, execute A to compute next term
    ]dsAx        # Close macro definition, store on `A' and execute
    li;a         # When we've got enough terms, load target index and push value
    f            # Dump stack (a[i]) to stdout
    

    Joe

    Posted 2016-07-29T15:25:42.053

    Reputation: 895

    In conclusion, if anyone is building an IDE for dc, let me know! – Joe – 2016-07-29T22:52:07.587

    0

    Erlang, 46 bytes

    f(N)when N<3->1;f(N)->f(N-f(N-1))+f(N-f(N-2)).
    

    c.P.u1

    Posted 2016-07-29T15:25:42.053

    Reputation: 1 049

    0

    Lua, 59 bytes

    function a(n)return n<3 and 1 or a(n-a(n-1))+a(n-a(n-2))end
    

    brianush1

    Posted 2016-07-29T15:25:42.053

    Reputation: 300

    0

    Racket, 63 bytes

    (define(a n)(if(> n 2)(for/sum([m'(1 2)])(a(- n(a(- n m)))))1))
    

    Winny

    Posted 2016-07-29T15:25:42.053

    Reputation: 1 120

    0

    ><>, 65+2 = 67 bytes

    ^n;
    .+]{0$
    v1}\
    v2} @2->1[
    v3}>-  /:::1-1[
    >4}:2)?^~~1]{0$.
    /0$1[
    

    Input neds to be present on the stack at program start, so +2 bytes for the -v flag. Try it online!

    More ridiculously slow recursive madness. Test case for 20 on TIO takes 20.5 seconds, so use larger inputs at your own risk

    Sok

    Posted 2016-07-29T15:25:42.053

    Reputation: 5 592