Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Exercise: permutations of all vowels in a String
- object Str {
- private def perm(base: List[Char], acc: List[Char]): List[List[Char]] = {
- if (base.size == acc.size) List(acc)
- else base filter(!acc.contains(_)) flatMap { c =>
- perm(base, c :: acc)
- }
- }
- // usage: val s = "abcdei"; vowelPerm(s, n => "aeiouyAEIOUY".contains(s(n)))
- def vowelPerm(s: String, predicate: Int => Boolean): List[String] = {
- val vowels = s.zipWithIndex.filter{t => predicate(t._2)}.map{_._1}.toList
- perm(vowels, Nil).map { p =>
- var k = -1
- val result = s.zipWithIndex.map {
- case (_, i) if predicate(i) => k+=1; p(k)
- case (c, _) => c
- }.toArray
- new String(result)
- }
- }
- }
- // test:
- val s = "abcdei"
- Str.vowelPerm(s, n => "aeiouyAEIOUY".contains(s(n))) foreach println
- // output:
- // ibcdea
- // ebcdia
- // ibcdae
- // abcdie
- // ebcdai
- // abcdei
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement