Advertisement
mitrakov

Permutations of vowels

Oct 7th, 2018
435
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.91 KB | None | 0 0
  1. // Exercise: permutations of all vowels in a String
  2.  
  3. object Str {
  4.   private def perm(base: List[Char], acc: List[Char]): List[List[Char]] = {
  5.     if (base.size == acc.size) List(acc)
  6.     else base filter(!acc.contains(_)) flatMap { c =>
  7.       perm(base, c :: acc)
  8.     }
  9.   }
  10.  
  11.   // usage: val s = "abcdei"; vowelPerm(s, n => "aeiouyAEIOUY".contains(s(n)))
  12.   def vowelPerm(s: String, predicate: Int => Boolean): List[String] = {
  13.     val vowels = s.zipWithIndex.filter{t => predicate(t._2)}.map{_._1}.toList
  14.     perm(vowels, Nil).map { p =>
  15.       var k = -1
  16.       val result = s.zipWithIndex.map {
  17.         case (_, i) if predicate(i) => k+=1; p(k)
  18.         case (c, _) => c
  19.       }.toArray
  20.       new String(result)
  21.     }
  22.   }
  23. }
  24.  
  25. // test:
  26. val s = "abcdei"
  27. Str.vowelPerm(s, n => "aeiouyAEIOUY".contains(s(n))) foreach println
  28.  
  29. // output:
  30. // ibcdea
  31. // ebcdia
  32. // ibcdae
  33. // abcdie
  34. // ebcdai
  35. // abcdei
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement