34 lines
1 KiB
Text
34 lines
1 KiB
Text
import ballerina/io;
|
|
import ballerina/random;
|
|
|
|
function isBalanced(string s) returns boolean {
|
|
if s == "" { return true; }
|
|
int countLeft = 0; // number of left brackets so far unmatched
|
|
foreach var c in s {
|
|
if c == "[" {
|
|
countLeft += 1;
|
|
} else if countLeft > 0 {
|
|
countLeft -= 1;
|
|
} else {
|
|
return false;
|
|
}
|
|
}
|
|
return countLeft == 0;
|
|
}
|
|
|
|
public function main() {
|
|
io:println("Checking examples in task description:");
|
|
var brackets = ["", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]"];
|
|
foreach string b in brackets {
|
|
io:print((b != "") ? b : "(empty)");
|
|
io:println("\t ", isBalanced(b) ? "OK" : "NOT OK");
|
|
}
|
|
io:println("\nChecking 7 random strings of brackets of length 8:");
|
|
foreach int i in 1...7 {
|
|
string s = "";
|
|
foreach int j in 1...8 {
|
|
s += random:createIntInRange(0, 2) == 0 ? "[" : "]";
|
|
}
|
|
io:println(s, " ", isBalanced(s) ? "OK" : "NOT OK");
|
|
}
|
|
}
|