简体   繁体   中英

How to replace a random letter in a triple with a random character from the alphabet, if the letters in the triple are repeated?

How to replace a random letter in a triple with a random character from the alphabet, if the letters in the triple are repeated? Like this IIImmmpppooorrrtttaaannnttt ----> I1ImQmOppooT0rruttaJannQ tt. In my code, I replace all letters in a triple.

import java.util.LinkedList;
import java.util.Random;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        char[] alphabet = {' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
                'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
                'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
                'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
                'u', 'v', 'w', 'x', 'y', 'z',};
        Scanner scan = new Scanner(System.in);
        String str = scan.nextLine();
        LinkedList<String> list = new LinkedList<>();
        System.out.println(str);

        StringBuilder full1 = new StringBuilder();
            for (int i = 0; i < str.length(); i++) {
                String text0 = "";
                char s = str.charAt(i);
                //String s = str.substring(i, i + 3);
                text0 += s;
                text0 += s;
                text0 += s;
                list.add(text0);
                full1.append(text0);
            }
        System.out.println(full1);

        StringBuilder full = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            Random random = new Random();
            String text = list.get(i);
            int select = random.nextInt(text.length());
            String text2 = text.replace(text.charAt(select), alphabet[random.nextInt(alphabet.length)]);
            full.append(text2);
        }
        System.out.println(full);
    }
}

You should be able to do something like this by using a character array:

String input = "ttteeesss";
Character[] arr = input.toCharArray();
arr[randomNumberInTriplet] = alphabet[randomAlphabet];
String ans = new String(arr); 

If you replace the character it will replace all the characters in the String.

public static void main(String[] args) {
    Random random = new Random();
    char[] alphabet = {' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
        'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
        'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
        'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
        'u', 'v', 'w', 'x', 'y', 'z',};
    Scanner scan = new Scanner(System.in);
    String str = scan.nextLine();
    List<String> list = new LinkedList<>();
    System.out.println(str);

    StringBuilder full1 = new StringBuilder();
    for (int i = 0; i < str.length(); i++) {
        String text0 = "";
        char s = str.charAt(i);
        text0 += s;
        text0 += s;
        text0 += s;
        list.add(text0);
        full1.append(text0);
    }
    System.out.println(full1);
    System.out.println(list);

    StringBuilder full = new StringBuilder();
    for (int i = 0; i < list.size(); i++) {
        String text = list.get(i);
        int select = random.nextInt(text.length());
        char[] text2 = text.toCharArray();
        text2[select] = alphabet[random.nextInt(alphabet.length)];
        full.append(text2);
    }
    System.out.println(full);
}

You cannot replace just one particular index like this. You need to convert it into an array , replace on the index and then store it back as string .


No need to create a new Random object every-time. You can reuse.


Write this:

text0 += s;
text0 += s;    
text0 += s;

Like this:

text0 += s + s + s;

Convert the loop to stream:

list.stream().map(String::toCharArray).forEach(c -> {
    c[random.nextInt(c.length)] = alphabet[random.nextInt(alphabet.length)];
    full.append(c);
});

You are not using full1 anywhere. Convert the loop above to stream like this:

str.chars().mapToObj(c -> String.valueOf(c + c + c)).forEach(list::add);

The less code there is, the less places there are for bugs to lurk.

Try using StringBuilder . It has convenient method for replacing character at specific position, so you won't need to deal with char arrays. (I renamed some variables to make it clearer)

Random rand = new Random();
StringBuilder replacer;
String triple;
for (int i = 0; i < list.size(); i++) {
    triple = list.get(i);
    int indexToReplace = rand.nextInt(triple.length());
    replacer = new StringBuilder(triple);
    replacer.setCharAt(indexToReplace, alphabet[rand.nextInt(alphabet.length)]);
    full.append(replacer);
}

Instead of complicating things using LinkendList, StringBuilder and various methods from String class, just think for a while how you would do it using a pen and paper. If I were you, I would chose the following aproach:

  • Split the original string at every third char (using regex, substring..)
  • Check for each sub string (triplet) if the chars are repeated (using regex, a loop...)
  • If yes replace a char at random index with a random char, else do nothing
  • Concatenate the substrings to one result string

Example:

public class Example {
    static char[] alphabet = {' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
                'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
                'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
                'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
                'u', 'v', 'w', 'x', 'y', 'z',};
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String original = scan.nextLine();    
        String[] splited = original.split("(?<=\\G...)");
        System.out.println(original);
        String result = "";
        for (String triple : splited) {
            if(contains3RepeatedChars(triple)){
               triple =  replaceARandomIndexWithARandomChar(triple);
            }
            result += triple;
        }
        System.out.println(result);
    } 
    static boolean contains3RepeatedChars(String str){
        return str.matches("(.)\\1{2}");
    }
    static String replaceARandomIndexWithARandomChar(String str){
        Random r = new Random();
        int randIndex = r.nextInt(3);
        char randChar = alphabet[r.nextInt(alphabet.length)];
        while (randChar == str.charAt(0)) {
            randChar = alphabet[r.nextInt(alphabet.length)];            
        }
        char[] arr = str.toCharArray();
        arr[randIndex] = randChar;
        return new String(arr);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM