-2
  for (int i = 0; i < 19; i++) {
         long t1 = System.nanoTime();
         long total = 0;
         for (int j = 0; j < 5000; j++) {
            x.algorithm1(randomArray[i]);
            long t2 = System.nanoTime();
            long elapsed = t2 - t1;
            total += elapsed;
         }
         long averageTime = 0;
         averageTime= total / 5000;
         matrix[i][0] = averageTime;
      }

  /* Running Algorithm 2 */
  for (int i = 0; i < 19; i++) {
     long t1 = System.nanoTime();
     long total = 0;
     for (int j = 0; j < 5000; j++) {
        x.algorithm2(randomArray[i]);
        long t2 = System.nanoTime();
        long elapsed = t2 - t1;
        total += elapsed;
     }
     long averageTime = 0;
     averageTime = total / 5000;
     matrix[i][1] = averageTime;
  } 

I have 3 of these for loops that basically do the same thing however the line "x.algorithm2(randomArray[i]);" changes to a different algorithm in each different for loop. How can I reduce this repetitive code to only change the algorithm being called?

amkirila
  • 7
  • 1

1 Answers1

1

Here's an example of what you could do using functional interfaces and generics:

public static <T> void runAlgorithm(long[][] matrix, Consumer<T> tConsumer, T[] tArray) {
    for (int i = 0; i < 19; i++) {
        long t1 = System.nanoTime();
        long total = 0;
        for (int j = 0; j < 5000; j++) {
            tConsumer.accept(tArray[i]);
            long t2 = System.nanoTime();
            long elapsed = t2 - t1;
            total += elapsed;
        }
        long averageTime = 0;
        averageTime = total / 5000;
        matrix[i][1] = averageTime;
    }
}

public static void main(String[] args) {

    long[][] matrix1 = null; // ???
    Integer[] randomInts = new Integer[] {}; // ???
    runAlgorithm(matrix1, Algorithms::algorithmOnInts, randomInts);


    long[][] matrix2 = null; // ???
    Object[] randomObjects = new Object[] {}; // ???
    runAlgorithm(matrix2, Algorithms::algorithmOnObjects, randomObjects);
}

public static class Algorithms {
    public static void algorithmOnInts(Integer i) {}
    public static void algorithmOnObjects(Object o) {}
}
xtratic
  • 4,600
  • 2
  • 14
  • 32