Skip to content

Instantly share code, notes, and snippets.

@nobsun
Last active August 29, 2015 14:26
Show Gist options
  • Save nobsun/1b4c7373b4804d28391d to your computer and use it in GitHub Desktop.
Save nobsun/1b4c7373b4804d28391d to your computer and use it in GitHub Desktop.
permNth :: [a] -> Int -> [a]
permNth xs = (perms xs !!)
permNth :: [a] -> Integer -> [a]
permNth xs idx = snd $ mapAccumL f (xs,idx) $ reverse $ take n facts
f (ys,jdx) fact = case divMod jdx fact of
(d,m) -> case splitAt (fromIntegral d) ys of
(zs,w:ws) -> ((zs++ws,fromIntegral m),w)
permNth :: [a] -> Integer -> [a]
permNth xs idx = snd $ mapAccumL f (xs,idx) $ reverse $ take n facts
where
n = length xs
f (ys,jdx) fact = case divMod jdx fact of
(d,m) -> case splitAt (fromIntegral d) ys of
(zs,w:ws) -> ((zs++ws,fromIntegral m),w)
facts :: [Integer]
facts = scanl (*) 1 [1..]
permIndex :: Eq a => [a] -> [a] -> Integer
permIndex [] [] = 0
permIndex xs@(_:_) ys@(_:_) = sum $ zipWith (*) zs $ snd $ mapAccumL f xs ys
where
zs = reverse $ take (length xs) facts
f ps q = case elemIndex q ps of
Just i -> (delete q ps,fromIntegral i)
import Data.List (mapAccumL,elemIndex,delete)
permNth :: [a] -> Integer -> [a]
permNth xs idx = snd $ mapAccumL f (xs,idx) $ reverse $ take n facts
where
n = length xs
f (ys,jdx) fact = case divMod jdx fact of
(d,m) -> case splitAt (fromIntegral d) ys of
(zs,w:ws) -> ((zs++ws,fromIntegral m),w)
permIndex :: Eq a => [a] -> [a] -> Integer
permIndex [] [] = 0
permIndex xs@(_:_) ys@(_:_) = sum $ zipWith (*) zs $ snd $ mapAccumL f xs ys
where
zs = reverse $ take (length xs) facts
f ps q = case elemIndex q ps of
Just i -> (delete q ps,fromIntegral i)
facts :: [Integer]
facts = scanl (*) 1 [1..]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment