Don't know how this "kumite" stuff works yet, so i may be doing sth wrong.
This is about finding better/more efficient ways to permutate a list starting with my sorry attempt. The result requires types of the typeclass Ord, to get a common result for the test cases. Havent thought about a way to solve that differently yet.
module Permutation where
import Data.List (sort)
permu :: [a] ->[[a]]
permu [] = [[]]
permu [x] = [[x]]
permu x = fuzz (length x) 0 x
where fuzz l n (x:xs) |n == l = []
|otherwise = map ((:) x) (permu xs) ++ fuzz l (n+1) (xs ++ [x])
permutation :: Ord a => [a] -> [[a]]
permutation x = permu x
module PermuSpec where
import Test.Hspec
import Data.List (sort)
import Permutation
-- `spec` of type `Spec` must exist
spec :: Spec
spec = do
describe "Permutation" $ do
it "Basic Tests" $ do
shouldBe (sort $ permutation [1,2,3]) [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
shouldBe (sort $ permutation [1..4]) [[1,2,3,4],[1,2,4,3],[1,3,2,4],[1,3,4,2],[1,4,2,3],[1,4,3,2],[2,1,3,4],[2,1,4,3],[2,3,1,4],[2,3,4,1],[2,4,1,3],[2,4,3,1],[3,1,2,4],[3,1,4,2],[3,2,1,4],[3,2,4,1],[3,4,1,2],[3,4,2,1],[4,1,2,3],[4,1,3,2],[4,2,1,3],[4,2,3,1],[4,3,1,2],[4,3,2,1]]
shouldBe (sort $ permutation "wup") ["puw","pwu","upw","uwp","wpu","wup"]