【问题标题】:Find number of occurrences and positional matches of 2 arrays查找 2 个数组的出现次数和位置匹配
【发布时间】:2022-01-21 02:05:34
【问题描述】:

我正在努力处理 C# 中的一些逻辑代码... 我想检查一个数组的元素是否与另一个数组的元素在同一位置,如果不是,它是否出现在其他数组中。 让我举几个例子(这些字母是白色、蓝色、红色、绿色的缩写):

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 和数组来完成吗?还是有“更简单”的方法?

【问题讨论】:

  • 到目前为止你有什么?

标签: c# arrays linq comparison


【解决方案1】:

睡了个好觉后我自己找到了解决办法:-)

// 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}");

你怎么看?有更简单的方法吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-10
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多