vendredi 22 février 2019

Java: Generate Unique Random Character

I have a string of "random" characters. I assigned a numeric value to each character depending on its position in the string and then set a loop to output the character at whatever random position gets chosen. Here's my code so far:

public class Random9_4 {

  public static void main(String[] args) {

    final String chords = "ADE";
    final int N = chords.length();
    java.util.Random rand = new java.util.Random();
    for(int i = 0; i < 50; i++)
    {
        //char s = chords.charAt(rand.nextInt(N));
        //char t = chords.charAt(rand.nextInt(N));

        System.out.println(chords.charAt(rand.nextInt(N)));
        //temp variable
        //while(s == t)
        //{
        //  
        //}System.out.println(chords.charAt(rand.nextInt(N)));
    }
  }
}

As of now it works fine but the characters can repeat at times. I want it so that it is "unique" output of characters (meaning no repeats). I understand one way to do this is to use a temporary variable to check the current character with the previous one and the character that will be displayed next but I am unsure of how to get started.




Aucun commentaire:

Enregistrer un commentaire