Hi,
I have a small algorithm which replaces the position of characters in a String:
class Program
{
static void Main(string[] args)
{
String pairSwitchedStr = pairSwitch("some short sentence");
Console.WriteLine(pairSwitchedStr);
Console.ReadKey();
}
private static String pairSwitch(String str)
{
StringBuilder pairSwitchedStringBuilder = new StringBuilder();
for (int position = 0; position + 1 < str.Length; position += 2)
{
pairSwitchedStringBuilder.Append((char)str[position + 1]);
pairSwitchedStringBuilder.Append((char)str[position]);
}
return pairSwitchedStringBuilder.ToString();
}
}
I would like to make it as generic as possible, possibly using Generics. What I'd like to have is something which works with:
- Anything that is built up using a list of instances.
- Including strings, arrays, linked lists
I suspect that the solution must use generics as the algorithm is working on a list of instances of T (there T is ... something). Version of C# isn't of interest, I guess the solution will be nicer if features from C# version >2.0 is used.
I ended up with: (Where I fixed the error in the above code, it didn't handle odd lengths correctly)
private static IEnumerable<T> switchSubstitutionCipher<T>(IEnumerable<T> input)
{
bool even = false;
T lastItem = default(T);
foreach (T element in input)
{
if (even) {
yield return element;
yield return lastItem;
}
even = !even;
lastItem = element;
}
if (even)
yield return lastItem;
}