hi guys i am writing a program where it takes number pairs as input and form the clusters based on the common numbers between the pairs.This is the code i have written so far:
public class cluster
{
public static void main(String args[]) throws FileNotFoundException
{ ArrayList<arraylist><integer>> x = new ArrayList();
ArrayList y = new ArrayList();
ArrayList k=new ArrayList();
ArrayList z=new ArrayList();
ArrayList w=new ArrayList();
System.out.println("how many");
Scanner s=new Scanner(System.in);
int n=s.nextInt();
for(int i=1;i<=n;i++)
{
System.out.println("enter pairs");
int a=s.nextInt();
int b=s.nextInt();
if(!y.contains(a) && !y.contains(b)&& x.isEmpty())
{ y.add(a);
y.add(b);
x.add(y);
System.out.println(y);
}
else if(!y.contains(a) && !y.contains(b)&& !x.isEmpty() && k.isEmpty())
{
k.add(a);
k.add(b);
System.out.println(k);
System.out.println(y);
}
else if(!y.contains(a) && !y.contains(b)&& !x.isEmpty() && !k.isEmpty() && z.isEmpty())
{
if(k.contains(a)&& !k.contains(b))
{
k.add(b);
System.out.println(k);
}
else if(!k.contains(a)&& k.contains(b))
{
k.add(a);
System.out.println(k);
System.out.println(y);
}
else if(!k.contains(a)&& !k.contains(b))
{
z.add(a);
z.add(b);
System.out.println(z);
System.out.println(k);
System.out.println(k);
}
}
else if(!y.contains(a) && !y.contains(b)&& !x.isEmpty() && !k.isEmpty() && !z.isEmpty())
{
if(z.contains(a)&& !z.contains(b))
{
z.add(b);
System.out.println(z);
}
else if(!z.contains(a)&& z.contains(b))
{
z.add(a);
System.out.println(z);
}
else if(!z.contains(b) && !z.contains(a))
{
w.add(a);
w.add(b);
System.out.println(w);
} }
Now what my problem is if i am entering 5 distinct pairs i am able to get 4 distinct clusters but if my 5th pair is also a unique pair then my 5th pair is added to the 4th pair forming that as cluster.How can i write nested if loops if there are 1000 pairs .please guys help me how to make this code work even for 1000 pairs
Input:
1 2
2 4
3 5
6 7
8 9
11 12
Expected output:
1 2 4
3 5
6 7
8 9
11 12
My output:
1 2 4
3 5
6 7
8 9 11 12