# Minimum swaps for bracket balancing in scala

Scala program for Minimum swaps for bracket balancing. Here problem description and explanation.

``````import scala.collection.mutable._;
/*
Scala program for
Minimum swaps for bracket balancing
*/
class Test()
{
def swapBalancingCount(text: String): Unit = {
var n: Int = text.length();
if (n == 0)
{
return;
}
// Auxiliary variables
var bracketCount: Int = 0;
var index: Int = 0;
var sum: Long = 0;
var data: Array[Char] = text.toCharArray();
// This is collecting the all open bracket character position.
var openBracket: ArrayBuffer[Int] = new ArrayBuffer[Int]();
var i: Int = 0;
// This loop are collecting position of all open bracket.
// And calculates the number of open and close brackets.
while (i < n)
{
if (data(i) == '[')
{
openBracket += i;
bracketCount += 1;
}
else
{
bracketCount -= 1;
}
i += 1;
}
if (bracketCount != 0)
{
// Means open and close brackets not same
return;
}
// Reset bracket counter
bracketCount = 0;
i = 0;
while (i < n)
{
if (data(i) == '[')
{
bracketCount += 1;
index += 1;
}
else if (data(i) == ']')
{
bracketCount -= 1;
}
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: Char = data(i);
data(i) = data(openBracket(index));
data(openBracket(index)) = t;
// Reset counter
bracketCount = 1;
// Position to next open bracket
index += 1;
}
i += 1;
}
// Balancing bracket
var ans: String = new String(data);
// Display given and calculated results
println(" Given text     : " + text);
println(" Results text   : " + ans);
println(" Swaps  : " + sum);
}
}
object Main
{
def main(args: Array[String]): Unit = {
var task: Test = new Test();
var text: String = "]]][[[[]";
/*
]]][[[[]  <-  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
*/
}
}``````

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.