Array Truncation (with.Java)
This is the “Truncate Array” problem.
We’re going to learn by solving coding test problems, reflecting on the problems we solved, and exploring other ways to solve them.
Let’s start with the problem
Problem
Given an array of integers numbers and integers num1 and num2 as parameters, complete the solution function so that it returns an array of integers truncated from the num1st index of numbers to the num2nd index of numbers.
Limitations
2 ≤ length of numbers ≤ 30
0 ≤ element of numbers ≤ 1,000
0 ≤num1 < num2 < length of numbers
Example input and output
numbers | num1 | num2 | result |
---|---|---|---|
[1, 2, 3, 4, 5] | 1 | 3 | [2 ,3, 4] |
[1, 3, 5] | 1 | 2 | [3, 5] |
My solution to the ### problem
import java.util.*;
class Solution {
public int[] solution(int[] numbers, int num1, int num2) {
int[] answer = Arrays.copyOfRange(numbers, num1, num2 + 1);
return answer;
}
}
Solution Explanation
There is no direct method for slicing an array in Java.
However, you can copy parts of an array to create a new array.
For example, you can slice an array using the Arrays.copyOfRange() method. The above problem was solved by using that method to slice and copy into a new array.
In the example above, Arrays.copyOfRange(numbers, num1, num2 + 1) creates a partial array of num1 through num2 from the array numbers. The reason for the +1 is to include num2 as well.