[英]Find number of occurrences and positional matches of 2 arrays
我正在努力處理 C# 中的一些邏輯代碼......我想檢查一個數組的元素是否與另一個數組的元素在同一個 position 中,如果不是,它是否出現在其他數組中。 讓我舉幾個例子(字母是 colors White、Blue、Red、Green 的縮寫):
array1: W B G G
array2: W R G B
----------------
2 exact matches: W in position 1 and G in position 3
1 other occurrences: B (position 2 in array1 and position 4 in array2)
array1: W R B B
array2: R W G G
----------------
should return:
0 exact matches
2 other occurrences: W (position 1 in array1 and position 2 in array2)
R (position 2 in array1 and position 1 in array2)
array1: B W W B
array2: R W R R
----------------
should return:
1 exact match: W in position 2
0 other occurrences
array1: G R R B
array2: R R R B
----------------
should return:
3 exact matches: R in position 2 and 3, and B in position 4
0 other occurrences
所以要清楚:我只想知道匹配的數量和出現的數量,而不是匹配的確切位置。 這可以使用 LINQ 和 arrays 來完成嗎? 還是有“更簡單”的方法?
睡個好覺后,我自己找到了解決方案:-)
// 2 example arrays
char[] List1 = { 'B', 'W', 'W', 'B' };
char[] List2 = { 'R', 'W', 'B', 'W' };
int BlackPin = 0;
int WhitePin = 0;
// First check all exact matches
for (int i = 0; i < List2.Length; i++)
{
// check if there is an exact match
if (List2[i] == List1[i])
{
// Black pin, as it is found, and on the exact place
BlackPin++;
List1[i] = '!';
continue;
}
}
// Now check all non-exact matches
for (int i = 0; i < List2.Length; i++)
{
int Index = Array.IndexOf(List1, List2[i]);
if (Index == -1)
{
// Nothing found, so moving to the next
continue;
}
// White pin, as it is found, but not on the exact place
List1[Index] = '!';
WhitePin++;
}
Console.WriteLine($"# exact matches: {BlackPin}");
Console.WriteLine($"# non-exact matches: {WhitePin}");
你怎么看? 有沒有更簡單的方法來做到這一點?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.