Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Description:
- 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.
- Input sample:
- File containing two lists of ascending order sorted integers, comma delimited, one per line. e.g.
- 1,2,3,4;4,5,6
- 7,8,9;8,9,10,11,12
- Output sample:
- Print out the ascending order sorted intersection of the two lists, one per line
- e.g.
- 4
- 8,9
- */
- import java.io.BufferedReader;
- import java.io.FileReader;
- import java.util.*;
- public class intersection {
- public static void main(String[] args) throws Exception {
- FileReader input = new FileReader(args[0]);
- BufferedReader bufRead = new BufferedReader(input);
- String line = bufRead.readLine();
- while(line != null) {
- interSect(line);
- line = bufRead.readLine();
- }
- bufRead.close();
- System.exit(0);
- }
- private static void interSect(String s) {
- //most of this rubbish is because of the way the program expects
- //the input and output to be formatted
- String[] bothSets = s.split(";");
- String[] setA = bothSets[0].split(",");
- String[] setB = bothSets[1].split(",");
- Set<String> a = new TreeSet<String>(Arrays.asList(setA));
- Set<String> b = new TreeSet<String>(Arrays.asList(setB));
- a.retainAll(b);
- String z = a.toString();
- //remove the leading [ and trailing ] that TreeSet.toString adds
- z = z.substring(1, z.length()-1);
- String newString = "";
- //remove the spaces between the elements or the auto marker
- //fails the solution
- for(int i = 0; i < z.length(); i++) {
- if(z.charAt(i) != ' ')
- newString += z.charAt(i);
- }
- /*FINALLY, print out the damn thing */
- System.out.println(newString);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement