Assignment Help >> Programming Languages
Write a program in Haskell which calculates a balanced partition of N items where each item has a value between 0 and K such that the difference b/w the sum of the values of first partition, S1, and the sum of the values of the second partition, S2, is minimized. Each partition does not have to have the same number of elements.
One classical way to do this is by using dynamic programming. For dynamic programming to be efficient you should avoid recalculating intermediate results. This can be tricky in a functional language as it does not store state information. The solution is data memorization. Intermediate results are stored is a data structure when they are initially calculated and then simply retrieved when needed.
Here is an example of data memorization in calculating a Fibonacci number.
import Data.Array
fibonacci :: Integer -> Integer
fibonacci n = memo!n
where
memo = array (0, n) [ (i, fib i) | i <- [0..n] ]
fib 0 = 0
fib 1 = 1
fib i = memo!(i-1) + memo!(i-2)
This example uses the Array module. Since Haskell is a lazy programming language it only calculates a function when it is needed.
Implement a solution to the balanced partition in Haskell.