I tried implementing the rod cutting problem with memoization preferred in a functional programming language while trying to honor immutability, but I don't know how I can get around to doing so. The algorithm for the cutting rod problem is...
memoized-cut-rod(p, n)
let r[0..n] be a new array
for i = 0 to n
r[i] = -infinity
return memoized-cut-rod-aux(p, n, r)
memoized-cut-rod-aux(p, n, r)
if r[n] >= 0
return r[n]
if n == 0
q = 0
else
q = -infinity
for i = 1 to n
q = max(q, p[i] + memoized-cut-rod-aux(p, n - i, r))
r[n] = q
return q
Can someone assist me in getting a purely functional approach to this algorithm?
The following is a translation of the top-down algorithm into Scala. The memoized values are local to
memoizedCutRodso they have no impact on the environment, i.e., without side effects. I changed a couple of the names. The interior, recursive function usespfrom the exterior function since it is not changing, andmemois share across all instances of the recursive function.I also changed the use of
- infinityto anOption[Int], so that we have a clear indicator that the value is not yet defined. I prefer that to the method of using an "impossible" number as a flag.