Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Choosing a random element from a list of tuples C#

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)’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there any way to make this work?

Thanks in advance!

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading