Code and Bugs

Coding things

Haskell or C?

with 2 comments

I got bored one day and was looking for something to test my coding skills by trying to solve a difficult problem on a difficult contest. Luckily, reddit provided me with this contest which was exactly what I was looking for.

It seemed to me that Haskell was a valid option for solving this. So, I started writing a function to compute the value of the sequence of darts. Simple enough:

valueOfSeq :: Int -> [Int] -> Int
valueOfSeq n seq = fst . head' . (dropWhile f) . (zip [1..]) $ result
  where
    head' [] = (1 + last result, 1)
    head' l = head l
    f (x, y) = x == y
    result = sort . nub $ l1 ++ l2 ++ l3 ++ l4 ++ l5 ++ l6
    l1 = seq
    l2 = nub [ x+y | x <- l1, y <- l1]
    l3 = nub [ x+y | x <- l2, y <- l1]
    l4
      | n > 3 = nub [ x+y | x <- l3, y <- l1]
      | otherwise = []
    l5
      | n > 4 = nub [ x+y | x <- l4, y <- l1]
      | otherwise = []
    l6
      | n > 5 = nub [ x+y | x <- l5, y <- l1]
      | otherwise = []

However, while trying to generate those sequences in an intelligent way I got into some troubles. Mainly caused by my inexperience in Haskell language but unacceptable at the moment. So, I’ve tried the same thing in C:

 int getValueOfSeq(int R, int D, int seq[R])
{
  Q *q = initQ();
  int i;
  elem x, y;
  int value = 1;
  for (i = 0; i < R; i++){
    x.value = seq[i];
    x.count = 1;
    pushQ(q, x);
  }
  while (!isEmptyQ(q)){
    x = popQ(q);
    if (x.value != value)
      break;
    else
      value++;
    y.count = x.count + 1;
    if (y.count <= D){
      for (i = 0; i < R; i++){
        y.value = x.value + seq[i];
        pushQ(q, y);
      }
    }
  }
  cleanQ(q);
  return value;
 }
 

Taking into account some more additions (the auxiliary functions in C and some sequence generation in Haskell) the entire code looks like this:

mihai@keldon:~$ wc -l p.c
115 p.c
mihai@keldon:~$ wc -l Test.hs
38 Test.hs

Need I say more?

Written by Mithrandir

July 10, 2009 at 11:55 am

Posted in Contests

Tagged with ,

2 Responses

Subscribe to comments with RSS.

  1. > Need I say more?

    Hmm.. yes, like: what should this demonstrate?

    gu

    July 10, 2009 at 10:23 pm

  2. That Haskell and C code can be differently written to solve the same problem. That Haskell code can be written more quickly than C code (and in fewer lines) on some problems and that the programmer should think before very well before choosing the language used.

    Mithrandir

    July 11, 2009 at 4:08 am


Leave a Reply