(UVA) Simply Subsets - Solution

Link to the problem: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=437

Each set of numbers is kept in a set structure. Then, it is checked the numbers that are common between the sets, which allows us to know the relation between them.


import java.io.*;
import java.util.*;

class Main {
    public void process() throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       
        String line = br.readLine(); // first subset
        while (line != null) {
            String[] s = line.split("\\s");
            HashSet<Integer> firstSubset = new HashSet<>();
            for (int i = 0; i < s.length; i++) {
                firstSubset.add(Integer.parseInt(s[i]));
            }
           
            line = br.readLine(); // second subset
            s = line.split("\\s");
            HashSet<Integer> secondSubset = new HashSet<>();
            for (int i = 0; i < s.length; i++) {
                secondSubset.add(Integer.parseInt(s[i]));
            }
           
            int compareFirstWithSecond = 0;
            int compareSecondWithFirst = 0;
            Iterator it = firstSubset.iterator();
            while (it.hasNext()) {
                if (secondSubset.contains(it.next())) {
                    compareFirstWithSecond++;
                }
            }
            it = secondSubset.iterator();
            while (it.hasNext()) {
                if (firstSubset.contains(it.next())) {
                    compareSecondWithFirst++;
                }
            }
           
            if (compareFirstWithSecond == firstSubset.size() && compareSecondWithFirst == secondSubset.size()) {
                System.out.println("A equals B");
            }
            else if (compareFirstWithSecond == firstSubset.size()) {
                System.out.println("A is a proper subset of B");
            }
            else if (compareSecondWithFirst == secondSubset.size()) {
                System.out.println("B is a proper subset of A");
            }
            else if (compareFirstWithSecond == 0 && compareSecondWithFirst == 0) {
                System.out.println("A and B are disjoint");
            }
            else {
                System.out.println("I'm confused!");
            }
           
            line = br.readLine(); // first subset
        }
    }
   
    public static void main(String[] args) throws NumberFormatException, IOException {
        Main m = new Main();
        m.process();
       
        System.exit(0);
    }
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução