Home > Mobile >  Change random character in string
Change random character in string

Time:06-11

Good time of the day

I have to implement some functions on my site. When a user enters the website, he has to enter a number of errors that should be occurred in some string. If he chooses 0, the original string will be displayed without error. If the user enters 1 in the error field, the string should be displayed with 1 error. For instance, the word "programming" should be displayed like "rrograming" or "prugramming", or adding/deleting one character to/from the string. Consequently, if the error is 2, the mistakes also should be 2.
In addition, the result should be the same every time. Someone told me to use seeds in Random class, but now I don't have idea.

I am programming in Java and some JS

Please, if you faced the same problem or experience, give me some ideas or resources to learn.

CodePudding user response:

Random with a seed results in the same sequence of values every time, so use the same random every time.

The trick is using a random seed based on the word content. Otherwise you would end up doing the same mutilation pattern on all words.

The likeliness of changing a letter can be in the order of the length of the word. And inserting twice as much as removing, both rare.

String mutilateWord(String word, int times) {
    //Random random = new Random(42);
    // Or better (as different words get differently mixed up:
    Random random = new Random(word.hashCode());

    for (int t = 0; t < times;   t) {
        int chars = word.length;

        // If a letter modification has the same likeliness:
        int choices = chars   2   1; // change some letter   (twice) add   remove
        word = switch (random.nextInt(choices)) {
            case 0 -> removeRandomLetter(word, random);
            case 1, 2 -> insertRandomLetter(word, random);
            default -> changeRandomLetter(word, random);
        };
    }
    return word;
}

Since java 12 one can use a switch expression as above.

The above will also mutilate the mutilations, so you might prefer to first have a times loop changing random letters (or not), and then a second times loop adding/removing letters.

CodePudding user response:

Your friend's idea is correct, setting the random number seed to the same value each time will yield same results. However, you can cache the result everytime you compute it in a map for example. Setting the keys as the error number and the value as the string result. On each function call you check if the error number is cached, if that's the case you return it without computing it else you compute the result then cache it and finally return it.

  • Related