I am trying to solve this exercise Two Intervals Intersection, I think that I solved almost all the problem, but when I try the sample input I get 15 and 5, and I want to order that results, my idea is using an arraylist for the intervals, and then delete the duplicates, but I just want a better approach to solve this problem, if I enter as input 2 3 and 2 3 I get as output 2 3 and 2 3, that why I ask you a better approach to solve this exercise, any better ideas
thanks for help
this is my code so far
import java.util.*;
public class TwoIntervalIntersection {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int n1 = sc.nextInt();
int n2 = sc.nextInt();
int n3 = sc.nextInt();
int n4 = sc.nextInt();
if(n1 >= n3 && n1 <= n4){
System.out.print(n1);
System.out.print(" ");
}
if(n2 >= n3 && n2 <= n4){
System.out.print(n2);
System.out.print(" ");
}
if(n3 >= n1 && n3 <= n2){
System.out.print(n3);
System.out.print(" ");
}
if(n4 >= n1 && n4 <= n2){
System.out.print(n4);
}
}
}
Hey your approach isn’t bad though it’s better to store the things before print them in the end so you can change/swap/check their values before the final print in the console. To fix the part with the interval been posted on the wrong way you can do something like :
If you want to improve the program more the same swap mechanism may be added for the entered intervals of the users so when he enter “15 1” instead of “1 15” the program still works correct.