How to resolve the algorithm Balanced brackets step by step in the JavaScript programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Balanced brackets step by step in the JavaScript 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 JavaScript programming language
1. Overview
The provided code snippet contains several functions and a main program that generate and evaluate strings of brackets ([
and ]
) to determine if they are balanced.
2. Function: shuffle
- Takes a string as input.
- Splits the string into an array of characters.
- Randomly shuffles the characters in the array.
- Re-joins the shuffled characters into a string.
3. Function: isBalanced
- Takes a string as input.
- Iteratively removes pairs of matching open and closed brackets (
[]
) from the string until no more pairs are found. - If the final string is empty, the input string is considered balanced.
4. Main Program
- Generates 20 random strings of brackets and evaluates their balance using
isBalanced
. - Logs the results to the console.
5. Additional Functions (Supplied Examples)
isStringBalanced
: Checks if a string is balanced, returning a boolean.generate
: Generates a random string of brackets of a specified length.
6. Additional Functions (Balanced Brackets)
firstUnbalancedBracket
: Takes a string of brackets and returns the index of the first unbalanced bracket (orNothing
if no unbalanced bracket is found).main
: Generates a series of random strings of brackets and logs whether they are balanced or not.randomBrackets
: Generates a random string of brackets of a given length.
7. Generic Functions
Just
andNothing
: Used for representing Maybe values (either a value orNothing
).enumFromTo
: Generates a list of integers within a specified range.maybe
: Used to provide a default value if a value isNothing
.
8. Usage
The code snippets demonstrate how to generate and check the balance of strings of brackets. These concepts are commonly used in computer science for evaluating the validity of expressions and code structures.
Source code in the javascript programming language
function shuffle(str) {
var a = str.split(''), b, c = a.length, d
while (c) b = Math.random() * c-- | 0, d = a[c], a[c] = a[b], a[b] = d
return a.join('')
}
function isBalanced(str) {
var a = str, b
do { b = a, a = a.replace(/\[\]/g, '') } while (a != b)
return !a
}
var M = 20
while (M-- > 0) {
var N = Math.random() * 10 | 0, bs = shuffle('['.repeat(N) + ']'.repeat(N))
console.log('"' + bs + '" is ' + (isBalanced(bs) ? '' : 'un') + 'balanced')
}
console.log("Supplied examples");
var tests = ["", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]"];
for (var test of tests)
{
console.log("The string '" + test + "' is " +
(isStringBalanced(test) ? "" : "not ") + "OK.");
}
console.log();
console.log("Random generated examples");
for (var example = 1; example <= 10; example++)
{
var test = generate(Math.floor(Math.random() * 10) + 1);
console.log("The string '" + test + "' is " +
(isStringBalanced(test) ? "" : "not ") + "OK.");
}
function isStringBalanced(str)
{
var paired = 0;
for (var i = 0; i < str.length && paired >= 0; i++)
{
var c = str[i];
if (c == '[')
paired++;
else if (c == ']')
paired--;
}
return (paired == 0);
}
function generate(n)
{
var opensCount = 0, closesCount = 0;
// Choose at random until n of one type generated
var generated = "";
while (opensCount < n && closesCount < n)
{
switch (Math.floor(Math.random() * 2) + 1)
{
case 1:
opensCount++;
generated += "[";
break;
case 2:
closesCount++;
generated += "]";
break;
default:
break;
}
}
// Now pad with the remaining other brackets
generated +=
opensCount == n ? "]".repeat(n - closesCount) : "[".repeat(n - opensCount);
return generated;
}
(() => {
'use strict';
// ---------------- BALANCED BRACKETS ----------------
// firstUnbalancedBracket :: String -> String -> Maybe Int
const firstUnbalancedBracket = brackets =>
haystack => {
const [openBracket, closeBracket] = [...brackets];
const go = (xs, iDepth, iCharPosn) =>
// iDepth: initial nesting depth (0 = closed)
// iCharPosn: starting character position
0 < xs.length ? (() => {
const
h = xs[0],
tail = xs.slice(1),
iNext = iDepth + (
brackets.includes(h) ? (
openBracket === h ? (
1
) : -1
) : 0
);
return 0 > iNext ? (
Just(iCharPosn) // Unmatched closing bracket.
) : 0 < tail.length ? go(
tail, iNext, 1 + iCharPosn
) : 0 !== iNext ? (
Just(iCharPosn)
) : Nothing();
})() : 0 !== iDepth ? (
Just(iCharPosn)
) : Nothing();
return go([...haystack], 0, 0);
};
// ---------------------- TEST -----------------------
// main :: IO ()
const main = () => {
const
intPairs = 6,
strPad = ' '.repeat(4 + (2 * intPairs));
console.log(
enumFromTo(0)(intPairs)
.map(pairCount => {
const
stringLength = 2 * pairCount,
strSample = randomBrackets(stringLength);
return "'" + strSample + "'" +
strPad.slice(2 + stringLength) + maybe('OK')(
iUnMatched => 'problem\n' +
' '.repeat(1 + iUnMatched) + '^'
)(
firstUnbalancedBracket('[]')(strSample)
);
}).join('\n')
);
};
// Int -> String
const randomBrackets = n =>
enumFromTo(1)(n)
.map(() => Math.random() < 0.5 ? (
'['
) : ']').join('');
// --------------------- GENERIC ---------------------
// Just :: a -> Maybe a
const Just = x => ({
type: 'Maybe',
Nothing: false,
Just: x
});
// Nothing :: Maybe a
const Nothing = () => ({
type: 'Maybe',
Nothing: true,
});
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = m =>
n => !isNaN(m) ? (
Array.from({
length: 1 + n - m
}, (_, i) => m + i)
) : enumFromTo_(m)(n);
// maybe :: b -> (a -> b) -> Maybe a -> b
const maybe = v =>
// Default value (v) if m is Nothing, or f(m.Just)
f => m => m.Nothing ? (
v
) : f(m.Just);
// ---
return main();
})();
You may also check:How to resolve the algorithm SHA-256 step by step in the AutoHotkey programming language
You may also check:How to resolve the algorithm Circular primes step by step in the Go programming language
You may also check:How to resolve the algorithm Animation step by step in the Rust programming language
You may also check:How to resolve the algorithm Loops/Break step by step in the E programming language
You may also check:How to resolve the algorithm Roman numerals/Encode step by step in the Icon and Unicon programming language