Skip to content

Instantly share code, notes, and snippets.

@daimatz
Created March 7, 2014 12:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daimatz/9410299 to your computer and use it in GitHub Desktop.
Save daimatz/9410299 to your computer and use it in GitHub Desktop.
object Main {
def main(args: Array[String]) = {
val data = testData()
val start1 = System.currentTimeMillis()
data.foreach(isValidIpFormat1)
val end1 = System.currentTimeMillis()
println("1: " + (end1 - start1))
val start2 = System.currentTimeMillis()
data.foreach(isValidIpFormat2)
val end2 = System.currentTimeMillis()
println("2: " + (end2 - start2))
var n = 0
data.foreach { x =>
require(isValidIpFormat1(x) == isValidIpFormat2(x))
if (isValidIpFormat1(x)) n += 1
}
println("valid: " + n)
}
def testData(): Seq[String] = {
var i = 0
val ret = scala.collection.mutable.ArrayBuffer[String]()
val r = new scala.util.Random()
while (i < 1000000) {
val x = r.nextInt(5)
if (x == 4) {
ret +=
r.nextInt(300).toString + "." +
r.nextInt(300).toString + "." +
r.nextInt(300).toString + "." +
r.nextInt(300).toString
} else if (x == 3) {
ret +=
r.nextInt(300).toString + "." +
r.nextInt(300).toString + "." +
r.nextInt(300).toString
} else if (x == 2) {
ret +=
r.nextInt(300).toString + "." +
r.nextInt(300).toString
} else if (x == 1) {
ret +=
r.nextInt(300).toString
}
i += 1
}
ret
}
private[this] def isDigit(c: Char): Boolean = {
'0' <= c && c <= '9'
}
def isValidIpFormat1(ip: String): Boolean = {
val ipArray: Array[String] = ip.split("\\.")
if (ipArray.length != 4) { return false }
var i = 0
while (i < 4) {
val s = ipArray(i)
if (s.size == 3) {
if (s(0) == '2') {
if (s(1) == '5') {
if (! ('0' <= s(2) && s(2) <= '5')) { return false }
} else if ('0' <= s(1) && s(1) <= '4') {
if (! isDigit(s(2))) { return false }
} else {
return false
}
} else if ('0' <= s(0) && s(0) <= '1') {
if (! isDigit(s(1))) { return false }
if (! isDigit(s(2))) { return false }
} else {
return false
}
} else if (s.size == 2) {
if (! isDigit(s(0))) { return false }
if (! isDigit(s(1))) { return false }
} else if (s.size == 1) {
if (! isDigit(s(0))) { return false }
} else {
return false
}
i += 1
}
return true
}
val pattern = java.util.regex.Pattern.compile(
"^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"
)
def isValidIpFormat2(ip: String): Boolean = {
pattern.matcher(ip).matches()
}
}
$ for i in `seq 10`; scala Main
1: 647
2: 359
valid: 105767
1: 354
2: 395
valid: 106295
1: 668
2: 392
valid: 105741
1: 650
2: 384
valid: 106096
1: 662
2: 382
valid: 106424
1: 673
2: 428
valid: 106588
1: 686
2: 381
valid: 106354
1: 642
2: 383
valid: 105919
1: 342
2: 403
valid: 105998
1: 685
2: 393
valid: 106096
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment