Home > Blockchain >  Split a String into 'N' Roughly Equal Pieces (Java)
Split a String into 'N' Roughly Equal Pieces (Java)

Time:12-12

The question I am asking has been asked/answered here, however the answer provided uses a Python specific library, and as such does not help.

I am attempting to build an algorithm, that given:

  • A string s with length l
  • A number of "splits" n

Will return n number of substrings ss, whos' length ssl cannot be more than 1 apart from each other.


Examples:

Split ATestString into 3 parts:

  • The following would be valid: ["ates", "tstr", "ing"], [4, 4, 3]
  • Whereas this would not: ["atest", "strin", "g"], [5, 4, 1]

Split AnotherTestString into 4 parts:

  • Valid: ["Anoth", "erTe", "stSt", "ring"], [5, 4, 4, 4,]

CodePudding user response:

static int[] PerformStringDivision(String word, int numSplits) {

    int len = word.length();;
    int[] solution = new int[numSplits]; // an array of strings that will hold the solution

    int roughDivision = (int) Math.ceil( (double) len/numSplits); // the length of each divided word
    int remainingLetters = len;
    
    boolean reduced = false; // flag to see if I've already reduced the size of the sub-words
    
    for (int i = 0; i < numSplits;   i) {

        
        int x = (roughDivision-1)*(numSplits-(i)); // see next comment
        // checks to see if a reduced word length * remaining splits exactly equals remaining letters
        if (!reduced && x == remainingLetters) {
            roughDivision -= 1;
            reduced = true;
        }

        solution[i] = roughDivision;

        remainingLetters -= roughDivision;
    }

    return solution;
}

CodePudding user response:

Continue to evaluate the maximum number of characters you can extract from the String in each iteration of your loop based on:

  1. the remaining characters in the string
  2. the number of loops remaining to process the entire string

Something like:

public class Main
{
    public static void main(String[] args) throws Exception
    {
        String text = "ALongerTestString";
        int parts = 4;

        String[] result = Main.split(text, parts);
        System.out.println( Arrays.asList( result ) );
    }

    static public String[] split(String text, int parts)
    {
        String[] list = new String[parts];
        double length = (double)text.length();

        int start = 0;

        for (int i = 0; i < parts; i  )
        {
            double remainder = length - start;
            int characters = (int)Math.ceil(remainder / (parts - i));
            int end = start   characters;
            list[i] = text.substring(start, end);
            start = end;
        }

        return list;
    }
}
  • Related