making permutation from two list but not using full number [closed]

Making a guess at what your current code does, here’s a proposal for an algorithm:

  1. nondeterministically pick a permutation of the vowels
  2. assign indices to the permutation
  3. use the standard tails trick to nondeterministically choose the appropriate number of elements from this list

In code:

import Data.List

choose :: Int -> [a] -> [[a]]
choose 0 xs = [[]]
choose n xs = do
    x:xs' <- tails xs
    (x:) <$> choose (n-1) xs'

assignments :: Int -> [a] -> [[(Int, a)]]
assignments n xs = do
    xs' <- permutations xs
    choose n (zip [1..] xs')

In ghci:

> mapM_ print (assignments 2 "abc")
[(1,'a'),(2,'b')]
[(1,'a'),(3,'c')]
[(2,'b'),(3,'c')]
[(1,'b'),(2,'a')]
[(1,'b'),(3,'c')]
[(2,'a'),(3,'c')]
[(1,'c'),(2,'b')]
[(1,'c'),(3,'a')]
[(2,'b'),(3,'a')]
[(1,'b'),(2,'c')]
[(1,'b'),(3,'a')]
[(2,'c'),(3,'a')]
[(1,'c'),(2,'a')]
[(1,'c'),(3,'b')]
[(2,'a'),(3,'b')]
[(1,'a'),(2,'c')]
[(1,'a'),(3,'b')]
[(2,'c'),(3,'b')]

Leave a Comment