Contents

Transforming a sequence based on conditions 1, How to control an array based on conditions (with.Java)

   Oct 7, 2023     2 min read

In this article, we learned about converting a sequence to fit a condition.

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

You are given an array of integers, arr.

For each element in arr, divide by 2 if the value is an even number greater than or equal to 50, and multiply by 2 if it is an odd number less than or equal to 50.

Complete the solution function to return the resulting array of integers.

Example input and output
arrresult
[1, 2, 3, 100, 99, 98][2, 2, 6, 50, 99, 49]

My solution to the problem

class Solution {
    public int[] solution(int[] arr) {
        int[] answer = new int[arr.length];
        for(int i = 0; i < arr.length; i++){
            if(arr[i] >= 50 && arr[i] % 2 == 0){
                answer[i] = arr[i] / 2;
            }else if(arr[i] < 50 && arr[i] % 2 != 0){
                answer[i] = arr[i] * 2;
            }else{
                answer[i] = arr[i];
            }
        }
    } return answer;
}
Solution

int[] answer = new int[arr.length]; : Create an array answer with the same length as the input array arr to store the result.

for(int i = 0; i < arr.length; i++) : Iterate over the input array arr, examining each element.

if(arr[i] >= 50 && arr[i] % 2 == 0) : If the current element is greater than or equal to 50 and is an even number:

Store the current element divided by 2 in the answer array.

else if(arr[i] < 50 && arr[i] % 2 != 0) : If the current element is less than 50 and odd:

Store the value of the current element multiplied by 2 in the ANSWER array.

else : If the above two conditions are not satisfied (i.e., greater than 50 but not an even number, or less than 50 but not an odd number):

Store the current element as it is in the answer array.

return answer;: Returns the answer array with the operation finally completed.