В настоящее время я работаю над школьным проектом, который будет анализировать текстовые файлы, содержащие разные инструкции о перемещении. Эти инструкции затем помещаются в древовидную структуру, которая всегда отрывается справа с новой инструкцией, а слева - с тем, как каждая инструкция может идти.Что заставляет мою программу обрабатывать вещи дольше, чем нужно?
Это будет выглядеть примерно так:
FORW
/ \
2 LEFT
/ \
90 Rep
/ \
FORW FORW
/ /
4 2
В любом случае, не вдаваясь в гораздо более подробно о специфике моей программы мой вопрос к вам, как я могу улучшить эту часть программы, чтобы она стала Быстрее?
Как вы можете видеть, я попытался использовать построитель строк, чтобы ускорить процесс, но он не сильно изменился, и на данный момент я отчасти из идей, поэтому любая помощь будет принята с большой благодарностью.
Эта программа протестирована с большим количеством тестовых примеров, и если какая-либо из них занимает больше 7 секунд, она не работает, и теперь это происходит.
import java.util.ArrayList;
// Ett syntaxträd
public class CreateLines{
private boolean penDown; // 1 om pennan är nere 0 om inte.
private double x1, x2, y1, y2; // x,y-koordinat
private int degrees; // vinkel v
private String color; // nuvarande färg
private double piDegrees;
private double decimals;
private ArrayList<String> result;
public CreateLines() {
penDown = false;
x1 = 0;
x2 = 0;
y1 = 0;
y2 = 0;
degrees = 0;
color = "#0000FF";
// For optimization.
decimals = 100000;
}
public StringBuilder treeSearch (Operation tree) {
// Some variables we use down here:
double x1 = this.x1;
double y1 = this.y1;
double x2;
double y2;
int numberNode;
StringBuilder str = new StringBuilder();
switch (tree.operation) {
case FORW:
piDegrees = Math.PI*degrees/180;
numberNode = tree.evaluate();
x2 = x1 + (numberNode * Math.cos(piDegrees));
y2 = y1 + (numberNode * Math.sin(piDegrees));
x2 = (double)Math.rint(x2 * decimals)/decimals;
y2 = (double)Math.rint(y2 * decimals)/decimals;
this.x1 = x2;
this.x2 = x2;
this.y1 = y2;
this.y2 = y2;
// If penDown then we print otherwise not.
if (penDown){
str.append(color + " " + x1 + " " + y1 + " " + x2 + " " + y2 + "\n");
if(tree.right == null){
return str;
}
return str.append(treeSearch((Operation) tree.right));
}
else{
if(tree.right == null){
return str;
}
return treeSearch((Operation) tree.right);
}
case BACK:
piDegrees = Math.PI*degrees/180;
numberNode = tree.evaluate();
x2 = x1 - (numberNode * Math.cos(piDegrees));
y2 = y1 - (numberNode * Math.sin(piDegrees));
x2 = (double)Math.rint(x2 * decimals)/decimals;
y2 = (double)Math.rint(y2 * decimals)/decimals;
this.x1 = x2;
this.x2 = x2;
this.y1 = y2;
this.y2 = y2;
// If penDown then we print otherwise not.
if (penDown){
str.append(color + " " + x1 + " " + y1 + " " + x2 + " " + y2 + "\n");
if(tree.right == null){
return str;
}
return str.append(treeSearch((Operation) tree.right));
}
else{
if(tree.right == null){
return str;
}
return treeSearch((Operation) tree.right);
}
case LEFT:
numberNode = tree.evaluate();
this.degrees = degrees+numberNode;
if (penDown){
if(tree.right == null){
return str;
}
return treeSearch((Operation) tree.right);
}
else{
if(tree.right == null){
return str;
}
return treeSearch((Operation) tree.right);
}
case RIGHT:
numberNode = tree.evaluate();
this.degrees = degrees-numberNode;
if (penDown){
if(tree.right == null){
return str;
}
return treeSearch((Operation) tree.right);
}
else{
if(tree.right == null){
return str;
}
return treeSearch((Operation) tree.right);
}
case DOWN:
this.penDown = true;
if(tree.right == null){
return str;
}
return treeSearch((Operation) tree.right);
case UP:
this.penDown = false;
if(tree.right == null){
return str;
}
return treeSearch((Operation) tree.right);
case COLOR:
this.color = tree.color.toUpperCase();
if (penDown){
if(tree.right == null){
return str;
}
return treeSearch((Operation) tree.right);
}
else{
if(tree.right == null){
return str;
}
return treeSearch((Operation) tree.right);
}
case REP:
// if we got a rep instruction to the left we
if(tree.right == null){
for(int i = 0; i < tree.rep; i++){
str.append(treeSearch((Operation) tree.left));
}
return str;
}
else {
for(int i = 0; i < tree.rep; i++){
str.append(treeSearch((Operation) tree.left));
}
return str.append(treeSearch((Operation)tree.right));
}
}
assert false; // borde aldrig kunna hända
return null;
}
}
Я не думаю, что это правильная структура для этого. – MightyPork
Это часть задания, поэтому у меня нет такого выбора в этом вопросе. – Dreamus
Возможно, это лучше подходит для http://codereview.stackexchange.com –