2

I'm new to Scala and for practice I'm trying to write brute-force string matching function that can return a list of indices of matches. The best that I have is pasted below. I would appreciate assitance in making this idiomatic. Also as you'll notice this just prints the indices, whereas I'd prefer a List or Stream.

def strMatching(txt: String, pat: String): Unit = {
        val N = txt.length
        val M = pat.length
        for (i <- 1 to N-M) {
            var j = 0
            while (j < M && pat(j) == txt(i+j)) {
                if (j == M-1) print(s"${i+1} ")
                j = j + 1
            }
        }
    }

Thanks a lot!

2 Answers 2

3

A possible one liner, with the brute force algorithm, could be

txt.indices.filter(i => txt.substring(i).startsWith(pat))
Sign up to request clarification or add additional context in comments.

1 Comment

even shorter : txt.indices filter (txt.startsWith(pat, _))
1
def strMatch(txt: String, pat: String): List[Int] = {

     var index = 0;
     var indices = List.empty[Int]

     // sliding gives a sliding window of given length
     txt sliding pat.length foreach { x => 
                                      if (pat == x) indices = indices :+ index
                                      index += 1 }

     indices
}

2 Comments

Thanks for your answer. To be honest, I'd prefer a solution that doesn't use a var
It's fine. The above function with var is side-effect free, which is what matters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.