how to choose a random string of character in c++

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Noss
    New Member
    • Dec 2009
    • 1

    how to choose a random string of character in c++

    like if i have a list of items and each time i want the program to choose one random item for me. i know how to generate a random number..but not picking a random string of charachters in a specific list..i don't know if i explain it right but i just want a general i dea about it ..
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Well just generate a random number N and then select the Nth string from you list.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      A trick:

      If you know the number of items in your list, say it is 100, then you random number has to be between 0 and 99. Then if you use a system provided random number generation function you can take the result % 100 to get that range 0 to 99.

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        The problem with that trick is that on some systems (hopefully fewer and fewer as time goes by) the numbers produced by the random number generator don't have very much randomness in the lower bits due to the algorithm used. Using % as you have specifically discards the high order bits and relies on the low order bits.

        You get better randomness by using the whole of the range returned by rand.

        This and other pitfalls of using rand are explained in C-FAQ Q13.16 How can I get random integers in a certain range?

        Comment

        Working...