Last active
January 30, 2023 15:22
-
-
Save scriptingstudio/201ace34522f4e222cb6cbb8cb3b5a90 to your computer and use it in GitHub Desktop.
Powershell fibonacci - just for fun
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # DEMO: caching calculations demo - superfast | |
| # reverse calculations | |
| function fibonacciR ([Double]$fn, [switch]$series, $fbcache) { | |
| #if ($MyInvocation.MyCommand.name -ne $(Get-PSCallStack)[1].FunctionName) { | |
| # $fbcache = $null # prevent using $fbcache from root | |
| #} | |
| if ($fbcache -eq $null) {$fbcache = [System.Collections.Generic.Dictionary[string,Double]]::new($fn)} | |
| if ($fbcache.ContainsKey($fn)) {$fbcache[$fn]} | |
| elseif ($fn -lt 2) { | |
| $fbcache[$fn] = $fn | |
| if ($series) {$fbcache.GetEnumerator() | Sort-Object {$_.value}} else {$fn} | |
| } | |
| else { | |
| $fbcache[$fn] = (fibonacci ($fn - 1) -fbcache $fbcache) + (fibonacci ($fn - 2) -fbcache $fbcache) | |
| if ($series) {$fbcache.GetEnumerator() | Sort-Object {$_.value}} else {$fbcache[$fn]} | |
| } | |
| } # END fibonacciR | |
| function fibonacci ([double]$fn, [switch]$series) { | |
| $fbcache = [System.Collections.Generic.Dictionary[Double,Double]]::new() | |
| $fbcache.add(0,0) | |
| $fbcache.add(1,1) | |
| if ($fn -lt 2) { | |
| return $fbcache | |
| } | |
| for ([double]$i=2; $i -le $fn; $i++) { | |
| $fbcache[$i] = $fbcache[$i-1] + $fbcache[$i-2] | |
| } | |
| if ($series) {$fbcache} else {$fbcache[$fn]} | |
| } # END fibonacci | |
| fibonacciR 1000 -series |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment