How to resolve the algorithm Balanced brackets step by step in the Wren programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Balanced brackets step by step in the Wren 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 Wren programming language
Source code in the wren programming language
import "random" for Random
var isBalanced = Fn.new { |s|
if (s.isEmpty) return true
var countLeft = 0 // number of left brackets so far unmatched
for (c in s) {
if (c == "[") {
countLeft = countLeft + 1
} else if (countLeft > 0) {
countLeft = countLeft - 1
} else {
return false
}
}
return countLeft == 0
}
System.print("Checking examples in task description:")
var brackets = ["", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]"]
for (b in brackets) {
System.write((b != "") ? b : "(empty)")
System.print("\t %(isBalanced.call(b) ? "OK" : "NOT OK")")
}
System.print("\nChecking 7 random strings of brackets of length 8:")
var rand = Random.new()
for (i in 1..7) {
var s = ""
for (j in 1..8) s = s + ((rand.int(2) == 0) ? "[" : "]")
System.print("%(s) %(isBalanced.call(s) ? "OK" : "NOT OK")")
}
You may also check:How to resolve the algorithm Show ASCII table step by step in the VBA programming language
You may also check:How to resolve the algorithm Perfect numbers step by step in the SparForte programming language
You may also check:How to resolve the algorithm Formatted numeric output step by step in the F# programming language
You may also check:How to resolve the algorithm Sum of squares step by step in the Golfscript programming language
You may also check:How to resolve the algorithm Comments step by step in the Ursa programming language