2

I have a homework assignment in which I've been tasked with randomizing 5 cards out of my array cardArray of type SuperCard using the Random class with all values returned as an array of type SuperCard. What I'm getting hung up on is how to cast my custom type SuperCard to int in order to use the Next() method from the Random class. What I have thus far is ;

SuperCard[] hand = new SuperCard[5];
for (int index1 = 0; index1 <= 4; index1++)
{
    hand[index1] = rand.Next(cardArray[0], cardArray[51]);//cant figure out how to cast this   
}

If I attempt to cast rand.Next((int)cardArray[0],(int)cardArray[51]); I get the error "Cannot convert type SuperCard to int". I can convert the array to an integer array but not back again.

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
Mumbles
  • 23
  • 2
  • 4
    How about pick a random number from 0 - 51, and retrieve the `SuperCard` in `cardArray` with this random number? – Prisoner Nov 03 '17 at 02:01
  • randomizing raw result should be always a number, from that number you can map (lookup for) any kind of object. Just think it simply. That's why they don't put all guests (human bodies?) in a big globe and rotate them in there to find who wins a lotto, instead they put in all small balls marked with number and later find out who is mapped with the chosen number to give the prize. – King King Nov 03 '17 at 02:14
  • What is the data structure of SuperCard? –  Nov 03 '17 at 03:31
  • You can achieve what you trying to do by using implicit conversion from int as shown in [linked duplicate](https://stackoverflow.com/questions/1407689/how-do-i-provide-custom-cast-support-for-my-class). Note that it unlikely useful for your assignment - see explanation provided in good Peter's answer (if not enough there are plenty similar https://www.bing.com/search?q=c%23%20take%20random%20cards discussion all sorts of picking numbers/cards from list). – Alexei Levenkov Nov 03 '17 at 04:01

1 Answers1

1

Your immediate issue is addressed by using the indexes of the cardArray for your random number, and not the elements themselves. I.e.:

hand[index1] = cardArray[rand.Next(0, cardArray.Length)];

Note that the range of indexes valid for cardArray are used for the random number, and the number returned is then used to actually index the cardArray to select an actual card.

A couple of other points:

  • There is a Next(int) overload for the method that assumes the lower bound of the range is 0. So you could use rand.Next(cardArray.Length) instead.
  • The code as you have it now can (and eventually will) pick the same card more than once. What you really want to do is shuffle the array and then just select the first five elements. See e.g. Best way to randomize an array with .NET for dealing with this next obstacle in your code.
Peter Duniho
  • 68,759
  • 7
  • 102
  • 136