|
| 1 | +import java.util.Scanner; |
| 2 | + |
| 3 | +public class print_transpose { |
| 4 | + static Scanner sc = new Scanner(System.in); |
| 5 | + void print_matrix(char[][] matrix){ |
| 6 | + for (char[] C: matrix){ |
| 7 | + for (char c: C){ |
| 8 | + System.out.print(c + "\t"); |
| 9 | + } |
| 10 | + System.out.println(); |
| 11 | + } |
| 12 | + } |
| 13 | + |
| 14 | + void print_matrix(char[][] matrix, int r, int c){ |
| 15 | + for (int i=0; i<c; i++){ |
| 16 | + for (int j=0; j<r; j++){ |
| 17 | + if (i<matrix[j].length) |
| 18 | + System.out.print(matrix[j][i] + " "); |
| 19 | + else |
| 20 | + System.out.print(" "); |
| 21 | + } |
| 22 | + System.out.println(); |
| 23 | + } |
| 24 | + } |
| 25 | + int find_longestWord(String sentence){ |
| 26 | + int max_len = 0; |
| 27 | + for (String word : sentence.split(" ")) { |
| 28 | + if (word.length() > max_len) { |
| 29 | + max_len = word.length(); |
| 30 | + } |
| 31 | + } |
| 32 | + return max_len; |
| 33 | + } |
| 34 | + |
| 35 | + char[][] str_to_matrix(String sentence, char[][] matrix){ |
| 36 | + int row=0, col=0; |
| 37 | + for (String word : sentence.split(" ")){ |
| 38 | + col = 0; |
| 39 | + for (char c : word.toCharArray()){ |
| 40 | + matrix[row][col] = c; |
| 41 | + col++; |
| 42 | + } |
| 43 | + row ++; |
| 44 | + } |
| 45 | + return matrix; |
| 46 | + } |
| 47 | + |
| 48 | + public static void main(String[] args) { |
| 49 | + String ip_sent; |
| 50 | + System.out.print("Enter the input string:"); |
| 51 | + ip_sent = sc.nextLine(); |
| 52 | + print_transpose ob = new print_transpose(); |
| 53 | + |
| 54 | + // STEP 1. Start creating the matrix |
| 55 | + |
| 56 | + int nr_words = ip_sent.split(" ").length; // number of words in the input sentence |
| 57 | + int longest_word_len = ob.find_longestWord(ip_sent); |
| 58 | + System.out.printf("Longest word length: %d\n", longest_word_len); |
| 59 | + char[][] matrix = new char[nr_words][longest_word_len]; |
| 60 | +// ob.print_matrix(matrix); |
| 61 | + matrix = ob.str_to_matrix(ip_sent, matrix); |
| 62 | + |
| 63 | + // STEP 2: Print the matrix in the transposed form |
| 64 | + ob.print_matrix(matrix, nr_words, longest_word_len); |
| 65 | + |
| 66 | + System.out.println("\n----------Done---------"); |
| 67 | + } |
| 68 | +} |
0 commit comments