Skip to content

Instantly share code, notes, and snippets.

@rodrigogiraoserrao
Created August 6, 2020 15:47
Show Gist options
  • Save rodrigogiraoserrao/0ffe48f804f4f46c215c50a3d7fe4e44 to your computer and use it in GitHub Desktop.
Save rodrigogiraoserrao/0ffe48f804f4f46c215c50a3d7fe4e44 to your computer and use it in GitHub Desktop.
RGS's solution for Problem 5, Phase 2 of 2020 APL competition (see https://mathspp.com/blog/2020-apl-competition for my thoughts on it)
⍝ PROBLEM 5.1
rr ← {
(⎕IO ⎕ML ⎕WX) ← 0 1 3
⍝ Computes how much your investment is worth after cash flows and rate calculations.
⍝ Dyadic function expecting number vector on the left (deposits/withdrawals) and number vector on the right (corresponding rates).
⍝ At moment 1 you have r[1] ← ⍺[0] and at the subsequent moments you have r[n] ← ⍺[n-1] + r[n-1]×⍵[n-1].
⍝ Expanding the recurrence relation we can determine beforehand all expressions.
⍝ Assuming ⎕IO←0 and traditional mathematical notation,
⍝ r[1]←⍺[0], r[2]←⍺[1]+⍺[0]⍵[1], r[3]←⍺[2]+⍺[1]⍵[2]+⍺[0]⍵[2]⍵[1], r[4]←⍺[3]+⍺[2]⍵[3]+⍺[1]⍵[3]⍵[2]+⍺[0]⍵[3]⍵[2]⍵[1]
⍝ Returns a number.
⍝ This code manipulates triangular matrices as seen in https://aplcart.info/?q=extract%20triangular%20matrix#,
⍝ content I added to APL Cart, cf. https://github.com/abrudz/aplcart/pull/46
_E ← {(⊢×∘.⍺⍺⍨∘⍳∘≢)⍵} ⍝ Extract the lower/upper (strict?) triangular part of a matrix
_M ← {(∘.⍺⍺⍨)⍵} ⍝ Vector into rows (⊢) or columns (⊣) of a square matrix
rt ← ×⍀ 1 + >_E ⊣_M ⍵ ⍝ Produce cumulative rates,
a ← ≥_E ⊢_M ⍺ ⍝ expand amounts to proper shape
+/ a × rt ⍝ and sum them after multiplying.
}
⍝ PROBLEM 5.2
⍝ Computes the present value of an investment with future cash flows ⍺ at inflation rates ⍵.
⍝ Dyadic function expecting two vectors with the same length.
⍝ Returns a number.
pv ← (1⊥×∘(×\1÷+∘1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment