Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

random generate character in a string

i need to generate random character in a String java when user click on button. for example :if we take cat example i need to disply character in a string like follwing:

CAT,ACT,TAC,TCA

Thanks in advance

Aswan

like image 636
Aswan Avatar asked Aug 25 '26 07:08

Aswan


1 Answers

On Fisher-Yates shuffling algorithm

Fisher-Yates shuffle is a standard algorithm for shuffling. Here's the pseudocode:

To shuffle an array a of n elements:
   for i from n - 1 downto 0 do
         j ← random integer with 0 ≤ j ≤ i
         exchange a[j] and a[i]

Here's a straightforward Java implementation:

static String shuffled(String s) {
    char[] a = s.toCharArray();
    final int N = a.length;
    Random r = new Random();
    for (int i = N - 1; i >= 0; i--) {
        int j = r.nextInt(i + 1);
        swap(a, i, j);
    }
    return new String(a);
}
static void swap(char[] a, int i, int j) {
    char t = a[i];
    a[i] = a[j];
    a[j] = t;
}

Then you can have:

    String text = "stackoverflow";
    for (int i = 0; i < 10; i++) {
        System.out.println(shuffled(text));
    }

This will generate 10 shuffling of the string "stackoverflow" (see also on ideone.com).


Guava + Java Collections Framework alternative solution

If you have Guava library installed, then this would be a nice solution. Here are the key facts:

  • Guava has Chars.asList(char...) which creates a List<Character> live view of a char[]. Modifications to the returned list will affect the backing array (and vice versa).
  • java.util.Collections can shuffle(List<?>)

We can then combine the two to get the following clean and readable code:

import com.google.common.primitives.*;
import java.util.*;

public class AnagramCreator {
    public static void main(String[] args) {
        String text = "stackoverflow";
        char[] arr = text.toCharArray();
        List<Character> list = Chars.asList(arr);

        for (int i = 0; i < 10; i++) {
            Collections.shuffle(list);
            System.out.println(new String(arr));
        }
    }
}

The above will print 10 anagrams of "stackoverflow".

Note that Guava is only used to provide the List<Character> live view of the char[]. A char[] does not get autoboxed to a Character[] (and vice versa), otherwise Arrays.asList(T...) would've been sufficient.

See also

  • Java Language Guide/Autoboxing

Related questions

  • Arrays.asList() not working as it should?
like image 180
polygenelubricants Avatar answered Aug 27 '26 22:08

polygenelubricants



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!