How do I compare these two string :
val a = "fit bit versa"
val b = "fitbit"
another example
val a = "go pro hero 6"
val b = "gopro"
another example
val a = "hero go pro 6"
val b = "gopro"
another example
val a = "hero 6 go pro"
val b = "gopro"
I want to get "true" for the above comparisons but not here:
val a = "vegan protein powder"
val b = "vega"
This should be false.
Currently I am doing:
def matchPattern(a:String, b: String):String=
{
val dd = a.split(" ")
val result = dd.map(_.toLowerCase())
if(result contains b.toLowerCase) true
else false
}
This works for last case but not the rest.
Any suggestion ?
Here's one approach using sliding(i)
, where i
ranges from 2 to word-count in a
, to assemble a list of all possible concatenated adjacent words. It is then checked to see whether b
exactly matches any of the elements in the list, as shown below:
def matchPattern(a: String, b: String): Boolean = {
val words = a.toLowerCase.split("\\s+")
val concats = (2 to words.size).foldLeft(words)(
(acc, i) => acc ++ words.sliding(i).map(_.mkString)
)
concats contains b.toLowerCase
}
matchPattern("Hero go Pro 6", "gopro")
// res1: Boolean = true
matchPattern("Hero go Pro 6", "gopro6")
// res2: Boolean = true
matchPattern("Vegan protein powder", "vega")
// res3: Boolean = false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With