In: Computer Science
I want to print out the array as well as its intersection, and also it doesn't show the time elapsed after 100,000
Missing is: 1,000,000 and 10,000,000
import java.util.Random;
import java.util.HashSet;
import java.util.Arrays;
public class array_intersect {
public static void main(String[] args)
{
for(int i=1000; i <= 10000000; i= i*10)
{
Integer[] array1 = generate_random_array(i);
Integer[] array2 = generate_random_array(i);
long startTime = System.nanoTime();
get_intersection(array1, array2);
long stopTime = System.nanoTime();
long elapsedTime = stopTime - startTime;
System.out.println("Time elapsed for dataset of " + i + " points :
"+ elapsedTime + " in nanoseconds");
}
}
public static Integer[] generate_random_array(int size)
{
Random rand = new Random();
Integer[] return_array = new Integer[size];
for(int i=0;i< size ; i ++)
{
return_array[i] = rand.nextInt(size);
}
return return_array;
}
public static Integer[] get_intersection(Integer[] array1,
Integer[] array2)
{
HashSet<Integer> set = new HashSet<>();
set.addAll(Arrays.asList(array1));
set.retainAll(Arrays.asList(array2));
Integer[] intersection = {};
intersection = set.toArray(intersection);
return intersection;
}
}
Its is printing after 100,000 it just takes more time.
As you can see from the above picture, it takes 939930274600 nanoseconds( ~15 mins) for printing 1000,000 data sets. So if you wait it will print all the results.
For printing, the arrays and insection will mess up your console. I will suggest you avoid it but still, I have provided the code(its highlighted) for that.
Program
import java.util.Random;
import java.util.HashSet;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
for (int i = 1000; i <=
10000000; i = i * 10) {
Integer[] array1
= generate_random_array(i);
Integer[] array2
= generate_random_array(i);
long
startTime = System.nanoTime();
Integer[]
intersection=get_intersection(array1, array2);
long stopTime =
System.nanoTime();
long elapsedTime
= stopTime - startTime;
System.out.println("Array1: "+Arrays.toString(array1));
System.out.println("Array2: "+Arrays.toString(array2));
System.out.println("Intersection:
"+Arrays.toString(intersection));
System.out.println("Time elapsed for dataset of " + i + " points :
" + elapsedTime + " in nanoseconds");
}
}
public static Integer[] generate_random_array(int
size) {
Random rand = new Random();
Integer[] return_array = new
Integer[size];
for (int i = 0; i < size; i++)
{
return_array[i]
= rand.nextInt(size);
}
return return_array;
}
public static Integer[] get_intersection(Integer[]
array1, Integer[] array2) {
HashSet<Integer> set = new
HashSet<>();
set.addAll(Arrays.asList(array1));
set.retainAll(Arrays.asList(array2));
Integer[] intersection =
{};
intersection =
set.toArray(intersection);
return intersection;
}
}
If you have any further doubts feel free to comment