I was trying one of the problems found on HP Codewars 2007: (2)
Task Description: The CodeWars judges and scorekeepers need help printing the team names above each column on our score sheet. But we want them to look nice, so they need to be printed vertically. All we have to use is a list of team names. Please write us a program that will take a list of team names, and print them vertically.
Program Input Your program will prompt for a team name. Continue prompting for names until you receive “END”. Unlike the real CodeWars, this one will be limited to 16 teams maximum.
Program Output Your program will output to the screen each team’s name, in the order it was entered, arranged vertically such that it is read from top to bottom. There should be two spaces between each name as printed.
I attempted the problem and created the Java solution below:
import java.util.Scanner;
import java.util.ArrayList;
public class Prob02 {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
ArrayList<String> teams = new ArrayList<>();
ArrayList<Integer> log = new ArrayList<>();
do{
System.out.print("Enter team name: ");
teams.add(stdin.nextLine());
//System.out.println(); Optional for clearer display. But not required.
} while (!"END".equals(teams.get((teams.size()-1))));
//while END is not equal to last element of teams
teams.remove(teams.get((teams.size()-1)));
//Find largest String length
//set defaults - index is 0 and elementLength is first length
int index = 0;
int elementLength = teams.get(0).length();
//If the first one was indeed the longest one and the only one...
log.add(index);
for(int i = 0; i < teams.size(); i++) {
if ((teams.get(i)).length() > elementLength) {
//overwrite index and elementLength if the new one is larger than the default
index = i;
elementLength = (teams.get(i)).length();
log.add(index); //now, we only need index (or team).
}
//repeat.
}
String longest = teams.get( log.get(log.size()-1) );
int longestLengthOfTeam = longest.length();
int letterYouArePrinting = 0;
for(int i = 0; i < (longestLengthOfTeam); i++){
for(int x = 0; x < teams.size(); x++) {
String team = teams.get(x);
String[] teamSplit = team.split("");
//CONVERT !! !!! !!!!!
ArrayList<String> teamTheNewOne = new ArrayList<>();
for(int ttno=0; ttno < teamSplit.length; ttno++) {
teamTheNewOne.add(teamSplit[ttno]);
}
boolean inBoundChecker = (letterYouArePrinting >= teamTheNewOne.size());
if (inBoundChecker == true) {
System.out.print(" "); //not a whole line! 3 Spaces, [1] + 2 req.
continue;
}
//Print first letter of all teams
System.out.print(teamTheNewOne.get(letterYouArePrinting) + " " /*Two spaces rule*/);
}
System.out.println();
letterYouArePrinting++;
//Now, print next letter
}
}
}
Is there a more efficient way to solve this problem?
P.S.: Problem can be found at http://www.hpcodewars.org/past/cw10/problems/Prob02%20--%20Vertical%20Printing.pdf .