Minimum swaps for bracket balancing in c#
Csharp program for Minimum swaps for bracket balancing. Here more information.
// Include namespace system
using System;
using System.Collections.Generic;
/*
Csharp program for
Minimum swaps for bracket balancing
*/
public class Balancing
{
public void swapBalancingCount(String text)
{
var n = text.Length;
if (n == 0)
{
return;
}
// Auxiliary variables
var bracketCount = 0;
var index = 0;
var sum = 0;
char[] data = text.ToCharArray();
// This is collecting the all open bracket character position.
var openBracket = new List < int > ();
// 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.Add(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 = new String(data);
// Display given and calculated results
Console.WriteLine(" Given text : " + text);
Console.WriteLine(" Results text : " + ans);
Console.WriteLine(" Swaps : " + sum.ToString());
}
public static void Main(String[] args)
{
var task = new Balancing();
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
*/
task.swapBalancingCount(text);
text = "][[][]";
/*
][[][] <- text
--
[][][] ➀ Swap position (0,1)
----------------------------
Number of swap : 1
*/
task.swapBalancingCount(text);
}
}
Output
Given text : ]]][[[[]
Results text : [][][][]
Swaps : 6
Given text : ][[][]
Results text : [][][]
Swaps : 1
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.
New Comment