Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is the code snippet for <strong>random sample problem</strong> (thanks Eyal for naming it). Not sure if that is what you are looking for.</p> <p>Be aware, that this solution would run into an infinete loop if not enough lowercase letters are in the string. So you would need to tackle that as well, but I guess it is a starting point. ;-)</p> <pre><code>String myString = "9aie3ra3nr23rr5r21t"; System.out.println(upperCaseRandom(myString, 10)); public static String upperCaseRandom(String input, int n) { StringBuilder output = new StringBuilder(input); Random r = new Random(); for (int i = 0; i &lt; n; i++) { // Pick a place int position = r.nextInt(input.length()); // Check if lowercase alpha if (Character.isLowerCase(output.charAt(position))) { output.setCharAt(position, Character.toUpperCase(output.charAt(position))); } else { i--; } } return output.toString(); } </code></pre> <p><strong>Edit:</strong> Here is an improved version. It does change exactly n lowercase letters into uppercase letters (if there are enough, otherwise it changes all of them). The programm does not run into infinite loops, but still running time is a problem though.</p> <pre><code>public static String upperCaseRandom(String input, int n) { final int length = input.length(); final StringBuilder output = new StringBuilder(input); final boolean[] alreadyChecked = new boolean[length]; final Random r = new Random(); for (int i = 0, checks = 0; i &lt; n &amp;&amp; checks &lt; length; i++) { // Pick a place int position = r.nextInt(length); // Check if lowercase alpha if (!alreadyChecked[position]) { if (Character.isLowerCase(output.charAt(position))) { output.setCharAt(position, Character.toUpperCase(output.charAt(position))); } else { i--; } checks++; alreadyChecked[position] = true; } else { i--; } } return output.toString(); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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