Skip to content

Commit

Permalink
BruteForce
Browse files Browse the repository at this point in the history
  • Loading branch information
email2liyang committed Jan 13, 2019
1 parent b36b6c7 commit dc7e517
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
24 changes: 24 additions & 0 deletions scala/src/main/scala/ch32_matching/BruteForce.scala
Original file line number Diff line number Diff line change
@@ -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 changes: 20 additions & 0 deletions scala/src/test/scala/ch32_matching/BruteForceTest.scala
Original file line number Diff line number Diff line change
@@ -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)
}

}

0 comments on commit dc7e517

Please sign in to comment.