Fabio Carello
Fabio Carello

Reputation: 1102

Parsing variable number of lines

I need to parse this kind of input:

Each symbol (A-Z) defines a set containing all the values in the associated line. { } represent an empty set. No one symbol can be repeated.

Examples of input:

3
Z = { 5 6 2 }
X = { 2 5 7 }
Y = { 2 4 3 0 }

or

2
X = { 7 }
Y = { }

I have to store these sets and identify them by the associated symbol. For reach my goal I used a java Map that stores <set_id, set_values> couples where each symbol is a set_id key for the map.

HashMap<Character, List<Integer>> sets = new HashMap<Character, List<Integer>>();

Here is the rest of the code. I wish someone could give me some advice to find another way and improve the performances.

    BufferedReader r =
            new BufferedReader (new InputStreamReader(System.in));
    String line = null;

    /* Stores couple <Set_id, Set_values> */
    HashMap<Character, List<Integer>> sets = new HashMap<Character, List<Integer>>();

    /* number of sets, first line parsed */
    int n_sets = Integer.parseInt(r.readLine());

    Character set_id = null;
    Character current = null;
    List<Integer> set_values = null;

    System.out.println("DEBUG: Will perform "+n_sets+" iteration");
    while(n_sets != 0){
        set_values = new ArrayList<Integer>();
        line = r.readLine();
        set_id = new Character(line.charAt(0));

        /* Set input example : Z = { 5 6 2 } */
        for(int i=0; i<line.length(); i++){
            current = line.charAt(i);
            /* Fill values list for current set */
            if(Character.isDigit(current))
                set_values.add(Integer.parseInt(current.toString()));
        }

        /*Put current <set_id, set_values> into map */
        sets.put(set_id, set_values);
        -- n_sets;
    }

Upvotes: 1

Views: 95

Answers (1)

Inglonias
Inglonias

Reputation: 542

Try using split() to eliminate having to process the whitespace (which always fails your criteria anyway)

    String[] splitLine = line.split(" ");
    for(int i=0; i<splitLine.length; i++){
                if (Character.isDigit(splitLine[i].charAt(0)))
                   set_values.add(Integer.parseInt(current.toString()));
            }

Upvotes: 1

Related Questions