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