Home > Enterprise >  Choosing a random element from a list of tuples C#
Choosing a random element from a list of tuples C#

Time:01-11

I'm quite new to programming and I am trying to add a random bot move to a small game I've made. My idea was to make a list of tuples of all of the legal moves and then pick a random tuple from that list to then deconstruct and change a value in a 2D-array. I've looked all over the internet and found a way to make a list of tuples (I think), but couldn't manage to pick a random element from that list.

This is what I tried:

List<Tuple<int, int>> legalMoves; // To make the list of tuples

// Later on in a double for-loop that iterates through all the rows and columns of the 2D-array I check if that certain row and column combination is a legal move and then add it to the list like so:

legalMoves.Add(Tuple.Create(row, col));

//Then in a different method I try to pick a random element from that list (this doesn't work)

Random random = new Random();
int randomIndex = random.Next(legalMoves.Count);
(int, int) randomMove = legalMoves[randomIndex];

It gives the following error on the last line: Error CS0029 Cannot implicitly convert type 'System.Tuple<int, int>' to '(int, int)'

Is there any way to make this work?

Thanks in advance!

CodePudding user response:

The syntax (int, int) defines a ValueTuple<int,int> not a Tuple<int,int>. Change the list definition to :

List<ValueTuple<int, int>> legalMoves;

and Tuple.Create to ValueTuple.Create

  • Related