BruteForce

This commit is contained in:
Ivan Li 2019-01-13 14:53:07 +08:00
parent b36b6c759e
commit dc7e5171b1
2 changed files with 44 additions and 0 deletions

View File

@ -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
}
}

View File

@ -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)
}
}