Stewie's sequence: + * - / + * - /
Haskell, 69 68 64 bytes
x#n=take n$x++zipWith3 id(cycle[(+),(*),(-),(/)])(x#n)(tail$x#n)
x1
and x2
are taken as a list. Usage example: [1,3] # 8
-> [1.0,3.0,4.0,12.0,-8.0,-1.5,-9.5,14.25]
.
Laziness makes it possible to define an infinite recursive list where we take the first n elements.
Haskell, 66 bytes
(h%g)y x=x:g(h x y)y
a=(+)%b
b=(*)%c
c=(-)%d
d=(/)%a
(.a).(.).take
Different approach, slightly longer. Argument order is N
, x2
, x1
. Usage example: ( (.a).(.).take ) 8 3 1
-> [1.0,3.0,4.0,12.0,-8.0,-1.5,-9.5,14.25]
.
Defines 4 functions a
, b
, c
and d
which take two arguments y
, x
and make a list by putting x
in front of a call to the next function with y
as the second argument and x op y
as the first. For example a
is: a y x = x : (b (x+y) y)
, b
does multiplication: b y x = x : (c (x*y) y)
, etc.
Edit: @Michael Klein saved a byte in the 1st variant (#
). Luckily I also found one byte for the second variant, so both have the same length again.
Edit II: @Zgarb found 2 bytes in the second version to save, and I 4 in the first, so they are no longer of the same length.
ES6 (Javascript), 79, 67, 65 bytes
- minus 2 bytes, by starting with i=2, as suggested by @ETHProductions
- Saved 3 bytes, thanks to excellent advice from @Neil !
Golfed
S=(n,a,i=2)=>i<n?S(n,a,a.push(eval(a[i-2]+"-/+*"[i%4]+a[i-1]))):a
Test
S=(n,a,i=2)=>i<n?S(n,a,a.push(eval(a[i-2]+"-/+*"[i%4]+a[i-1]))):a
>S(8,[1,3])
Array [ 1, 3, 4, 12, -8, -1.5, -9.5, 14.25 ]
>S(5,[0,1])
Array [ 0, 1, 1, 1, 0 ]
>S(9,[1,0])
Array [ 1, 0, 1, 0, 1, 0, 1, 0, 1 ]
>S(25,[6,3])
Array [ 6, 3, 9, 27, -18, -1.5, -19.5, 29.25, -48.75, -0.6, ...]
Python 3, 90 80 74 bytes
xnor's probably going to come and destroy this solution...
def F(s,n,i=2):
while i<n:s+=eval('%s'*3%(s[-2],'-/+*'[i%4],s[-1])),;i+=1
The function modifies the list passed to it. Use like this:
s = [1,3]
F(s,8)
Try on repl.it!
-6 bytes thanks to Copper