Just another update
This commit is contained in:
parent
a25938f123
commit
00a190b0a6
6591 changed files with 94363 additions and 23227 deletions
|
|
@ -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
|
||||
|
|
|
|||
19
Task/Balanced-brackets/Scala/balanced-brackets-3.scala
Normal file
19
Task/Balanced-brackets/Scala/balanced-brackets-3.scala
Normal 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)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue