Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Jul 24, 2023. It is now read-only.

Commit d99df7c

Browse files
author
cd155
committed
add generate permutations
1 parent babea83 commit d99df7c

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

‎src/Recursion.hs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -299,3 +299,46 @@ hanoi 0 _ _ _ = []
299299
hanoi 1 start _ end = [(start, end)]
300300
hanoi n start temp end =
301301
hanoi (n-1) start end temp ++ [(start, end)] ++ hanoi (n-1) temp start end
302+
303+
{-
304+
8.7 and 8.8
305+
1. Generate all permutations of a unique string
306+
307+
2. Generate all permutations of an non-unique string
308+
309+
test case: (sort $ permutations "abc") == (sort $ genPerm "abc")
310+
311+
bottom-up solution p356
312+
-}
313+
genPerm :: String -> [String]
314+
genPerm = genPermHelper [[]]
315+
316+
-- Loop through all possible character
317+
genPermHelper :: [String] -> String -> [String]
318+
genPermHelper inp [] = inp
319+
genPermHelper inp (x:xs) = genPermHelper newInp xs
320+
where newInp = appendPerm inp x
321+
322+
-- Accumulate new permutations (not finished)
323+
appendPerm :: [String] -> Char -> [String]
324+
appendPerm [] _ = []
325+
appendPerm (x:xs) c = newPerm ++ appendPerm xs c
326+
where -- newPerm = appendPermHelper x c 0 -- with duplicates
327+
newPerm = appendPermHelper' x c 0 [] -- without duplicates
328+
329+
-- Insert the character to every index of the input
330+
appendPermHelper :: String -> Char -> Nat -> [String]
331+
appendPermHelper str c ind
332+
| ind > length str = []
333+
| otherwise = (fstHalf ++ [c] ++ sndHalf): appendPermHelper str c (ind+1)
334+
where (fstHalf,sndHalf) = splitAt ind str
335+
336+
-- Insert the character to every index of the input with no duplicates
337+
appendPermHelper' :: String -> Char -> Nat -> [String] -> [String]
338+
appendPermHelper' str c ind acc
339+
| ind > length str = acc
340+
| newPerm `elem` acc = appendPermHelper' str c (ind+1) acc
341+
| otherwise = appendPermHelper' str c (ind+1) (newPerm:acc)
342+
where (fstHalf,sndHalf) = splitAt ind str
343+
newPerm = fstHalf ++ [c] ++ sndHalf
344+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /