views:

121

answers:

2

Hi Folks

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

A: 

Hi Thankq for all finally i got solution for my problem.

public String RandomString(String word){

    int no=word.length();
    String temp="";
    String temp2=null;
     while(no>0){
         int genNo=ran.nextInt(word.length());
         if(temp2==null){
             temp2=""+genNo;
             temp=Character.toString(word.charAt(genNo));
             no--;
         }else{
            if(!temp2.contains(""+genNo)){
                temp2=temp2+""+genNo;
                temp=temp+Character.toString(word.charAt(genNo));
                no--;
            }
         }
     }

    if(!temp.equals(word)){
         Log.v("check","temp2 = "+temp2);
         Log.v("check","String = "+temp);
        return temp;
    }else{
        RandomGenerate(word);
    }
    return null;

}
Aswan
This is a very poor solution. There are several exceptional circumstances where it will enter an infinite loop. It's also *horrifically* slow, especially for long Strings.
Gunslinger47
can u pl suggest me if you have any solution for this
Aswan
Using the + operator on Strings is very slow. Instead, use the [StringBuilder](http://download-llnw.oracle.com/javase/6/docs/api/java/lang/StringBuilder.html) class or manipulate the characters directly in a `char` buffer.
Gunslinger47
As for your algorithm, the core problem comes with the `temp2.contains` call. As it is, you randomly generate a number until you find one that's not already been used. This is slow for long strongs, since it can take a very long time to find the single last unused index is a large range. In my initial answer above, I instead suggested to keep a list of characters that *haven't* been used yet, then `remove` them until there are none remaining. This way no random numbers are wasted.
Gunslinger47
+3  A: 

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:

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

Related questions

polygenelubricants
The condition on your `for` statement should be `i > 0`. A final loop with `i` equal to zero has no effect. I think the algorithm meant "downto 0" non-inclusive.
Gunslinger47
+1. Nice answer, though it might be a bit much for a new programmer. I'm interested to see the Guava solution, which actually performs fairly well. It takes about 50% longer than a good Fisher-Yates shuffle.
Gunslinger47