Contents

About Vertical Reading (with.Java)

   Sep 14, 2023     2 min read

This is an article about how to read vertically (with.Java).

We’ve been solving coding test problems, reflecting on the problems we’ve solved, and learning about other ways to solve them.

Let’s start with the problem

Problem

You are given a string my_string and two integers m, c.

Write a solution function that returns as a string the characters written in the cth column from the left when my_string is written horizontally with m characters per line.

Example input and output

my_string: “ihrhbakrfpndopljhygc”

m: 4

c: 2

result: “happy”

If you write my_string with 4 characters per line, the table looks like this

Column 1Column 2Column 3Column 4
ihrh
bakr
fpnd
oplj
hygc

Return “happy” because the letter in column 2 reads happy when read vertically.

My solution to the problem

class Solution {
    public String solution(String my_string, int m, int c) {
        char[] arr = my_string.toCharArray();
        char[] arr1 = new char[arr.length/m];
        int j = 0;
        for(int i = c-1; i < arr.length; i+=m){
            arr1[j++] = arr[i];
        }
        } return new String(arr1);
    }
}
Solution Explained

To establish the matrix, we first need to convert the string type to Char type and store it as an array.

To do so, we store my_string in an array of type char[] with toCharArray().

After that, we need to make arr1 of the same type to store the return value, and the size of the array is how many columns from the length of arr.

So, I declared a divide-and-conquer loop to set the conditions the way the problem requires, and stored and returned the element with the specific IDX from the matrix.