In computer science, manipulating data in arrays is one of the basic tasks. Sometimes, it is required to filter out the data from the array based on certain criteria. In this article, we will discuss a simple problem of filtering out elements from an array based on a certain condition. Specifically, we will discuss the problem of finding all integers in an array that are less than a given value.
Problem Statement: Given an array of N integers and a value K. The task is to return a list of integers from the given array whose value is less than K.
Example: Input: arr[] = {17, 10, 20, 13, 7, 9}, K = 15 Output: List = [10, 13, 7, 9]
Input: arr[] = {10, 5, 8, 9, 1, 2}, K = 7 Output: List = [5, 1, 2]
Approach: One way to solve this problem is to iterate through the given array and add all elements that are less than the given value K to a new list. We can use ArrayLists in Java to create a dynamic list that can be expanded at runtime.
First, we create an ArrayList to store the output list. We traverse the input array and add all elements with values less than K to the ArrayList. Finally, we return the ArrayList.
Implementation: We can implement this approach in Java as follows:
import java.util.*;
class Test{
javastatic List<Integer> getSmaller(int arr[], int k){
List<Integer> al = new ArrayList<Integer>();
for(int i=0; i<arr.length; i++){
if(arr[i] < k)
al.add(arr[i]);
}
return al;
}
public static void main (String[] args) {
// Create a ArrayList
int arr[] = {10, 40, 80, 30, 20, 15};
List<Integer> al = getSmaller(arr, 30);
for(Integer x: al)
System.out.println(x);
}
}
Output: 10 20 15
Explanation: In the above code, we first create an ArrayList named 'al'. We then iterate through the input array using a for loop. Inside the for loop, we use an if condition to check if the current element of the array is less than the given value K. If it is, we add it to the ArrayList using the add() method. Finally, we return the ArrayList.
In the main method, we create an input array named 'arr'. We then call the getSmaller() method and pass the input array and the value K as arguments. The method returns an ArrayList of integers that are less than K. We then use a for-each loop to print all the elements of the ArrayList on the console.
Conclusion: In this article, we discussed a simple problem of finding all integers in an array that are less than a given value. We presented an approach to solve this problem using ArrayLists in Java. We also provided an implementation of this approach in Java. This problem can be solved using other programming languages and data structures as well.