我一直在尋找一些時間,現在就如何做到這一點的任何答案。如何查找鏡像副本的所有實例?
我想要做的是,採取一系列的數字,例如, {1, 3, 5, 6, 8, 7, 6 ,5, 3, 1}
(但它將使用用戶輸入),並找到鏡像的這些數字的重複項,並返回該數組的一個實例中涉及的索引數。
我知道C#的基礎知識,但無法掌握此任務。不,這不是功課。這是我自己的項目,以進一步提高我的知識。
我目前沒有圍繞這個部分的代碼,但真的很感謝任何人可以給我的任何幫助/建議。
我一直在尋找一些時間,現在就如何做到這一點的任何答案。如何查找鏡像副本的所有實例?
我想要做的是,採取一系列的數字,例如, {1, 3, 5, 6, 8, 7, 6 ,5, 3, 1}
(但它將使用用戶輸入),並找到鏡像的這些數字的重複項,並返回該數組的一個實例中涉及的索引數。
我知道C#的基礎知識,但無法掌握此任務。不,這不是功課。這是我自己的項目,以進一步提高我的知識。
我目前沒有圍繞這個部分的代碼,但真的很感謝任何人可以給我的任何幫助/建議。
我認爲這就是你所追求的。這將返回匹配索引的列表。例如,第一==最後,第二==倒數第二,第三==倒數第三
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
你可以走的更遠,使用自定義類,並捕獲匹配的實際值(例如,索引1是1,索引2是8和值是1。
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)
請你能給預期的結果,我仍然不明確 –
定義/解釋/的「鏡像複製」的樣品會給這個問題是一個機會...... –
你期望返回'1,3,5,6'嗎?即相同索引中的相同整數在顛倒時是相同的? –