[Haskell-cafe] algorithm-for-finding-numerical-permutation-given-lexicographic-index
Tom Davie
tom.davie at gmail.com
Wed Apr 3 18:44:27 CEST 2013
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 <amslonewolf at 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 at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20130403/710ee6bc/attachment.htm>
More information about the Haskell-Cafe
mailing list