How to resolve the algorithm Balanced brackets step by step in the Scala programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Balanced brackets step by step in the Scala programming language
Table of Contents
Problem Statement
Task:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Balanced brackets step by step in the Scala programming language
Source code in the scala programming language
import scala.collection.mutable.ListBuffer
import scala.util.Random
object BalancedBrackets extends App {
val random = new Random()
def generateRandom: List[String] = {
import scala.util.Random._
val shuffleIt: Int => String = i => shuffle(("["*i+"]"*i).toList).foldLeft("")(_+_)
(1 to 20).map(i=>(random.nextDouble*100).toInt).filter(_>2).map(shuffleIt(_)).toList
}
def generate(n: Int): List[String] = {
val base = "["*n+"]"*n
var lb = ListBuffer[String]()
base.permutations.foreach(s=>lb+=s)
lb.toList.sorted
}
def checkBalance(brackets: String):Boolean = {
def balI(brackets: String, depth: Int):Boolean = {
if (brackets == "") depth == 0
else brackets(0) match {
case '[' => ((brackets.size > 1) && balI(brackets.substring(1), depth + 1))
case ']' => (depth > 0) && ((brackets.size == 1) || balI(brackets.substring(1), depth -1))
case _ => false
}
}
balI(brackets, 0)
}
println("arbitrary random order:")
generateRandom.map(s=>Pair(s,checkBalance(s))).foreach(p=>println((if(p._2) "balanced: " else "unbalanced: ")+p._1))
println("\n"+"check all permutations of given length:")
(1 to 5).map(generate(_)).flatten.map(s=>Pair(s,checkBalance(s))).foreach(p=>println((if(p._2) "balanced: " else "unbalanced: ")+p._1))
}
import scala.util.Random.shuffle
object BalancedBracketsApp extends App {
for (length <- 0 until 10) {
val str = randomBrackets(length)
if (is_balanced(str))
println(s"$str - ok")
else
println(s"$str - NOT ok")
}
def randomBrackets(length: Int): String =
shuffle(("[]" * length).toSeq).mkString
def isBalanced(bracketString: String): Boolean = {
var balance = 0
for (char <- bracketString) {
char match {
case '[' => balance += 1
case ']' => balance -= 1
}
if (balance < 0) return false;
}
balance == 0
}
}
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)
}
@scala.annotation.tailrec
final def isBalanced(
str: List[Char],
// accumulator|indicator|flag
balance: Int = 0,
options_Map: Map[Char, Int] = Map(('[' -> 1), (']' -> -1))
): Boolean = if (balance < 0) {
// base case
false
} else {
if (str.isEmpty){
// base case
balance == 0
} else {
// recursive step
isBalanced(str.tail, balance + options_Map(str.head))
}
}
You may also check:How to resolve the algorithm Literals/Integer step by step in the Emacs Lisp programming language
You may also check:How to resolve the algorithm Playing cards step by step in the CoffeeScript programming language
You may also check:How to resolve the algorithm String comparison step by step in the Java programming language
You may also check:How to resolve the algorithm Pancake numbers step by step in the F# programming language
You may also check:How to resolve the algorithm String prepend step by step in the sed programming language