How to check if each letter in a string maps to the first letter of a word in another string with Scala

1 Answer

0 votes
object PatternMatch {

  def matchesPattern(pattern: String, sentence: String): Boolean = {
    val words = sentence.split("\\s+").toList

    // Length mismatch → automatic failure
    if (pattern.length != words.length)
      return false

    // Compare each pattern character to the first letter of each word
    pattern
      .zip(words)
      .forall { case (p, w) =>
        p.toLower == w.head.toLower
      }
  }

  def main(args: Array[String]): Unit = {
    val pattern  = "jpcrg"
    val sentence = "java python c rust go"

    if (matchesPattern(pattern, sentence))
      println("Pattern matches!")
    else
      println("Pattern does NOT match.")
  }
}




/*
run:

Pattern matches!

*/


 



answered Jan 6 by avibootz

Related questions

...