gpt4 book ai didi

c# - 之字形,IndexOutOfRangeException

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:37:39 25 4
gpt4 key购买 nike

我有一个问题。我尝试实现 Zig-Zag 算法 ( Rail Fence )。

enter image description here

我的代码如下所示:

    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: 'Index was outside the bounds of the array.'

我的问题是,我的代码哪里有错误?

当我从这里更改嵌套 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];

按行迭代非常好,现在我需要解决列问题

最佳答案

有一种方法可以生成一个从 0 递增到 N 递减回到 0 的数列。
考虑以下几点:
对于 N=2 ,序列是 {0,1,0,1 ..}
对于 N=3 ,序列是 {0,1,2,1,0,1,2 ..}

如果我们有一个像这样的序列,我们可以枚举它们,模数为 N+1** :
对于 N=3 ,{0,1,2,1}
对于 N=4 ,{0,1,2,3,2,1}

要生成这个序列,我们必须:从0数到N。然后从 N-1 数到 0+1。并将两者结合在一起。

static int[] GenerateIncreasingDecreasing(int level)
{
var tempRange = Enumerable.Range(0, level).ToArray();
var indexMap = (tempRange.Length < 2) ?
tempRange :
tempRange.Concat(Enumerable.Range(1, level-2).Reverse());
return indexMap.ToArray();
}

那么 Crypt 函数将是:

static string ZigZag(string input, int level)
{
var indexMap = GenerateIncreasingDecreasing(level);
var result =
input.Select((c, i) => new {
Char = c,
Index = indexMap[i % ((level>2)?(level + 1):level)]
})
.GroupBy(x => x.Index)
.OrderBy(g => g.Key)
.SelectMany(x => x.Select(y => y.Char))
.ToArray();

return new string(result);
}

** :对于 N < 2,没有重复。所以模一定是N。

关于c# - 之字形,IndexOutOfRangeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55003316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com