Click here to Skip to main content
15,867,756 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
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:
Java
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
Posted
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900