0

The code should know what the length of the input is, which is a string. For example, if "apple" is put in, it displays

EDIT NEW ANSWER

row 1: APPL                         
row 2: E*** 

EDIT row 3: (***) should not be here

If Water Melon

Row 1: Wate
Row 2: r Me
Row 3: lon*

EDIT (Row 4: ****) should not be here

It finds the minimum 1 by 1, 2 by 2, 3 by 3 and so forth length possible. Spaces are included, and extra spaces are replaced with asterisks

The code below runs perfectly if there is an assigned length for the 2D array. I need a way for the array to dynamically change based on the string input

public A(String input) {
    // Array = new String[4][4];
    int i = 0;
    // Increment through the rows
    for (int row = 0; row < Array.length; row++) {
        // Increment through the columns
            for (int col = 0; col < Array[0].length; col++) {
            if (i < input.length() && (row * col) <= input.length()) {
                Array[row][col] = input.substring(i, i + 1);
                i++;
            } else
                Array[row][col] = " ";
        }
    }
}



A test = new A("Apple");
        System.out.println(test);
A test2 = new A("Water Melon");
        System.out.println(test2);
5
  • Try using an ArrayList. Also, a sidenote - I think instead of increment, you mean iterate. Commented Apr 6, 2021 at 16:48
  • Yeah thanks for the notice, I will try to implement Array list Commented Apr 6, 2021 at 16:51
  • So I'm pretty sure I need to use an Array @M-Chen-3 Commented Apr 6, 2021 at 17:01
  • The information you provided is not enough for me to imagine how the result should look like. Please give us the complete input string and an example of the result you expect. Commented Apr 6, 2021 at 17:09
  • I'm not quite sure how else to describe it, if you have the string "apple" it only fits in a 3 row 3 column, so APP at row 0, [0][1][2] Le at row 1 etc, hope that clarifies Commented Apr 6, 2021 at 17:13

2 Answers 2

3

You need to calculate the dimenssion of your resulting 2D-Array first. This can be simply done by ceiling the square root of the input length. Then you just need to fill the resulting array with each char of input and add an asteriks if the input is to short.

public static void main(String args[]) {
    String a = "Water Melon";
    for(String[] row : fill2DArray(a)){
        System.out.println(Arrays.toString(row));
    }
}

static int getDim(String input){
    return (int) Math.ceil(Math.sqrt(input.length()));
}

static String[][] fill2DArray(String input){
    int dim = getDim(input);
    String[][] result = new String[dim][dim];
    
    for(int i = 0; i < dim * dim; i++){
        if(i < input.length()){
            result[i/dim][i%dim] = String.valueOf(input.charAt(i));
        }
        else{
            result[i/dim][i%dim] = "*";
        }
    }
    return result;
}

The above method fill2DArray can be shortend using ternary operator like :

static String[][] fill2DArrayTernary(String input){
    int dim = getDim(input);
    String[][] result = new String[dim][dim];
    
    for(int i = 0; i < dim * dim; i++){
        result[i/dim][i%dim] = i < input.length() ? String.valueOf(input.charAt(i)) : "*";            
    }
    return result;
}

You can do the task also using regex after appending the required asteriks to the input and spliting the string first at each nth (dim) char and then again at each char. Example:

static String[][] fill2DArrayRegex(String input){
    int dim = getDim(input);
    String inputWithAsteriks = input + "*".repeat(dim * dim - input.length());
    String[] rows = inputWithAsteriks.split("(?<=\\G.{" + dim +"})");
    String[][] result = new String[dim][dim];        
    for(int i = 0; i < rows.length ; i++){
        result[i] = rows[i].split("");
    }
    return result;
}

Also streams can be used here if needed:

static String[][] fill2DArrayStreams(String input){
    int dim = getDim(input);
    String inputWithAsteriks = input + "*".repeat(dim * dim - input.length());
    
    return Pattern.compile("(?<=\\G.{" + dim +"})")
                  .splitAsStream(inputWithAsteriks)
                  .map(str -> str.split(""))
                  .toArray(String[][]::new);
}

UPDATE

If your original code works (i haven't tested it) and the only thing you need is to calculate the column count of your array dynamicaly depending on input:

public A(String input) {
    int columns = (int)Math.ceil(input.length()/4.0);
    Array = new String[4][columns];

    for (int i = 0; i < 4 * columns; i++) {
        if (i < input.length()) {
            Array[i / columns][i % columns] = String.valueOf(input.charAt(i));
        } else {
            Array[i / columns][i % columns] =  "*";
        }
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

If I were to retain my original method public A(String input) without returning, how would that work?
Your code seems to be working, but I made a mistake in my original question. I guess the array had to be dynamically changed 4 x (any number), not just 4. So for Watermelon, the last row of asterisk are not to be there.
@HarryIguana Does that mean you are not looking for a sqare "matrix" n x n but a 4 x n array?
Right, sorry about confusion. A 4 x n array that changes based on input
@HarryIguana In that case you only need to divide your input length by 4 and add one if needed (if input length is not a multiple of four) or just use Math.ceil. See my update at the end.
1

Here is a possible solution:

// the import is for testing purposes only
import java.util.Arrays;

public class Test {

    public static void main(String[] args) {
        // the following code is for testing purposes only
        Test test = new Test();
        System.out.println(Arrays.deepToString(test.squareArray("Apple")));
        System.out.println(Arrays.deepToString(test.squareArray("Water Melon")));
    }
    
    public String[][] squareArray(String input){
        int size = 1;

        // find the smallest size for your array
        while(input.length() > (size * size)) 
            size++;

        // fill in the input up to the required size with asterik
        int length = size * size;
        input = input + "*".repeat(length - input.length());

        // create the array
        String[][] result = new String[size][size];

        // fill in all characters of the input into the array
        for(int i = 0; i < input.length(); i++) 
            result[i / size][i % size] = String.valueOf(input.charAt(i));

        // return the created array
        return result;
    }
}

I hope that meets your question.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.