I have been asked to translate the following code which finds a maximum non-overlapping increasing sub sequence given a large amount of input. I haven't had much time to learn a lot on Haskell and I am stuck how to actually do it.
Here is the code in Java:
import java.util.*;
public class mnois {
public static int[][] memo;
public static int[][] lis;
public static int[] nums;
public static int[][][] lmemo;
public static int n;
public static String input;
public static String[] arrIn;
public static void main(String[] args) {
Scanner br = new Scanner(System.in);
int t = br.nextInt();
for(int c = 1;c<=t;c++) {
n = br.nextInt();
input = br.nextLine();
arrIn = input.split(" ");
nums = new int[n];
for(int i = 0;i<n;i++){
nums[i] = Integer.parseInt(arrIn[i]);
}
memo = new int[n][n+1];
for(int i = 0;i<n;i++){
Arrays.fill(memo[i], -1);
}
lmemo = new int[n][n+1][n+1];
for(int i = 0;i<n;i++){
for(int j = 0;j<n+1;j++){
Arrays.fill(lmemo[i][j], -1);
}
}
lis = new int[n][n];
for(int i = 0;i<n;i++){
for(int j = i;j<n;j++){
lis[i][j] = lis(i, n, j);
}
}
for(int i = 1;i<=n;i++){
System.out.print(go(0, i));
if (i != n){
System.out.print(" ");
}
}
System.out.println();
}
}
public static int lis(int pos, int last, int max) {
if (pos > max) {
return 0;
}
if (lmemo[pos][last][max] != -1){
return lmemo[pos][last][max];
}
int best = lis(pos+1, last, max);
if (last == n || nums[pos] > nums[last]) {
best = Math.max(best, lis(pos+1, pos, max)+1);
}
return lmemo[pos][last][max] = best;
}
public static int go(int pos , int k){
if (pos >= n) {
return 0;
}
if (memo[pos][k] != -1){
return memo[pos][k];
}
int best = go(pos+1, k);
for(int i = pos;i<n;i++){
if (lis[pos][i] >= k) {
best = Math.max(best, go(i+1, k)+lis[pos][i]);
}
}
return memo[pos][k] = best;
}
}
I am particularly having problems with creating mutable 2D and 3D arrays. Appreciate any help I can get.
This is what I have so far:
import Data.Array.IO
case :: Int -> Int -> Bool
case index n =
if (index >= n)
return True
else do
numElems :: Int <- readLn
strElems <- readLn
nums <- newArray_ (0, numElems) :: Int
addElems nums 0 0 numElems strElems
memo <- newArray ((0, 0), (strElems, strElems+1)) -1 :: IO (IOArray (Int, Int) Int)
lmemo <- newArray (((0,0),(0,0)), ()) -1 :: IO (IOArray (Int, Int) IO (IOArray (Int, Int) Int))
lis <- newArray ((0, 0), (strElems, strElems)) -1 :: IO (IOArray (Int, Int) Int)
addElems :: (IOArray s Int Int) -> Int -> Int -> Int -> String -> IO s ()
addElems arr startArr strIndex finish string =
if (start >= finish) then
return ()
else do
num <- digitToInt $ string !! strIndex
writeArray arr startArr char
addElems arr (startArr+1) (strIndex+2) finish string
lisLoop :: (IOArray s Int Int) -> Int -> Int -> IO s ()
listLoop arr start finish =
if (start >= finish) then
return ()
else do
next 0 finish
where
next i currIdx len =
if (i < len)
writeArray arr (currIdx, i)
next (i+1) currIdx len