Advertisement
Guest User

Untitled

a guest
Aug 30th, 2012
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.77 KB | None | 0 0
  1. /*
  2. Description:
  3.  
  4. You are given two sorted list of numbers(ascending order). The lists themselves are comma delimited and the two lists are semicolon delimited. Print out the intersection of these two sets.
  5.  
  6. Input sample:
  7.  
  8. File containing two lists of ascending order sorted integers, comma delimited, one per line. e.g.
  9.  
  10. 1,2,3,4;4,5,6
  11. 7,8,9;8,9,10,11,12
  12. Output sample:
  13.  
  14. Print out the ascending order sorted intersection of the two lists, one per line
  15. e.g.
  16.  
  17. 4
  18. 8,9
  19.  
  20. */
  21.  
  22. import java.io.BufferedReader;
  23. import java.io.FileReader;
  24. import java.util.*;
  25.  
  26. public class intersection {
  27.  
  28.     public static void main(String[] args) throws Exception {
  29.    
  30.         FileReader input = new FileReader(args[0]);
  31.         BufferedReader bufRead = new BufferedReader(input);
  32.         String line = bufRead.readLine();
  33.        
  34.         while(line != null) {
  35.             interSect(line);
  36.             line = bufRead.readLine();
  37.         }
  38.         bufRead.close();
  39.         System.exit(0);
  40.     }
  41.    
  42.     private static void interSect(String s) {
  43.        
  44.         //most of this rubbish is because of the way the program expects
  45.         //the input and output to be formatted
  46.        
  47.         String[] bothSets = s.split(";");
  48.         String[] setA = bothSets[0].split(",");
  49.         String[] setB = bothSets[1].split(",");
  50.        
  51.         Set<String> a = new TreeSet<String>(Arrays.asList(setA));
  52.         Set<String> b = new TreeSet<String>(Arrays.asList(setB));
  53.         a.retainAll(b);
  54.        
  55.         String z = a.toString();
  56.         //remove the leading [ and trailing ] that TreeSet.toString adds
  57.         z = z.substring(1, z.length()-1);
  58.         String newString = "";
  59.        
  60.         //remove the spaces between the elements or the auto marker
  61.         //fails the solution
  62.         for(int i = 0; i < z.length(); i++) {
  63.             if(z.charAt(i) != ' ')
  64.                 newString += z.charAt(i);
  65.         }
  66.         /*FINALLY, print out the damn thing */
  67.         System.out.println(newString);
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement