我在每次迭代时都有这个方法,字符串的奇数字符被组合并包装到它的开始,偶数字符被包装到末尾。source
为源字符串。count
为迭代次数。
public static string Shuffle(string source, int count)
{
for (long i = 0; i < count; i++)
{
source = string.Join(string.Empty, source.Where((v, j) => j % 2 == 0))
+ string.Join(string.Empty, source.Where((v, j) => j % 2 != 0));
}
return source;
}
一切工作正常,但当count = int.MaxValue
计算太长。如何改变算法来加快计算速度?
字符串是不可变的,您可以通过使用字符数组来避免在循环中创建字符串(以C语言的方式)。Shuffle2("ABCDEFGHIKKLMNOP", int.MaxValue)花费了67秒。但是这是浪费能量,这个算法是周期性的,周期长度为length(text)(偶数字符串长度)。Shuffle("ABCD", x)将产生与Shuffle("ABCD", x+4)相同的结果
public static string Shuffle2(string source, int count)
{
char[] text = source.ToCharArray();
char[] buffer = new char[source.Length];
for (long i = 0; i < count; i++)
{
int j = 0;
for (int k = 0; k < text.Length; k += 2, j++) buffer[j] = text[k]; // Odd characters at index 0, 2, 4, ...
for (int k = 1; k < text.Length; k += 2, j++) buffer[j] = text[k]; // Place even characters after the odd characters in the buffer.
buffer.CopyTo(text, 0); // Maybe there is a tricky exchange in your original array where you don't need a buffer.
}
return new string(text);
}