Untitled

mail@pastecode.io avatar
unknown
plain_text
5 months ago
2.6 kB
5
Indexable
import java.util.ArrayList;
import java.util.List;

public class ChatFormatter {

    public static List<String> formatConversation(String[][] messages, int width, int userWidth) {
        List<String> result = new ArrayList<>();
        
        // Create the top border of the frame
        String topBottomBorder = "+" + "*".repeat(width - 2) + "+";
        result.add(topBottomBorder);
        
        for (String[] message : messages) {
            String user = message[0];
            String text = message[1];
            List<String> lines = new ArrayList<>();
            
            // Split the text into words
            String[] words = text.split(" ");
            StringBuilder currentLine = new StringBuilder();
            
            for (String word : words) {
                if (currentLine.length() + word.length() + (currentLine.length() > 0 ? 1 : 0) <= userWidth) {
                    if (currentLine.length() > 0) {
                        currentLine.append(" ").append(word);
                    } else {
                        currentLine.append(word);
                    }
                } else {
                    lines.add(currentLine.toString());
                    currentLine = new StringBuilder(word);
                }
            }
            
            // Add the last line
            if (currentLine.length() > 0) {
                lines.add(currentLine.toString());
            }
            
            for (String line : lines) {
                String formattedLine;
                if (user.equals("1")) {  // Left-aligned
                    formattedLine = "|" + String.format("%-" + userWidth + "s", line) + " ".repeat(width - userWidth - 2) + "|";
                } else {  // Right-aligned
                    formattedLine = "|" + " ".repeat(width - userWidth - 1) + String.format("%-" + userWidth + "s", line) + "|";
                }
                result.add(formattedLine);
            }
        }
        
        // Add the bottom border of the frame
        result.add(topBottomBorder);
        
        return result;
    }

    public static void main(String[] args) {
        String[][] messages = {
            {"1", "Hello how r u"},
            {"2", "good ty"},
            {"2", "u"},
            {"1", "me too bro"}
        };
        int width = 15;
        int userWidth = 5;
        List<String> output = formatConversation(messages, width, userWidth);
        
        // Print the output
        for (String line : output) {
            System.out.println(line);
        }
    }
}
Leave a Comment