Forum Discussion
Viz
Jan 05, 2021Brass Contributor
Lambda Example: Generate Fibonacci series
In this post, I would like to explain how I have used Lambda to create a function to generate a Fibonacci series array. This example can also be used to understand how to create an array where th...
PeterBartholomew1
Apr 24, 2023Silver Contributor
I think I am becoming conditioned! I only have to read the words Pascal's triangle and I find myself writing
=REDUCE(1, SEQUENCE(n),
LAMBDA(triangle, k,
LET(
previous, TAKE(triangle, -1),
left, HSTACK(previous, 0),
right, HSTACK(0, previous),
IFNA(VSTACK(triangle, left + right), "")
)
)
)
Patrick2788
Apr 24, 2023Silver Contributor
Does that create a pyramid-like array?
I went with a left-justified version:
'Pascal
=Lambda(n,DROP(
REDUCE(
"",
SEQUENCE(, n),
LAMBDA(a, v, VSTACK(a, EXPAND(COMBIN(v - 1, SEQUENCE(, v, 0)), , n, "")))
),
1
))
- PeterBartholomew1Apr 25, 2023Silver Contributor
No, like yours it is left stacked. Far more effort would be required for they layout than was needed for the calculation! The main difference is that mine is more primitive in that it uses the recurrence relation from row to row rather that the functional form of the result.
Since you mention it though, how about this?
= REDUCE(1, SEQUENCE(n), LAMBDA(triangle,k, LET( previous, TAKE(triangle, -1), left, HSTACK(previous, {0,0}), right, HSTACK({0,0}, previous), triangle, VSTACK(HSTACK(0,triangle), left + right), IFERROR(IF(triangle,triangle,""),"") ) ) )
- Patrick2788Apr 25, 2023Silver ContributorIt reads very well and is elegant. It's a different approach than I've been studying. Pascal's Triangle is fascinating because of the sub-arrays contained within. I had been working on something where the triangle would be created and the fibonacci numbers would be pulled from the sum of the 'shallow diagonals'. I had to stop myself because I was creating a problem that didn't need to exist when a more direct approach is better!
- mtarlerApr 25, 2023Silver Contributor
PeterBartholomew1 OK all this inspired me to bring it back to this topic and create the "classic" fib spiral:
=LET(n,10, LET(a, {1,1;1,0}, IF(n>2, DROP(REDUCE({1,1;1,1},SEQUENCE(n-2,,0),LAMBDA(ac,n, LET(fibNs,TAKE(ac,1,2), fibSp,DROP(ac,1), fibNextPair,MMULT(fibNs,a), fibNext, INDEX(fibNextPair,1), fibNextBlock, SEQUENCE(fibNext,fibNext,fibNext,0), fibSpiral, CHOOSE(MOD(n,4)+1,VSTACK(fibSp,fibNextBlock), HSTACK(fibSp,fibNextBlock), VSTACK(fibNextBlock,fibSp),HSTACK(fibNextBlock,fibSp)), VSTACK(fibNextPair,fibSpiral) ))),1), "n must > 2")))
- PeterBartholomew1Apr 25, 2023Silver Contributor
I didn't even think of trying that! How about a bit of conditional formatting?
Every workbook should have one?