Zagraj w golfa w niestandardowej sekwencji Fibonacciego


25

Ciąg Fibonacciego jest dość dobrze znana rzecz tutaj. Cholera, ma nawet swój własny tag. Mimo to z pewnością lubimy trzymać się naszych korzeni 1, 1, ...(a może tak 0, 1, ...? Być może nigdy się nie dowiemy ...). W tym wyzwaniu zasady są takie same, ale zamiast dostać ten nelement w sekwencji Fibonacciego, otrzymasz ten nelement w sekwencji Fibonacciego od x, y, ....

Wkład

Trzy liczby całkowite, w dowolnej kolejności. njest indeksem (indeksowanym 0 lub 1) terminu w sekwencji dla danych wyjściowych. xi ysą pierwszymi dwoma elementami w sekwencji Fibonacciego w bieżącym programie.

Wydajność

nP określenie w ciągu Fibonacciego wychodząc z x, y.

Przypadki testowe

(0-indeksowane)

n   x     y     out
5   0     0     0
6   0     1     8
6   1     1     13
2   5     5     10
10  2     2     178
3   3     10    23
13  2308  4261  1325165
0   0     1     0
1   0     1     1

(1-indeksowany)

n   x     y     out
6   0     0     0
7   0     1     8
7   1     1     13
3   5     5     10
11  2     2     178
4   3     10    23
14  2308  4261  1325165
1   0     1     0
2   0     1     1

Ostrzeżenia

Załóżmy 0 <= x <= y.

Zwróć uwagę na kolejność wprowadzania (musi być stała).


Czy możemy wziąć listę jako dane wejściowe?
— Business Cat

@ BusinessCat masz na myśli [1, 2, 3]? Tak. Cokolwiek potrzebujesz, aby zaakceptować 3 liczby całkowite.
— Stephen

@StephenS Co powiesz na wprowadzenie danych, ponieważ n,[x,y]gdzie njest liczba i xczy yliczby są na liście? Prawdopodobnie jest to jednak zbyt elastyczne;)
— Tom

1
@ CAD97 Dodam je, zapomniałem o nich :)
— Stephen

Odpowiedzi:


15

Galaretka , 3 bajty

+¡ạ

Takes x, y, and n (0-indexed) as separate command-line arguments, in that order.

Try it online!

How it works

+¡ạ  Main link. Left argument: x. Right argument: y. Third argument: n

  ạ  Yield abs(x - y) = y - x, the (-1)-th value of the Lucas sequence.
+¡   Add the quicklink's left and right argument (initially x and y-x), replacing
     the right argument with the left one and the left argument with the result.
     Do this n times and return the final value of the left argument.

11

CJam, 14 9 bytes

l~{_@+}*;

Try it online!

Input format is "x y n". I'm still a noob at this, so I'm 100% sure there are better ways to do this, but please instead of telling me "do this" try to only give me hints so that I can find the answer myself and get better. Thanks!


1
ririri can be shortened to 2 bytes. fI can be shortened to 1 byte.
— Dennis

6
Welcome to PPCG!
— Martin Ender

@Dennis improved! Thank you! And thanks for the welcome.
— FrodCube


9

JavaScript (ES6), 27 26 bytes

Nothing fancy here, just a standard JS Fibonacci function with the initial values of 0 & 1 removed.

n=>g=(x,y)=>n--?g(y,x+y):x

Try it

f=
n=>g=(x,y)=>n--?g(y,x+y):x
o.value=f(i.value=13)(j.value=2308,k.value=4261)
oninput=_=>o.value=f(+i.value)(+j.value,+k.value)
*{font-family:sans-serif;}
input{margin:0 5px 0 0;width:50px;}
#o{width:75px;}
<label for=i>n: </label><input id=i type=number><label for=j>x: </label><input id=j type=number><label for=k>y: </label><input id=k type=number><label for=o>= </label><input id=o>



5

Haskell, 30 bytes

x#y=(f!!)where f=x:scanl(+)y f

Try it online! 0-indexed. Use as (x#y)n, e.g. (0#1)5 for the fifth element of the original sequence.

The most likely shortest way to get the Fibonacci sequence in Haskell is f=0:scanl(+)1f, which defines an infinite list f=[0,1,1,2,3,5,8,...] containing the sequence. Replacing 0 and 1 with arguments x and y yields the custom sequence. (f!!) is then a function returning the nth element of f.




4

Brain-Flak, 38 bytes

{({}[()]<(({}<>)<>{}<(<>{}<>)>)>)}{}{}

Try it online!

{({}[()]<                      >)}     # For n .. 0
         (({}<>)<>            )        # Copy TOS to the other stack and add it to...
                  {}                   # The second value
                    <(<>{}<>)>         # Copy what was TOS back
                                  {}{} # Pop the counter and the n+1th result


3

Jelly, 6 bytes

;SḊµ¡I

Try it online!

Explanation

   µ¡  - repeat n times (computes the n+1th and n+2th element):
 S     -  take the sum of the elements of the previous iteration (starting at (x,y))
;      -  append to the end of the previous iteration
  Ḋ    -  remove the first element
     I - Take the difference of the n+1th and n+2th to get the n-th.

3

TAESGL, 4 bytes

ēB)Ė

1-indexed

Interpreter

Explanation

Input taken as n,[x,y]

 ēB)Ė
