简体   繁体   中英

How do I know if elements from one list appear in another?

I need to know a efficient way in C# to determine if elements in listX appear in listY. I can do it in an (maybe) inefficient way by written alot of loops but I guess there is a must faster way (lambda expressions?)

I'm jumping from Java to C# so alot of things are new to me. I'm writting a Tic Tac Toe game and have 7 scenarios to win a game.:

    private int[] scenarioA = {1, 2, 3}; 
    private int[] scenarioB = {4, 5, 6}; 
    private int[] scenarioC = {7, 8, 9}; 
    private int[] scenarioD = {3, 5, 7}; 
    private int[] scenarioE = {1, 4, 7}; 
    private int[] scenarioF = {2, 5, 8}; 
    private int[] scenarioG = {3, 6, 9};

Whenever a player hits a button i'm saving the number of the cell in clickedCellsO or ClickedCellsX. After hitting 5 cells i need to check if there is a winner so i need to loop through clickedCellsO or ClickedCellsX to see if it has the combination of one of the scenarios.

List<int> clickedCellsO = new List<int>();
List<int> clickedCellsX = new List<int>();

Can anybody give me an advice how to do this without using a bench of loops?

Thanks in advance

You can just use LINQ:

var winningConditions = new[] {
    scenarioA,
    scenarioB,
    scenarioC,
    // ...
};

var hasPlayerOWon = winningConditions.Any(placements => placements.All(clickedCellsO.Contains));
var hasPlayerXWon = winningConditions.Any(placements => placements.All(clickedCellsX.Contains));

You could use a List<List<int>> to store the winning combinations, and then check use some System.Linq methods to determine if the player's combination contains All() of the items of Any() of the winning combinations.

The code in the method below basically says, "return true if any of the winning combinations has all of it's items contained in the player's combination, otherwise return false" .

private static readonly List<List<int>> WinningCombinations = new List<List<int>>
{
    new List<int> {1, 2, 3}, new List<int> {1, 5, 9},
    new List<int> {1, 4, 7}, new List<int> {2, 5, 8},
    new List<int> {3, 5, 7}, new List<int> {3, 6, 9},
    new List<int> {4, 5, 6}, new List<int> {7, 8, 9},
};

private static bool IsAWinner(List<int> playerCombination)
{
    return WinningCombinations.Any(winningCombo => 
        winningCombo.All(playerCombination.Contains));
}

In use you might do something like:

if (IsAWinner(clickedCellsX))
{
    // Player 'X' wins!
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM