BruteForce
This commit is contained in:
parent
b36b6c759e
commit
dc7e5171b1
24
scala/src/main/scala/ch32_matching/BruteForce.scala
Normal file
24
scala/src/main/scala/ch32_matching/BruteForce.scala
Normal 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
|
||||
}
|
||||
|
||||
}
|
20
scala/src/test/scala/ch32_matching/BruteForceTest.scala
Normal file
20
scala/src/test/scala/ch32_matching/BruteForceTest.scala
Normal 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)
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue
Block a user