dimanche 1 mars 2015

Substitute statements in code with loops in Java



I have these two pieces of code:



int prevY = 0;
// this is the function InsertionSort applied to i
StdDraw.setPenColor(Color.blue);
for (int i = 1; i <= N; i++) {
int x = i;
int y = runInsertion(i);
int prevX = i - 1;
StdDraw.setPenRadius(lineRadius);
StdDraw.line(prevX, prevY, x, y);
StdDraw.setPenRadius(pointRadius);
StdDraw.point(x, y);
prevY = y;
}

prevY = 0;
// this is the function SelectionSort applied to i
StdDraw.setPenColor(Color.black);
for (int i = 1; i <= N; i++) {
int x = i;
int y = runSelection(i);
int prevX = i - 1;
StdDraw.setPenRadius(lineRadius);
StdDraw.line(prevX, prevY, x, y);
StdDraw.setPenRadius(pointRadius);
StdDraw.point(x, y);
prevY = y;
}


They both do the same thing except for a minor change in the color that will be used and in the sorting algorithm that will be used.


Is there any way to make an array for the colors and the sorting algorithms like:



String[] algorithms = {"runInsertion", "runSelection"}
String[] colors = {"blue", "black"};


And then with a for loop call the appropriate index so that the code has been shortened.


I know this will not work as I proposed it, but I just want to know if there is a way or a specific method that lets me do this.




Aucun commentaire:

Enregistrer un commentaire