Just another update

This commit is contained in:
Ingy döt Net 2015-02-20 00:35:01 -05:00
parent a25938f123
commit 00a190b0a6
6591 changed files with 94363 additions and 23227 deletions

View file

@ -1,25 +1,21 @@
import scala.util.Random
import scala.util.Random.shuffle
object BalancedParensApp extends App {
object BalancedBracketsApp extends App {
val triesCount = 10
(0 until triesCount).foreach { i =>
val str = randomString(length = i)
val msg = if (isBalanced(str)) "ok" else "NOT ok"
println(s"$str - $msg")
for (length <- 0 until 10) {
val str = randomBrackets(length)
if (is_balanced(str))
println(s"$str - ok")
else
println(s"$str - NOT ok")
}
def randomString(length: Int) = {
val parensPairs = ("[]" * length).toSeq
val parensOfGivenLength = parensPairs.take(length)
val shuffledParens = Random.shuffle(parensOfGivenLength)
shuffledParens.mkString
}
def randomBrackets(length: Int): String =
shuffle(("[]" * length).toSeq).mkString
def isBalanced(parensString: String): Boolean = {
def isBalanced(bracketString: String): Boolean = {
var balance = 0
parensString.foreach { char =>
for (char <- bracketString) {
char match {
case '[' => balance += 1
case ']' => balance -= 1

View file

@ -0,0 +1,19 @@
import scala.util.Random.shuffle
import scala.annotation.tailrec
// ...
def isBalanced(str: String): Boolean = isBalanced(str.toList, balance = 0)
@tailrec
def isBalanced(str: List[Char], balance: Int = 0): Boolean =
str match {
case _ if (balance < 0) => false
case Nil => balance == 0
case char :: rest =>
val newBalance = char match {
case '[' => balance + 1
case ']' => balance -1
}
isBalanced(rest, newBalance)
}