I have an object ArrayList like:
{{"ObjectName",[[1,3],[11,24]]},
{"ObjectName2",[[3,4],[5,6],[12,20]]},
{"ObjectName3",[[30,38]]}}
The object is formed by a string(object name) and many pairs of integer list inside a integer list.
A pair of integer list like [11,24]: means from 11cm to 24cm, a length range.
How could I use Java code and less bigO to check if the pairs of length of 1 object has an intersection with other objects' length range. Like ObjectName2 has a pair of integer [12,20] is intersect with ObjectName's [11,24].
I have a sudo code has bigO(n^3):
for(Object o1 : Arraylist){
for(Object o2 : Arraylist){
for(int x = 0; x < o1.lengthlist.size(),x++){
if(o1.lengthlist.get(x)[0]>=o2.lengthlist.get(x)[0]
&& o1.lengthlist.get(x)[1]<=o2.lengthlist.get(x)[1])
{got the intersection part}
}
}
}
I did a full example of how to do it.
Class 1
package intersectioninintegerlist;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
*
* @author Ahmad
*/
public class IntersectionInIntegerList {
public static void main(String[] args) {
List<Pair> lst1 = new ArrayList<>(Arrays.asList(new Pair(1,3), new Pair(11,24)));
Obj obj1 = new Obj("obj1", lst1);
List<Pair> lst2 = new ArrayList<>(Arrays.asList(new Pair(3,4), new Pair(5,6), new Pair(12,20)));
Obj obj2 = new Obj("obj2", lst2);
List<Pair> lst3 = new ArrayList<>(Arrays.asList(new Pair(30,38)));
Obj obj3 = new Obj("obj3", lst3);
List<Obj> objs = new ArrayList<>(Arrays.asList(obj1, obj2, obj3));
for(int i = 0; i < objs.size(); i++){
for(int j = i+1; j < objs.size(); j++){
findIntersect(objs.get(i), objs.get(j));
}
}
}
private static void findIntersect(Obj o1, Obj o2) {
System.out.println(o1.name + " - " + o2.name);
for(Pair p1 : o1.pairs){
for(Pair p2 : o2.pairs){
int A = p1.i1;
int B = p1.i2;
int X = p2.i1;
int Y = p2.i2;
if((A >= X && A <= Y) || (X >= A && X <= B)){
System.out.println(o1.name + " intersects with " + o2.name);
}
}
}
}
}
Class2
package intersectioninintegerlist;
import java.util.List;
/**
*
* @author Ahmad
*/
public class Obj {
public String name;
public List<Pair> pairs;
public Obj(String n, List<Pair> p){
name = n;
pairs = p;
}
}
Class3
package intersectioninintegerlist;
/**
*
* @author Ahmad
*/
public class Pair {
int i1;
int i2;
public Pair(int _i1, int _i2){
i1 = _i1;
i2 = _i2;
}
}
Hope It helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.