AēB)     get implicit input "A" Fibonacci numbers where "B" is [x,y]
    Ė    pop the last item in the array

3

Prolog (SWI), 77 bytes

f(N,Y,Z):-M is N-1,f(M,X,Y),Z is X+Y.
l(N,A,B,X):-asserta(f(0,A,B)),f(N,X,_).

Try it online!

Started off golfing Leaky Nun's answer and arrived at something completely different.

This one has a rule for (Nᵗʰ, (N+1)ᵗʰ) in terms of ((N-1)ᵗʰ, Nᵗʰ) and uses database management to assert 0ᵗʰ and 1ˢᵗ elements at runtime.

f(N,X,Y) means Nᵗʰ element is X and (N+1)ᵗʰ element is Y.



2

Braingolf, 15 bytes

VR<2-M[R!+v]R_;

_; is no longer needed on the latest version of Braingolf, however that's as of ~5 minutes ago, so would be non-competing.



2

MATL, 7 bytes

:"wy+]x

Output is 0-based.

Try it at MATL Online!

Explanation

Let the inputs be denoted n (index), a, b (initial terms).

:"     % Implicitly input n. Do this n times
       %   At this point in each iteration, the stack contains the two most
       %   recently computed terms of the sequence, say s, t. In the first
       %   iteration the stack is empty, but a, b will be implicitly input
       %   by the next statement
  w    %   Swap. The stack contains t, s
  y    %   Duplicate from below. The stack contains t, s, t
  +    %   Add. The stack contains t, s+t. These are now the new two most
       %   recently comnputed terms
]      % End
x      % Delete (we have computed one term too many). Implicitly display

2

R, 39 bytes

f=function(x,y,n)'if'(n,f(y,x+y,n-1),x)

A simple recursive function. Funnily enough this is shorter than anything I can come up with for the regular Fibonacci sequence (without built-ins), because this doesn't have to assign 1 to both x and y =P

Calculates n+1 numbers of the sequence, including the initial values. Each recursion is calculates with n-1 and stopped when n==0. The lowest of the two numbers is then returned, giving back the n-th value.



2

PHP>=7.1, 55 Bytes

for([,$n,$x,$y]=$argv;$n--;$x=$y,$y=$t)$t=$x+$y;echo$x;

Online Version

PHP>=7.1, 73 Bytes

for([,$n,$x,$y]=$argv,$r=[$x,$y];$i<$n;)$r[]=$r[+$i]+$r[++$i];echo$r[$n];

Online Version


1
Taking advantage of strange PHP's evaluation order: $y=+$x+$x=$y. Also, you can use just $n-- instead of $i++<$n.
— user63956

2

Common Lisp, 49 Bytes, 0-indexed

(defun fib(n x y)(if(= 0 n)x(fib(1- n)y(+ x y))))

I'm a Lisp noob so any tips would be appreciated ;)

Explanation:

(defun fib(n x y)                                  | Define a function taking 3 arguments
                 (if(= 0 n)x                       | If n = 0, return x
                            (fib(1- n)y(+ x y))))  | Otherwise, call fib with n-1, y, and x+y


2

br**nfuck, 39 29 bytes

Thanks to @JoKing for -10!

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

TIO won't work particularly well for this (or for any BF solution to a problem involving numbers). I strongly suggest @Timwi's EsotericIDE (or implementing BF yourself).

Takes x, then y, then n. 0-indexed. Assumes an unbounded or wrapping tape.

Explanation

,<,<,            Take inputs. Tape: [n, y, x]
[                While n:
  > [->+>+<<]      Add y to x, copying it to the next cell along as well. Tape: [n, 0, x+y, y]
  < [>+<-]         Move n over. Tape: [0, n, x+y, y]
  >-               Decrement n.
] >>.            End loop. Print cell 2 to the right (x for n == 0).

Why do you bother moving x and y when you can just move n? Try It Online
— Jo King

@JoKing Considered that (but longer on my own), but it doesn't quite work, unless OP allows "-1-indexing".
— Khuldraeseth na'Barya

Oh, just add a > to the end or swap x and y order
— Jo King

@JoKing My palm hit my face quite hard just now. Thanks!
— Khuldraeseth na'Barya

Why did you bother to censor "brain" but not the second word in the programming language's name?
— MilkyWay90


1

05AB1E, 9 bytes

`©GDŠ+}®@

Try it online!

Explanation

`           # split inputs as separate to stack
 ©          # store n in register
  G         # n-1 times do
   D        # duplicate top of stack
    Š       # move down 2 places on stack
     +      # add top 2 values of stack
      }     # end loop
       ®@   # get the value nth value from the bottom of stack



1

Axiom, 88 57 bytes

f(k,x,y)==(repeat(k<=0=>break;c:=y;y:=x+y;x:=c;k:=k-1);x)

this would pass the test proposed (0 indexed)

(14) -> f(5,0,0)
   (14)  0
                                                 Type: NonNegativeInteger
(15) -> f(6,0,1)
   (15)  8
                                                    Type: PositiveInteger
(16) -> f(2,5,5)
   (16)  10
                                                    Type: PositiveInteger
(17) -> f(10,2,2)
   (17)  178
                                                    Type: PositiveInteger
(18) -> f(3,3,10)
   (18)  23
                                                    Type: PositiveInteger
(19) -> f(13,2308,4261)
   (19)  1325165
                                                    Type: PositiveInteger


Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.