Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: Java
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
Posted 1-Apr-13 1:54am
Edited 1-Apr-13 3:13am
(no name)117.8K
v2

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

  Print Answers RSS
0 Kornfeld Eliyahu Peter 169
1 Zoltán Zörgő 139
2 George Jonsson 135
3 PIEBALDconsult 130
4 OriginalGriff 120
0 OriginalGriff 6,165
1 DamithSL 4,658
2 Maciej Los 4,107
3 Kornfeld Eliyahu Peter 3,649
4 Sergey Alexandrovich Kryukov 3,342


Advertise | Privacy | Mobile
Web03 | 2.8.141220.1 | Last Updated 1 Apr 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100