permutationIndex :: Int → [Int] → [Int]
permutationIndex [] = []
permutationIndex xs =
  let len = length xs
      max = fac len
      divisor = max / len
      i = index / divisor
      el = xs !! i
   in permutationIndex (index - divisor * i) (filter (!= el) xs)

Of course, this is not very efficient, because you're using lists, and 
attempting to index into them and measure their lengths.  Perhaps a different 
data structure is in order.

Thanks

Tom Davie

On 3 Apr 2013, at 17:38, Lone Wolf <amslonew...@gmail.com> wrote:

> http://stackoverflow.com/questions/8940470/algorithm-for-finding-numerical-permutation-given-lexicographic-index
> 
> How would you rewrite this into Haskell?  The code snippet is in Scala. 
> 
> /**
>     example: index:=15, list:=(1, 2, 3, 4)
> */ 
> def permutationIndex (index: Int, list: List [Int]) : List [Int] = 
>   if (list.isEmpty) list else {
>     val len = list.size     // len = 4
>     val max = fac (len)     // max = 24
>     val divisor = max / len // divisor = 6
>     val i = index / divisor // i = 2
>     val el = list (i)
>     el :: permutationIndex (index - divisor * i, list.filter (_ != el)) }
> 
> 
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe@haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe

_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe

Reply via email to