@@ -299,3 +299,46 @@ hanoi 0 _ _ _ = []
299
299
hanoi 1 start _ end = [(start, end)]
300
300
hanoi n start temp end =
301
301
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