Can someone tell me if the following crazy loop structure can be rewritten in a much nicer way? Right now it does everything I want it to.
// xi and yi stand for x and y axis input index
for (int xi = 0; xi < this.inputNumberOfColumnsAlongXAxis; xi++)
{
for (int yi = 0; yi < this.inputNumberOfColumnsAlongYAxis; yi++)
{
InputCell inputCell = new InputCell(xi, yi);
Synapse synapse = new Synapse(inputCell);
// add (inputDataScaleReductionOnXAxis * inputDataScaleReductionOnYAxis)
// number of synapses to a proximalSegment.
for (int x = 0; x < this.numberOfColumnsAlongXAxis; x++)
{
for (int y = 0; y < this.numberOfColumnsAlongYAxis; y++)
{
int inputX =
(int)Math.round(x * inputDataScaleReductionOnXAxis);
int inputY =
(int)Math.round(y * inputDataScaleReductionOnYAxis);
this.columns[(y * this.numberOfColumnsAlongXAxis) + x] =
new Column(this, inputX, inputY, x, y);
// only add the square of synapses directly under the proximal segment
while (xi < this.inputDataScaleReductionOnXAxis * (x + 1))
{
while (yi < this.inputDataScaleReductionOnYAxis * (y + 1))
{
this.getColumn(x, y).getProximalSegment().addSynapse(synapse);
}
}
}
}
}
}
It looks like you have a 2-D data structure of cells and an
O(N^3)initialization process where theNis the number of cells. That looks kind of expensive … but that is only a significant issue if N is very large or the process is done frequently.Anyway, I cannot see anything in the code that can obviously be simplified … assuming that the current algorithm reflects the requirements. It would appear that the 6 levels of looping are inherent in the problem. Some computations are like that.
The only possibility I can see is that
Nsynapses withO(N^2)connections (I think that is what you are doing) … is somehow unrealistic. In other words, we can only suggest non-trivial improvements if we actually understand the problem you are trying to solve with this code.Note that I am not saying “As a rule, if something that complex works, don’t mess with it.”. What I’m saying is that:
“If it works don’t mess with it” is … IMO … a poor excuse for brushing problems under the carpet without giving them proper thought.
And “Don’t bother trying to optimize because usually the extra time and effort produces nothing …” is simply another formulation of the same excuse. To me, it says “I’m so good that my initial code cannot be improved on” or “I’m so bad that I cannot ever find decent optimizations” or “Too bad … the customer shouldn’t be expecting decent performance anyway”.
Note that this is significantly different from the standard (and valid) advice which is … “Profile before you optimize”.