forked from wangzheng0822/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
b36b6c7
commit dc7e517
Showing
2 changed files
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
|
||
} |