Contents

Elements at n intervals (with.Java)

   Sep 29, 2023     2 min read

In this article, we looked at the elements of n intervals (with.Java).

We’ll be 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 integer list num_list and an integer n, complete the solution function so that it returns a list containing the elements stored in n intervals from the first element in num_list to the last element.

Example input and output

num_list: [4, 2, 6, 1, 7, 6]

n: 2

result: [4, 6, 7]

My solution to the problem

class Solution {
    public int[] solution(int[] num_list, int n) {
        int answerLength = (int) Math.ceil((double) num_list.length / n);
        int[] answer = new int[answerLength];

        for (int i = 0; i < num_list.length; i += n) {
            int index = i / n;
            answer[index] = num_list[i];
        }

        } return answer;
    }
}
solution description

int answerLength = (int) Math.ceil((double) num_list.length / n);:

This part calculates the length of the new array answer.

The num_list.length represents the length of the input array num_list.

n is the given interval.

We divide it and perform a rounding operation to set the length so that we can fit all the remaining elements into the array.

int[] answer = new int[answerLength];:

Create the answer array based on the calculated answerLength.

This is the array that will eventually hold the elements extracted from num_list.

for (int i = 0; i < num_list.length; i += n) {:

This is the iteration part, which traverses the input array num_list, extracting elements at intervals n.

At the beginning of the iteration, i starts at 0.

int index = i / n;:

Calculate the index at which to store the element into the answer array.

Currently, i represents the index in num_list, which we need to store every n intervals, so we compute index.

index represents the index in the answer array.

answer[index] = num_list[i];:

Store the elements extracted from num_list in the answer array using the calculated index.

Extract the element located at index i and store it at position index in the answer array.

return answer;:

After executing all the iterations, the answer array contains the elements extracted from num_list at interval n.

Finally, we print the result by returning the answer array.

This code performs the task of extracting elements every interval n from the input array num_list and storing them in the answer array. This ensures that the ANSWER array contains the elements extracted from the input array at the desired interval in order.Performs the function of returning a column.