我有个问题。我试图实现Zag算法(钢轨栅栏).

我的代码如下所示:
int n = 3;
int j = 0;
int charCounter = 0;
char[,] chars = new char[n, input.Length]; //array to store chars
while(charCounter <= input.Length) //char counter related to input string
{
if (charCounter >= input.Length)
break;
chars[nCounter++, j++] = input[charCounter++]; //goes n = 0 => 1 => 2 => 3
if (nCounter == n)
for (int i = nCounter; i >= 0; i--) //from this loop, i want to go n => 3 => 2 => 1 => 0 etc
{
if (charCounter >= input.Length)
break;
if (nCounter == 0)
continue;
chars[--nCounter, j++] = input[charCounter++];
} //here i get an exception
}从上面的示例中我得到了一个Exception
System.IndexOutOfRangeException:“索引超出了数组的范围。”
我的问题是,我的代码中哪里有错误?
当我从以下位置更改嵌套for循环中的行时:chars[--nCounter, j++] = input[charCounter++];
对此:chars[nCounter--, j++] = input[charCounter++];
我没有任何异常,但char数组如下所示:
char[0,0] = input[0];
char[1,1] = input[1];
char[2,2] = input[2];
char[2,3] = input[3]; //that is wrong, should be [1,3]
char[1,4] = input[4];
//and so on..它应该是这样的:
char[0,0] = input[0];
char[1,1] = input[1];
char[2,2] = input[2];
char[1,3] = input[3]; //here the diffrence
char[0,4] = input[4];
//and so on..谢谢您对我的代码进行改进的建议!
编辑:基于评论的,我做了一些改进:
for(int i = 0; i <= input.Length; i++)
chars[i % n, i] = input[i];按行迭代很好,现在我需要解决列问题。
发布于 2019-03-05 14:01:10
最难的部分是产生升华,然后减少部分。由于没有容易的数学解来生成一个数字序列,从0增加到N,然后下降到0。
我们必须手动生成地图:
从0开始,直到我们到达N-1,然后下降到0。每一次都重复一遍。
对于TestInput = "abcdef“和level = 3,我们有:
input a b c d e f
index 0 1 2 1 0 1然后我们按索引对这2进行分组和排序:
index inputs
0 a,e
1 b,d
2 c 吃完Select后的早午餐:{a,e,b,d,c}。一个简单的字符串构造函数,它接受char数组,我们有结果字符串。
static string ZigZag(string input, int level)
{
var indexMap = new List<int>();
var tempIndex = 0; bool isIncreasing = true;
for (int i = 0; i < input.Length; i++)
{
indexMap.Add(tempIndex);
if (isIncreasing)
{ // Zig
tempIndex++;
}
else
{ // Zag
tempIndex--;
}
if (tempIndex == level - 1)
{
isIncreasing = false;
}
if (tempIndex == 0)
{
isIncreasing = true;
}
}
var result =
input.Select((c, i) => new { Char = c, Index = indexMap[i] })
.GroupBy(x => x.Index)
.OrderBy(g => g.Key)
.SelectMany(x => x.Select(y => y.Char))
.ToArray();
return new string(result);
}https://stackoverflow.com/questions/55003316
复制相似问题