Monday Mini-Golf #1: Reverse Fibonacci Solver
Pyth, 23 bytes
AQWgHGA,-HGG)VvwHA,H+GH
Try it online: Demonstration or Test Suite
Quite unusual style of Pyth programming. Sometimes functional programming has its downsides.
Explanation:
AQWgHGA,-HGG)VvwHA,H+GH Q = input list of the two starting numbers
AQ G, H = Q (unpacking Q)
WgHG while H >= G:
A,-HGG G, H = [H - G, G]
) end while
vw read a number from input
V for N in range(^):
H print H
A,H+GH G, H = [H, G + H]
Retina, 65 54 bytes
+`(1*),\1(1*)
$2,$1
+`(1*)(,1*);1\B
$1$2$2$1;
^1*,|;1
<empty>
Here, <empty>
represents an empty trailing line. Run the code as a single file with the -s
flag.
The input format is
A,B;N
where the numbers are represented in unary. The output is a comma-separated list, also in unary. For instance:
8 13 10
would be
11111111,1111111111111;1111111111
and yield
,1,1,11,111,11111,11111111,1111111111111,111111111111111111111,1111111111111111111111111111111111
Explanation
+`(1*),\1(1*)
$2,$1
First, we reduce A
and B
to the 0th and -1st element. The +
tells Retina to keep repeating this regex substitution until either the regex stops matching or the substitution doesn't modify the string. The regex captures A
into group 1 with (1*)
, and then makes sure that B
is at least as big as A
while capturing B-A
with \1(1*)
into group 2. This ensures that this loop terminates once A>B
.
The substitution simply turns A,B
into B-A,A
by setting the match to $2,$1
.
+`(1*)(,1*);1\B
$1$2$2$1;
Now we've already got the first number of the required output in the string (as well as the one before it, which we'll need to get rid off later). This substitution now adds another number as the sum of the last two numbers while taking a 1
from N
. Because we already have one number we want this to happen only N-1
. We do this by ensuring with \B
that there is still at least ;11
at the end of the string. If we call the last two values of the sequence C
and D
, then the regex captures C
into group 1 and ,D
into group two. We write those back with $1$2
. Then we also write $2$1
which translates to ,D+C
. Note that we don't write back the single 1
we matched in N
, thereby decrementing it.
^1*,|;1
<empty>
Finally, we need to get rid of -1st element of the sequence, as well the leftover ;1
from N
, which we simply do by matching either of those and replacing it with the empty string.
Python 2, 93 87 67 61 60 bytes
i,j,l=input()
while j/i:i,j=j-i,i
exec"i,j=j,i+j;print i;"*l
Gets the input (as a literal python list [8,10,13]
)
Works out the 0th term
Then prints out the sequence of additions until the length has been reached