Last active
October 22, 2017 21:56
-
-
Save chaixdev/83daa70bfe3f650b83609e61a4e7d356 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package util; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.List; | |
import Printer.Printer; | |
public class Vertical { | |
private Printer printer; | |
public Vertical(Printer p) { | |
this.printer = p; | |
} | |
// make data structure for words in sentences | |
public List<ArrayList<String>> structureInput(String s) { | |
List<ArrayList<String>> structuredText = new ArrayList<>(); | |
//count sentences | |
List<String> sentences = new ArrayList<String>(Arrays.asList(s.split("\n"))); | |
int columns = sentences.size(); | |
for(int i=0;i<columns;i++) { | |
structuredText.add(new ArrayList<String>(Arrays.asList(sentences.get(i).split(" ")))); | |
} | |
return structuredText; | |
} | |
public String composeOutput(List<ArrayList<String>> structuredText) { | |
int columns = structuredText.size(); | |
//count words in longest sentence | |
//determine column width | |
int rows = 0; | |
int columnwidth=0; | |
for (List<String> sentence : structuredText) { | |
rows = rows < sentence.size() ? sentence.size() : rows; | |
for(String word : sentence) { | |
columnwidth = columnwidth < word.length() ? word.length() : columnwidth; | |
} | |
} | |
//compose output | |
String out = ""; | |
//for each row | |
for(int i=0; i<rows;i++) { | |
//take one from each of the lists and append spaces to fill column | |
for(int j=0;j<columns;j++) { | |
String word = structuredText.get(j).isEmpty()?"":structuredText.get(j).remove(0) ; | |
while(word.length()<columnwidth+2) { | |
word += " "; | |
} | |
out += word; | |
} | |
out +="\n"; | |
} | |
return out; | |
} | |
public void process(String s) { | |
printer.println(composeOutput(structureInput(s))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment