Wednesday, December 18, 2013

Recursive solution in Java and Haskell

Java ===================================================

package lcs;
public class RecursiveLCS
{
  public RecursiveLCS()
  {
    super();
  }

  /**
   * @param a : Input String
   * @param b : Input String
   * @return longest common subsequence
   */
  public static String lcs(String a, String b)
  {
    int aLen = a.length();
    int bLen = b.length();

    if (aLen == 0 || bLen == 0)
      return "";

    if (a.charAt(0) != b.charAt(0))
    {
      String leftStr;
      leftStr = lcs(a.substring(1), b);
      String rightStr = lcs(a, b.substring(1));
      return (leftStr.length() >= rightStr.length())
              ? leftStr
              : rightStr;
    }
    else
    {
      /* Matches, so check remainder of strings */
      return (a.charAt(0) + lcs(a.substring(1), b.substring(1)));
    }
  }

  /**
   * @param args
   */
  public static void main(String args[])
  {
    System.out.println("RESULT =>");
    System.out.println(RecursiveLCS.lcs("nematode  knowledge", "empty bottle"));
    return;
  }
}


Program ran in a sub-second.

Haskell ================================================================
lcsList :: Eq a => [a] -> [a] -> [a]
lcsList [] _ = []
lcsList _ [] = []
lcsList (x:xs) (y:ys) = if x == y
                          then x : lcsList xs ys
                          else
                            let lcs1 = lcsList (x:xs) ys
                                lcs2 = lcsList xs (y:ys)
                            in if (length lcs1) > (length lcs2)
                                  then lcs1
                                  else lcs2


Program ran in almost 14 seconds with the interpreter (ghci)
However, with the compiled versions of each.

< timed on windows powershell >

PS Measure-Command {java lcs.RecursiveLCS}

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 1
Milliseconds      : 95
Ticks             : 10956387
TotalDays         : 1.26810034722222E-05
TotalHours        : 0.000304344083333333
TotalMinutes      : 0.018260645
TotalSeconds      : 1.0956387
TotalMilliseconds : 1095.6387


PS Measure-Command {.\lcsrecursive.exe}


Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 441
Ticks             : 4410242
TotalDays         : 5.10444675925926E-06
TotalHours        : 0.000122506722222222
TotalMinutes      : 0.00735040333333333
TotalSeconds      : 0.4410242
TotalMilliseconds : 441.0242
Ok, Haskell is a winner once compiled.

No comments:

Post a Comment