Find missing values from a sorted column and insert blank line in these positions

StackOverflow https://stackoverflow.com/questions/19885154

  •  30-07-2022
  •  | 
  •  

質問

Well, hello. What I am trying to do is this: I have a set of key,value pairs coming from a treemap which I write in a txt file. The output is like:

1 4 2 8 2
3 8 2 5 1
6 9 1 4 3
etc

the keys are in the first column and it is sorted. My goal is to find the position of missing values in the 1st column, insert a blank line for each missing number and write them to the file without the first column. So the list in the file would hopefully be like that:

4 2 8 2
         //blank line
8 2 5 1
         //blank line
         //blank line
9 1 4 3
etc

I've tried to count the difference between every key line and display a line like that, but nothing. Any suggestion would be appreciated.

...
int i = 0;
for (Integer key : rowMap.keySet()) {
                    String row = key + "";

                    for (Integer[] rows : rowMap.get(key)) {
                        for (Integer col : rows) {
                            row += " " + col;
                       }                          
       ------>      }
             i++;
             if (key.equals(i)){
                        writer.println(row);
                    }
                   else {
                      int dif = key-i;
                        int j;
                        for (j=1; j<=dif; j++){
                            writer.println("");
                        }
                        writer.println(row);
                    }
             }
                writer.close();
...
役に立ちましたか?

解決

The part around the dif is a little bit confusing. But it's less complex as you might think. Before you print a row for a certain key, you just have to print all the blank lines between the last key and the current (if there are some):

public static void print(SortedMap<Integer, int[]> map, PrintWriter writer) {
    int last = 1;
    for (int key : map.keySet()) {
        for (int i = last + 1; i < key; i++) {
            writer.println();
        }
        last = key;
        writer.println(Arrays.toString(map.get(key)));
    }
}

(For simplicity I just used Arrays.toString(...) to format a row. Replace it as desired.)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top