Created
November 16, 2021 20:18
-
-
Save Rafailong/ec0f126a22d9ce528d5537d7224c9142 to your computer and use it in GitHub Desktop.
Vowel Families
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Given two words, we can determine if they have the same vowels, | |
* ignoring order and repetition. | |
* | |
* For instance, “Hello” and “Vowel” both have \e and \o, so they have the same vowels. | |
* | |
* Write a function that groups words into “families” that all have the same vowels. | |
* “Tree” and “tent” also belong to the same family because we ignore the repetition of \e. | |
* | |
* Examples | |
* | |
* (vowel-families ["hello" "vowel" "fox" "cot" "hat" "cat"]) ;=> [["hello" "vowel"] | |
; ["fox" "cot"] | |
; ["hat" "cat"]] | |
(vowel-families []) ;=> [] | |
(vowel-families ["tree" "tent" "blanket"] ;=> [["tree" "tent"] | |
; ["blanket"]] | |
* | |
* Notes | |
* | |
* For this exercise, the vowels are \a, \e, \i, \o, and \u. | |
* If you wish, you may include vowels from other languages and scripts. | |
* Your algorithm should not be case-sensitive. | |
* | |
* Please maintain capitalization and non-alphabetic characters. | |
*/ | |
import $scalac.`-Ypartial-unification` | |
import $dep.`org.typelevel::cats-core:2.3.0` | |
import cats.data.State | |
import cats.implicits._ | |
import scala.collection.immutable._ | |
def isVowel(c: Char): Boolean = | |
"AEIOUaeiou".indexOf(c) =!= -1 | |
def vowels(str: String): Set[Char] = | |
str.toSet.filter(isVowel) | |
type Acc = Map[Set[Char], List[String]] | |
def f(str: String): State[Acc, Unit] = { | |
State { acc => | |
val vwls = vowels(str) | |
val family = acc.get(vwls) match { | |
case Some(fam) => str :: fam | |
case None => List(str) | |
} | |
val newAcc = acc + (vwls -> family) | |
(newAcc, ()) | |
} | |
} | |
def vowelFamilies(words: List[String]) = | |
words | |
.traverse_(f) | |
.run(initialState) | |
.value | |
._1 | |
val initialState: Acc = Map.empty[Set[Char], List[String]] | |
vowelFamilies(List.empty[String]) | |
vowelFamilies(List("hello", "vowel")) | |
vowelFamilies(List("tree", "tent", "blanket")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment