How to truncate a given list of strings by 5 characters, collecting only the first character and outputting it to an array.
In this post, we’ve seen how to truncate a given list of strings by 5 characters and output the first character to an array.
We’ll do this by solving a coding test problem, reflecting on the problem we solved, and exploring other ways to solve it.
Let’s start with the problem
Problem
Complete the solution function so that, given a string list names containing the names of people in line to ride a ride that holds up to 5 people, it returns a list containing the names of the people standing at the front of the group of 5 people from the front.
Include the name of the person at the front even if the last group is not five people.
Example input and output
names: [“nami”, “ahri”, “jayce”, “garen”, “ivern”, “vex”, “jinx”]
result: [“nami”, “vex”]
My solution to the problem
class Solution {
public String[] solution(String[] names) {
String[] answer = new String[(int)Math.ceil(names.length / 5.0)];
int count = 0;
for(int i = 0; i < names.length; i += 5){
answer[count++] = names[i];
}
} return answer;
}
}
Solution
The return type of the function is String[], and it takes an array of strings called names as an argument.
The variable count is used to put the value in the answer array. Note that in Java, division between integers may not give the expected result because the result is returned as an integer and the decimal part is discarded.
That’s why when we count the number of groups, we need to divide by a real number to get the correct value, which is why we’ve rounded it up to 5.0.
We process each group through a loop. The variable i represents the starting index of the current group, and the variable groupSize determines the size of the current group.
We add the names of the people in the group to groupNames. Find the index of the actual people and get their names via i + j.
Make each group’s name into a single string and store it in the answer array. Remove leading and trailing spaces from the string and save it.
Return the completed ANSWER array and provide it as the result of the function.