title: How do I generate a random string of up to a certain length?
body: <p>I would like to generate a random string (or a series of random strings, repetitions allowed) of length between 1 and <code>n</code> characters from some (finite) alphabet. Each string should be equally likely (in other words, the strings should be uniformly distributed).</p>
  
  <p>The uniformity requirement means that an algorithm like this doesn't work:</p>
  
  <pre><code>alphabet = "abcdefghijklmnopqrstuvwxyz"
  len = rand(1, n)
  s = ""
  for(i = 0; i &lt; len; ++i)
      s = s + alphabet[rand(0, 25)]
  </code></pre>
  
  <p>(pseudo code, <code>rand(a, b)</code> returns a integer between <code>a</code> and <code>b</code>, inclusively, each integer equally likely)</p>
  
  <p>This algorithm generates strings with uniformly distributed lengths, but the actual distribution should be weighted toward longer strings (there are 26 times as many strings with length 2 as there are with length 1, and so on.) How can I achieve this?</p>