diff --git a/scala/src/main/scala/ch32_matching/BruteForce.scala b/scala/src/main/scala/ch32_matching/BruteForce.scala new file mode 100644 index 0000000..ad61226 --- /dev/null +++ b/scala/src/main/scala/ch32_matching/BruteForce.scala @@ -0,0 +1,24 @@ +package ch32_matching + +import scala.util.control.Breaks._ + +object BruteForce { + + def firstIndexOf(main: Array[Char], sub: Array[Char]): Int = { + + require(main != null, "main array required") + require(sub != null, "sub array required") + require(main.length >= sub.length, "sub array should be small than main array") + var result = -1 + breakable { + for (i <- 0 until (main.length - sub.length)) { + if (main.slice(i, i + sub.length) sameElements sub) { + result = i + break + } + } + } + result + } + +} diff --git a/scala/src/test/scala/ch32_matching/BruteForceTest.scala b/scala/src/test/scala/ch32_matching/BruteForceTest.scala new file mode 100644 index 0000000..44f8700 --- /dev/null +++ b/scala/src/test/scala/ch32_matching/BruteForceTest.scala @@ -0,0 +1,20 @@ +package ch32_matching + +import org.scalatest.{FlatSpec, Matchers} + +import scala.util.Random + +class BruteForceTest extends FlatSpec with Matchers { + + behavior of "BruteForceTest" + + it should "find firstIndexOf a sub string" in { + val random = Random.alphanumeric + val main = random.take(1000).toArray + val index = Random.nextInt(950) + val sub = random.take(1000).toArray.slice(index, index + 50) + + BruteForce.firstIndexOf(main, sub) should equal(index) + } + +}