I am trying a problem where we are given binary string of length N(<10^5), and we are allowed exactly X(<10^5) flips on it, we are asked how many different string is p
This is in c#. See if it helps.
static class Program
{
static void Main(string[] args)
{
string bnryStr = "111111";
int x = 4;
//here in this string merely the poistions of the binary string numbers are placed
//if the binary string is "1111111", this fakeStr will hold "0123456"
string fakeStr = String.Empty;
for (int i = 0; i < bnryStr.Length; i++)
{
fakeStr += i.ToString();
}
char[] arr = fakeStr.ToCharArray();
// gets all combinations of the input string altered in x ways
IEnumerable> result = Combinations(arr, x);
// this holds all the combinations of positions of the binary string at which flips will be made
List places = new List();
foreach (IEnumerable elements in result)
{
string str = string.Empty;
foreach (var item in elements)
{
str += item;
}
places.Add(str);
}
List results = GetFlippedCombos(bnryStr, places);
Console.WriteLine("The number of all possible combinations are: " + results.Count);
foreach (var item in results)
{
Console.WriteLine(item);
}
Console.Read();
}
///
/// Gets a list of flipped strings
///
/// binary string
/// List of strings containing positions of binary string at which flips will be made
/// list of all possible combinations of flipped strings
private static List GetFlippedCombos(string bnryStr, List placeList)
{
List rtrnList = new List();
foreach (var item in placeList)
{
rtrnList.Add(Flip(bnryStr, item));
}
return rtrnList;
}
///
/// Flips all the positions (specified in 'places') of a binary string from 1 to 0 or vice versa
///
/// binary string
/// string holding the position values at which flips are made
/// a flipped string
private static string Flip(string bnryStr, string places)
{
StringBuilder str = new StringBuilder(bnryStr);
foreach (char place in places)
{
int i = int.Parse(place.ToString());
char ch = str[i];
str.Replace(ch, '0' == ch ? '1' : '0', i, 1);
}
return str.ToString();
}
///
/// Gets all combinations of k items from a collection with n elements
///
/// collection having n elements
/// no of combinations
/// all possible combinations of k items chosen from n elements
private static IEnumerable> Combinations(this IEnumerable elements, int k)
{
if (k == 0)
{
return new[] { new T[0] };
}
else
{
IEnumerable elements1 = elements as IList ?? elements.ToList();
IEnumerable> enumerable = elements1.SelectMany((e, i) =>
{
IEnumerable enumerable1 = elements as IList ?? elements1.ToList();
return enumerable1.Skip(i + 1).Combinations(k - 1).Select(c => (new[] { e }).Concat(c));
});
return enumerable;
}
}
}
Result:
Binary String: 111111
No. of Flips: 4
The number of all possible combinations are: 15
000011
000101
000110
001001
001010
001100
010001
010010
010100
011000
100001
100010
100100
101000
110000