/** * Merges the rows. This function uses a heuristical approach that guarantiess to merge all rows * into one if there is no conflict at all. If there are conflicts the heuristic will be * best-efford but with linear runtime (given a a number of rows). * * @param rows Will be altered, if no conflicts occcured this wil have only one element. */ private static void mergeAllRowsIfPossible(ArrayList<Row> rows) { // use fixed seed in order to get consistent results (with random properties) Random rand = new Random(5711l); int tries = 0; // this should be enough to be quite sure we don't miss any optimalization // possibility final int maxTries = rows.size() * 2; // do this loop until we successfully merged everything into one row // or we give up until too much tries while (rows.size() > 1 && tries < maxTries) { // choose two random entries int oneIdx = rand.nextInt(rows.size()); int secondIdx = rand.nextInt(rows.size()); if (oneIdx == secondIdx) { // try again if we choose the same rows by accident continue; } Row one = rows.get(oneIdx); Row second = rows.get(secondIdx); if (one.merge(second)) { // remove the second one since it is merged into the first rows.remove(secondIdx); // success: reset counter tries = 0; } else { // increase counter to avoid endless loops if no improvement is possible tries++; } } }