Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The solution depends on the probabilistic model you choose. If for example you decide on <a href="http://en.wikipedia.org/wiki/Binomial_distribution" rel="nofollow noreferrer">binomial distribution</a>, then you can traverse the chars, and switch every char to uppercase with a fixed probability p. The expected number of uppercase letters will be p * str.length():</p> <pre><code>public static String randomUpper(String str, double p) { StringBuilder sb = new StringBuilder(str.length()); for (int i = 0; i &lt; str.length(); i++) { char c = str.charAt(i); if (Character.isLetter(c) &amp;&amp; Math.random() &lt; p) c = Character.toUpperCase(c); sb.append(c); } return sb.toString(); } </code></pre> <p>If on the other hand you want to decide on the exact number of upercase letters for a given string, then the problem becomes a <a href="http://eyalsch.wordpress.com/2010/04/01/random-sample/" rel="nofollow noreferrer">random sample problem</a> (i.e. choose M positions to switch out of N positions in the string). This can be much faster than the first approach, when M is much smaller than N (though with Java's immutable strings the difference becomes minor because you have to copy the whole string anyway).</p> <p><strong>-- edit --</strong></p> <p>Now that you clarified the requirements, consider the following:</p> <pre><code>public static String randomUpper2(String str, double p) { int letters = 0; for (int i = 0; i &lt; str.length(); i++) { if (Character.isLetter(str.charAt(i))) letters++; } int toChoose = (int) (p * letters); StringBuilder sb = new StringBuilder(str.length()); for (int i = 0; i &lt; str.length(); i++) { char c = str.charAt(i); if (Character.isLetter(c)) { if (Math.random() &lt; (toChoose/(double)letters)) { c = Character.toUpperCase(c); toChoose--; } letters--; } sb.append(c); } return sb.toString(); } </code></pre> <p>This code performs a random sample "on the fly", considering only alpha chars, as required. Use p=0.5 to switch exactly half of the letters.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload