# Minimum swaps for bracket balancing in node js

Js program for Minimum swaps for bracket balancing. Here problem description and other solutions.

``````/*
Node JS program for
Minimum swaps for bracket balancing
*/
class Test
{
swapBalancingCount(text)
{
var n = text.length;
if (n == 0)
{
return;
}
// Auxiliary variables
var bracketCount = 0;
var index = 0;
var sum = 0;
var data = (text).split('');
// This is collecting the all open bracket character position.
var openBracket = [];
// This loop are collecting position of all open bracket.
// And calculates the number of open and close brackets.
for (var i = 0; i < n; ++i)
{
if (data[i] == '[')
{
openBracket.push(i);
bracketCount++;
}
else
{
bracketCount--;
}
}
if (bracketCount != 0)
{
// Means open and close brackets not same
return;
}
// Reset bracket counter
bracketCount = 0;
for (var i = 0; i < n; ++i)
{
if (data[i] == '[')
{
bracketCount++;
index++;
}
else if (data[i] == ']')
{
bracketCount--;
}
if (bracketCount < 0)
{
// Calculate number of swap operations
// required to move to block brackets.
// Here open break position will use
sum += (openBracket[index] - i);
// Swap element
var t = data[i];
data[i] = data[openBracket[index]];
data[openBracket[index]] = t;
// Reset counter
bracketCount = 1;
// Position to next open bracket
index++;
}
}
// Balancing bracket
var ans = data.join("");
// Display given and calculated results
console.log(" Given text     : " + text);
console.log(" Results text   : " + ans);
console.log(" Swaps  : " + sum);
}
}

function main()
{
var text = "]]][[[[]";
/*
]]][[[[]  <-  text
--
]][][[[]  ➀ Swap position 2-3
--
][]][[[]  ➁ Swap position 1-2
--
[]]][[[]  ➂ Swap position 0-1
--
[]][][[]  ➃ Swap position 3-4
--
[][]][[]  ➄ Swap position 2-3
--
[][][][]  ➅ Swap position 4-5
----------------------------
Number of swap : 6
*/
text = "][[][]";
/*
][[][]  <-  text
--
[][][]  ➀ Swap position 0-1

----------------------------
Number of swap : 1
*/
}
main();``````

Output

`````` Given text     : ]]][[[[]
Results text   : [][][][]
Swaps  : 6
Given text     : ][[][]
Results text   : [][][]
Swaps  : 1``````

## Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.