2

我一直在寻找有关如何执行此操作的任何答案。

我想要做的是,取一个数字数组,例如{1, 3, 5, 6, 8, 7, 6 ,5, 3, 1}(但它将使用用户输入)并找到这些数字的副本,这些数字被镜像并返回仅在所述数组的一个实例中涉及多少索引。

我知道 C# 的基础知识,但无法掌握这项任务。不,这不是家庭作业。这是我自己的项目,以进一步提高我的知识。

我目前不在我的部分代码周围,但非常感谢任何人可以给我的任何帮助/建议。

4

2 回答 2

2
int[] array =  {1, 3, 5, 6, 8, 7, 6 ,5, 3, 1};

//holds left index of mirrored pair, you can easily find the right one
var mirroredIndexes = new List<int>();
var length = array.Length;

for (int i = 0; i < length / 2; i++)
{
    if(array[i] == array[length - i - 1])
        mirroredIndexes.Add(i);
}

mirroredIndexes.ForEach(Console.WriteLine);
Console.WriteLine ("total of {0} mirrored pairs ({1})", 
                       mirroredIndexes.Count, 
                       string.Join(", ", mirroredIndexes.Select(i => array[i])));

打印下一个索引:

0
1
2
3
total of 4 mirrored pairs (1, 3, 5, 6)
于 2013-05-31T06:35:52.587 回答
1

我想这就是你所追求的。这将返回匹配索引的列表。例如。第一个 == 最后一个,第二个 == 倒数第二个,第三个 == 倒数第三个

var matches = new List<Tuple<int, int>>();

var array = new [] { 0, 1, 2, 3, 4, 5, 3, 2, 1, 0 };

if (array.Length % 2 != 0)
    throw new Exception("Array must have an even amount of elements");

for (int i = 0; i < array.Length / 2; i++)
{
    if (array[i] == array[array.Length - 1 - i])
    {
        matches.Add(new Tuple<int, int>(i, array.Length - 1 - i));
    }
}

var firstMatchingIndex1 = matches[0].Item1;
// This will be 0

var firstMatchingIndex2 = matches[0].Item2;
// This will be 9

您可以更进一步,使用自定义类,并捕获匹配的实际值(例如,index1 为 1,index2 为 8,值为 1。

于 2013-05-31T06:35:41.933 回答