1

So for an assignment I have to generate a random code, and have someone guess the code in the console. Now My problem is that I can't seem to find a way to replace any duplicate characters in the code. The code must range in "ABCDEF", and contain 4 letters. This is what I got so far:

    char codeLetters;
    String masterCode;
    StringBuilder strings = new StringBuilder(); 
    Random random = new Random();

    for (int i = 0; i < 4; i++) {
        codeLetters = code[random.nextInt(code.length)];
        strings.append(codeLetters);
    }
    masterCode = strings.toString();
    String temp = "";
    boolean isDuplicate = false;

    for (int i = 0; i < masterCode.length(); i++) {
        isDuplicate = false;
        char comparisonChar = masterCode.charAt(i);
        for (int j = i + 1; j < masterCode.length(); j++) {
            char nextChar = masterCode.charAt(j);
            if (comparisonChar == nextChar) isDuplicate = true;
        }
        if (!isDuplicate) temp = temp + comparisonChar;
    }
    masterCode = temp;

    System.out.println(masterCode);

it prints either a code consisting out of 2-3 letters, or a code containing 5 or 6 letters, and rarely a correct code with 4 letters. What this code does as far as I know is not add the duplicate characters, but I want it to Replace them instead with another character. Is there someway to replace the characters with another randomly generated char, which is not in the String yet, without using Sets?

3
  • Have you looked at String#replace or String#replaceAll ? Commented Jan 16, 2015 at 15:13
  • Replacing with another randomly generated char after detecting a duplicate is probably not the way you want to go. Although unlikely, in theory it might never terminate - and certainly might take an overly long time to do a simple task. I would consider changing your logic for how to do this if you truly want to randomly select 4 from the 6 in any order. The answer from @AndyBrown below shows one way to do this (stackoverflow.com/a/27987066/838992) Commented Jan 16, 2015 at 15:17
  • I've looked up so many questions here on StackOverflow, but now I see that I've been looking at it in the wrong way all along. I tried String#replace and String#replaceAll, but it mostly ended up only replacing duplicates that follow eachother up, or replacing it with another duplicate. Commented Jan 16, 2015 at 18:37

3 Answers 3

4

It sounds like you only want to use each letter in code once? Why don't you set that up from the beginning using an ArrayList, and removing each character if it is randomly selected:

// copy `code` into a temporary arraylist
ArrayList<Character> possibleLetters = new ArrayList<Character>(code.length);
for (char c : code) possibleLetters.add(c);
// select randomly "without replacement"
for (int i = 0; i < 4; i++) {
    int index = random.nextInt(possibleLetters.size());
    codeLetters = possibleLetters.remove(index);
    strings.append(codeLetters);
}
Sign up to request clarification or add additional context in comments.

1 Comment

yeah, not necessarily replacing them. Thanks a lot!
0
import java.util.Random;

public class Main {

    private static char[] code = new char[] { 'A', 'B', 'C', 'D', 'E', 'F'};

    public static final void main(String[] args) {
        char codeLetters;
        String masterCode;
        StringBuilder strings = new StringBuilder(); 
        Random random = new Random();

        while (strings.length() < 4) {
            char tmpcode = code[random.nextInt(code.length)];
            if (strings.toString().contains(tmpcode + "")) {
                continue;
            }
            codeLetters = tmpcode;
            strings.append(codeLetters);
        }
        masterCode = strings.toString();
        System.out.println(masterCode);
    }
}

Replace your for loop with this one and then you don't need to do any replacing afterwards. This will only insert characters that are not already in the string.

2 Comments

While this will work a lot of the time, it may take a long time to (or theoretically never if random.nextInt truly was random) terminate. Consider what happens if random.nextInt keeps returning indices that have already been used. It's OK for this example - but in general (say we need to select 99 non-duplicates from 100 in a random order) it could be very inefficient.
Yea I realized that just now after seeing Andy's post. xD
0

In my case, I needed to remove duplicates, but could not find the best answer for my situation, so I create a function to remove duplicate characters, supply String and String to remove duplicates of: This could be easily modified to replace as well. (Just thought it may help someone not so well versed in Java like myself)

private String removeDuplicates(String strString, String strDupToRemove){
    
String strLastChar = "";
StringBuilder strReturn = new StringBuilder();
   
for(int intIndex = 0;intIndex<strString.length();intIndex = intIndex+strDupToRemove.length()){  
        String strSub = strString.substring(intIndex,strDupToRemove.length() + intIndex);
        if(!strSub.equals(strDupToRemove) || (strSub.equals(strDupToRemove) && !strLastChar.equals(strDupToRemove))){//allow 1
            strReturn.append(strSub);
        }
        strLastChar = strSub;
    }       
    //System.out.println("Dups removed: " + strReturn.toString());
    return strReturn.toString();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.