Print only those numbers that are double of another number in the array in Java
Use a HashSet<Integer>
to store double the value of each element:
Set<Integer> setOfArray = new HashSet<>();
for (int a : array) setOfArray.add(2 * a);
Then loop through the array again, looking for matching elements:
for (int a : array) {
if (setOfArray.contains(a)) {
System.out.println(a);
}
}
Or
IntStream.of(array).boxed().filter(setOfArray::contains)
.forEach(System.out::println);
This is a simple task: first, for each number n, store 2n in a set. Then, iterate through the numbers and check which of them is in the set.
import java.util.*;
public class DoubleNums {
public static void main(String[] args) {
int[] numbers = new int[]{2, 3, 9, 12, 7, 18}; //original array
HashSet<Integer> h = new HashSet<Integer>(); //set
for(int i = 0; i < numbers.length; i++) h.add(numbers[i] * 2);
for(int i = 0; i < numbers.length; i++){
if(h.contains(numbers[i])) System.out.println(numbers[i]);
}
}
}
Complexity: O(n)
A HashSet<Integer>
works like a simple set, but faster, because it uses properties of hash tables to add and find elements.
I saw that you asked for a solution that started with your own code...
I know it's faster but I assumed that we can find a solution using my code with some minor changes.
So I tried to understand what you were trying to do and I have not been able to decipher your method so starting from your macro I created a clearer version.
Changes
- I used an ArrayList (
list
) as support instead of your array (even
). TheList
is very convenient in your case because it has thecontains()
function and also its size is variable. - I took an even number in the array and looked for if there was at least one "half" of it.
Code
public static void main(String[] args) {
Random random = new Random();
int[] array = new int[20];
ArrayList<Integer> list = new ArrayList<>();
int evenNumber = 0;
for (int i = 0; i < array.length; i++) {
array[i] = random.nextInt(100);
}
System.out.println(Arrays.toString(array));
for (int i = 0; i < array.length; i++) {
// If I found an even number and this is NOT already in the list then I'll study it
if (array[i] % 2 == 0 && !list.contains(array[i])) {
evenNumber = array[i];
for (int j = 0; j < array.length; j++) {
// I add "evenNumber" to the list only if at least one its "half" exist in the array
if (array[j] * 2 == evenNumber) {
list.add(evenNumber);
// I dont need to search more, I already found its "half"!
break;
}
}
}
}
System.out.println("Doubled nums: " + list);
}
Sample output
[71, 88, 45, 97, 64, 31, 54, 12, 14, 86, 22, 42, 35, 44, 70, 65, 93, 85, 99, 14]
Doubled nums: [88, 44, 70]