Last active
April 19, 2020 16:22
-
-
Save z-------------/4009a1248c38ed455fde2d149b1c9709 to your computer and use it in GitHub Desktop.
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
| class Hash | |
| def iloc(i, *rest, set: nil) | |
| if rest.empty? | |
| self[i] = set if set | |
| self[i] | |
| else | |
| self[i] = Hash.new if not self[i] | |
| self[i].iloc(*rest, set: set) | |
| end | |
| end | |
| end | |
| class DPMethod | |
| def initialize(f) | |
| @f = f | |
| @h = Hash.new | |
| end | |
| def call(*args) | |
| v = @h.iloc(*args) | |
| if not v | |
| v = @f.call(self, *args) | |
| @h.iloc(*args, set: v) | |
| end | |
| v | |
| end | |
| end | |
| =begin | |
| fdp = DPMethod.new(->(fdp, i){ | |
| case i | |
| when 0 then 0 | |
| when 1 then 1 | |
| else fdp.call(i - 2) + fdp.call(i - 1) | |
| end | |
| }) | |
| fdp.call 30 # => 832040 | |
| =end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment