Java solution using TreeSet; call random once every time
\npublic class RandomFlipMatrix {\n\n  private final int len;\n  private final int n_rows;\n  private final int n_cols;\n  private final TreeSet<Integer> treeSe
```\npublic class RandomFlipMatrix {\n\n  private final int len;\n  private final int n_rows;\n  private final int n_cols;\n  private final TreeSet<Integer> treeSet = new TreeSet<>();\n  private int currentLen;\n\n  public RandomFlipMatrix(int n_rows, int n_cols) {\n\n    this.len = n_cols * n_rows;\n    this.currentLen = len;\n    this.n_rows = n_rows;\n    this.n_cols = n_cols;\n  }\n\n  public int[] flip() {\n    if (currentLen == 0) return null;\n    int rnd = ThreadLocalRandom.current().nextInt(currentLen--);\n    Iterator<Integer> iterator = treeSet.iterator();\n    int lastSetIndex = -1, setIndex;\n    while (iterator.hasNext()) {\n      setIndex = iterator.next();\n      int intervalLen = setIndex - lastSetIndex - 1;\n      if (intervalLen <= rnd) {\n        rnd -= intervalLen;\n        lastSetIndex = setIndex;\n      } else {\n        break;\n      }\n    }\n    int index = lastSetIndex + rnd + 1;\n    treeSet.add(index);\n    return new int[] {index / n_cols, index % n_cols};\n  }\n\n  public void reset() {\n    currentLen = len;\n    treeSet.clear();\n  }\n}\n```
[]