Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.7 kB
1
Indexable
Never
package org.example;

import java.util.ArrayList;
import java.util.List;

class Solution {
    public static List<String> solution1(String[][] paragraphs, int maxWidth) {

        List<String> result = new ArrayList<>();

        for(String[] paragraph: paragraphs) {
            int paraLength = paragraph.length;
            int startIdx = 0;
            while(startIdx<paraLength) {
                int endIdx = startIdx+1;
                int lineLength = paragraph[startIdx].length();
                while(endIdx<paraLength && (lineLength+(endIdx-startIdx-1)+paragraph[endIdx].length()<maxWidth)) {
                    lineLength+=paragraph[endIdx].length();
                    endIdx++;
                }
                result.add(centerAlign(paragraph,startIdx,endIdx,lineLength,maxWidth));
                startIdx = endIdx;
            }
        }
        return result;
    }

    private static String centerAlign(String[] paragraph, int startIdx, int endIdx, int lineLength, int maxWidth) {
        System.out.println("CenterAlign");
        int remainingSpots = maxWidth - lineLength;
        int requiredSpacesBetweenWords = endIdx-startIdx-1;
        int remainingSpaces = remainingSpots-requiredSpacesBetweenWords;
        int leftSpaces =0,rightSpaces=0;
        if(remainingSpaces%2==0) {
            leftSpaces = remainingSpaces/2;
            rightSpaces = remainingSpaces/2;
        } else {
            leftSpaces = remainingSpaces/2;
            rightSpaces = (remainingSpaces/2) + 1;
        }
        return createCenterAlignedString(paragraph,startIdx,endIdx,leftSpaces,rightSpaces);
    }

    private static String createCenterAlignedString(String[] paragraph, int startIdx, int endIdx, int leftSpaces, int rightSpaces) {
        System.out.println("CenterAlignedString" + startIdx + endIdx + leftSpaces + rightSpaces);
        StringBuilder line = new StringBuilder("*");
        line.append("#".repeat(leftSpaces));
        for(int index=startIdx;index<endIdx;index++) {
            line.append(paragraph[index]);
            if(index!=endIdx-1) {
                line.append("#");
            }
        }
        line.append("#".repeat(rightSpaces));
        line.append("*");
        return line.toString();
    }

    public static void main(String[] args) {
        String[][] paragraphs = {{"hello", "world"}, {"How", "areYou", "doing"}, {"Please", "look", "and", "align", "to", "the", "center"}};
        int width = 16;
        System.out.println("Starting");

        String[] result = solution1(paragraphs, width).toArray(new String[0]);

        for (String line : result) {
            System.out.println(line);
        }
    }
}