I'm practicing algorithms and let's say we have an array with elements 2, 3, 9, 12, 7, 18
, then I want to print 18 only because it's double of 9. When I print the result it always displays much more lines, however, the printed numbers (if there are any) are good. How can I manage displaying the result properly? (Using only arrays.) I know it's a silly question but I tried so many ways and it was only worse.
Now, it shows me this for example (140 is correct, but the other line are not needed):
The following number is doubled of another number from the array: 0
The following number is doubled of another number from the array: 0
The following number is doubled of another number from the array: 140
The following number is doubled of another number from the array: 0
The following number is doubled of another number from the array: 0
My code:
public class DoubleNums {
public static void main(String[] args) {
Random random = new Random();
int[] array = new int[50];
int[] even;
int[] doubleNum;
int count = 0;
int doubles = 0;
for (int i = 0; i < array.length; i++) {
array[i] = random.nextInt(200);
System.out.println(array[i] + " ");
}
for (int j = 0; j < array.length; j++) {
even = new int[array.length];
if (array[j] % 2 == 0) {
even[count] = array[j];
count++;
}
for (int k = 0; k < array.length; k++) {
doubleNum = new int[array.length];
if (array[j] / 2 == array[k]) {
even[doubles] = k;
doubles++;
System.out.println("The following number is doubled of another number from the array: " + even[doubles]);
}
}
}
System.out.println("Number of even nums: " + count);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With