# Thread: Rand function for array of chars

1. ## Rand function for array of chars

Is there anyway to randomnly choose letters from an array of given chars and then continue to randomnly pick more removing the last picked one?

Say:

Code:
`char club[8] = {'J','Q','K','A','J','Q','K','A'};`
It picks Jack (J) and then removes it from the list and continues to randomnly pick the others.

2. What are you having problems with? Post some code, your algorithm sounds good. I'm guessing you're just having trouble with some part of the implementation.

3. I think the simpleast way will be shuffle the array in the beginning, and when just read it one by one in the regular order

4. The algorithm is easy, I just don't know how to exactly use the rand function to deal with characters, i have only used it with numbers...

say:

ran () % 10 picks a random number from 1 to 10

how do you get it to pick a random character that is not a number from an array?

5. Well let's see, array indexes are actually number right?
Therefore...
Code:
```char c[] = { 'A', 'B', 'C', 'D', 'E', 'F' };
int max_index = sizeof(c);
int rnd_idx;
char result;

do
{
rnd_idx = rand()&#37;max_index;   /* Pick random index */
} while( c[rnd_idx] == '\0' );
result = c[ rnd_idx ];
c[ rnd_idx ] = '\0';   /* Mark the character as got */```
Not the most efficient way to do it, but it will work...

6. Thanks, will try that.

7. Originally Posted by xuftugulus
Not the most efficient way to do it, but it will work...
Which is why, as someone mentioned previously, one should just pre-shuffle the array, decrement a last index, and grab the last element.

8. It turns out that premature optimization is the root of all evil.