Using Scala, how do I know if a list of characters is present in a String where there are duplicate characters?

Consider the following example: I have a given set of words and a given set of characters . I have to figure out if there is a word that can be made from a list of characters while respecting duplication, i.e. A word is a multiset subset of a multiset of characters. So, for symbols, a List('a', 'p', 'q', 'r', 's')

word is "apqsrr"

not a valid solution, since it contains two 'r'

s. The usual solution I can think of is to iterate over the characters of the word and if a match is found in characters then remove that char from the character list. This can handle duplicates, but I don't know how to write this in scala in a more functional way...

From what knowledge I have scala I was able to write the following code which works great if there are no duplicate letters.

val words = List("apqsrr", "avadavat", "avail", "availability", "available", 
  "avalanche", "avantgarde", "avarice")
val chars = List('a', 'p', 'q', 'r', 's')

for (w <- words if w.forall(chars.contains)) yield w

// another way 
words.find(_.forall(chars.contains))

      

+3


source to share


1 answer


scala> words.find(_.diff(chars).isEmpty)
res0: Option[String] = None

scala> val chars = List('a','p','q','r','s','r') // Added another 'r'
chars: List[Char] = List(a, p, q, r, s, r)

scala> words.find(_.diff(chars).isEmpty)
res1: Option[String] = Some(apqsrr)

      



+6


source







All Articles