I have 35 chars and i need to randomly select 20 of them. Can you tell me a random function and/or selecting from an array?
Thanks ~rab
I have 35 chars and i need to randomly select 20 of them. Can you tell me a random function and/or selecting from an array?
Thanks ~rab
I'd look up the functions rand() and srand(), you can use them with the modulus operator to (pseudo-)randomly generate a number only between 0 and 35.
Well, though there are better datastructures to use that allow you to get a random selection of your data, if you only wanted an array. Then consider filling a 2D array that holds the data and a picked flag
Then use the rand() function mod the size of your array. Take that indexed character, flag it as picked. Then repeat, taking only values that haven't been picked.Code:h e l l o w o r l d ! 1 1 1 1 1 1 1 1 1 1 1 1
There are a bunch of ways to do this, some are better than others. This was just off the top of my head.
Last edited by SlyMaelstrom; 02-11-2006 at 03:42 AM.
Sent from my iPadŽ
i dont want the numbers between 1-35. I need something to store a 35 char long string (dffd872jahdf0d9g734...ect like that). So i chose an array.
You store the characters in a char array like you did. But when you want to access a certain part of the array you need to use a number like MyArray[7]
So you need numbers. I could give you more of a description but without code examples I sometimes find it difficult to explain and if I give you the code example, it would pretty much be the code to do it hehe, which gives it away.
So basically you generate a random number between 0 and 35 (34 really) and then put that number in the squre brackets, and you access whatever number is chosen at random, which will give the character stored at that location of the array.
call srand
put the numbers 0-34 in an vector/deque/array
call random_shuffle on your vector
use the first 20 number in the vector as your indexes for your string/char array
Thanks.