Home > Blockchain >  Split sentence into words and arrange it vertically in 2d array
Split sentence into words and arrange it vertically in 2d array

Time:11-08

I have a String that I need to arrange vertically in a 2d array across n columns. The String may have multiple words, and if it does, the goal is to split the sentence into equal words per column, and arrange them in n columns vertically. One option is to sort by length, arrange the longest word in first column, and then arrange remaining words.

So if I have 8 words, I arrange 2 words each in 4 columns - something like that or 4 words across 2 columns making sure I have n words across n columns.

For ex, if I have "Apple is my favorite fruit because it is yummy", I need to arrange 3 words per column. I can't figure out how to code this up. I hardcoded the rows and columns for my solution below, and I am trying to incrementally get to it. Any inputs will be very helpful.

public static void main(String[] args) {
    putin2dArr("Apple is");
}

public static void putin2dArr(String inputString) {
    String[] input = inputString.split(" ");
    int rows = 0;
    int cols = 2;
    for (String inptString : input) {
        if (inptString.length() > rows) {
            rows = inptString.length();
        }
    }
    int col = 0;

    char[][] output = new char[rows][cols];

    for (String inptString : input) {
        for (int i = 0; i < rows; i  ) {
            if (inptString.length() < rows) {
                rows = inptString.length();
                while (i < rows) {
                    output[i][col] = inptString.charAt(i);
                    i  ;
                }
            } else {
                output[i][col] = inptString.charAt(i);
            }
        }
        col  ;
        if (col == cols) {
            break;
        }
    }
    print2dArray(output);
}

public static void print2dArray(char[][] inputStr) {
    int rows = inputStr.length;
    int cols = inputStr[0].length;

    for (int i = 0; i < rows; i  ) {
        for (int j = 0; j < cols; j  ) {
            System.out.println(inputStr[i][j]);
        }
    }
}

CodePudding user response:

Assuming the number of columns is an external input parameter, the 2D array may be created and populated using the words in the input string.
The words should be sorted by their length in descending order.

static String[][] buildTable(String str, int n) {
    // prepare sorted array of words
    String[] words = Arrays.stream(str.split("\\s "))
        .sorted(Comparator.<String>comparingInt(String::length).reversed())
        .toArray(String[]::new);
    // build the resulting 2D array
    String[][] res = new String[words.length / n][n];
    for (int i = 0; i < words.length; i  ) {
        res[i / n][i % n] = words[i];
    }
    return res;
}

Test:

String str = "Apple is my favorite fruit because it is yummy";

Arrays.stream(buildTable(str, 3))
    .map(Arrays::toString)
    .forEach(System.out::println);

Output

[favorite, because, Apple]
[fruit, yummy, is]
[my, it, is]

CodePudding user response:

Try something like this:

  public void test() {
    String inputStr = "Apple is my favorite fruit because it is";
    String[] words = inputStr.split(" ");
    int columns = (int) Math.sqrt(words.length);

    int c = 0;
    for (String word : words) {
      System.out.print(word   " ");
      c = c   1;
      if (c == columns) {
        System.out.println("");
        c = 0;
      }
    }
  }

The idea is that you get number of columns with square root of size. You add items to the column until the row is full and then you move to the next one.

CodePudding user response:

If the number of words is not divisible by n, push the rest into the last column.

static char[][] arrangeVertically(String inputStr, int n) {
    String[] words = inputStr.split("\\s ");
    String input = String.join(" ", words);
    int size = input.length(), wc = words.length / n;
    char[][] matrix = new char[size][n];
    for (char[] row : matrix)
        Arrays.fill(row, ' ');
    int maxRow = 0;
    for (int i = 0, w = 0, r = 0, c = 0; i < size;   i) {
        char ch = input.charAt(i);
        if (ch == ' ' &&   w >= wc && c < n - 1) {
              c;
            r = w = 0;
        } else {
            matrix[r  ][c] = ch;
            maxRow = Math.max(maxRow, r);
        }
    }
    return Arrays.copyOfRange(matrix, 0, maxRow);
}

public static void main(String[] args) {
    String inputStr =  "Apple is my favorite fruit because it is yummy";

    char[][] v = arrangeVertically(inputStr, 4);

    for (char[] row : v) {
        for (char c : row)
            System.out.print(c   " ");
        System.out.println();
    }
}

output: (n = 4)

A m f i 
p y r t 
p   u   
l f i i 
e a t s 
  v     
i o b y 
s r e u 
  i c m 
  t a m 
  e u y 
    s   
    e   
  •  Tags:  
  • java
  • Related