Search code examples
androidarraysstringrandomwords

Substituting percentage of words at random indexes in String array


I have a string like

This is a very nice sentence

I break it into separate words and store in String[] with:

String[] words = s.split(" ");

How can I take a specific percentage on the total number of words (lets say 2 of 6 words) and substitute these 2 words with something else. My code so far:

    //Indexes in total
    int maxIndex = words.length;
    //Percentage of total indexes
    double percentageOfIndexes = 0.20;
    //Round the number of indexes
    int NumOfIndexes = (int) Math.ceil( maxIndex * (percentageOfIndexes / 100.0));
    //Get a random number from rounded indexes
    int generatedIndex = random.nextInt(NumOfIndexes);` 

Solution

  • First, calculate how many words you want to replace:

    int totalWordsCount = words.length;
    
    double percentageOfWords = 0.20;
    
    int wordsToReplaceCount = (int) Math.ceil( totalWordsCount * percentageOfWords );
    

    Then, knowing how many words you want to replace, get that many random indexes, and just swap words at those indexes:

    for (int i=0; i<wordsToReplaceCount; i++) {
        int index = random.nextInt(totalWordsCount);
    
        //and replace
        words[index] = "Other"; // <--- insert new words
    }
    

    NOTE: Just remember that the smaller the number of words, the bigger discrepancy between your percentage, and actual number of words to replace, eg. 20% from 6 words is 1.2 word, which becomes 2 after Math.ceil(), and 2 is 33.33% from 6.