Reputation: 1101
As indicated by the question. I'm doing an assignment where the boarder is defined to be some number while the inner 2d array need some calculation. I wrote:
for(int col = 0; col < this.w; col++){
energyMatrix[0][col] = 195075;
energyMatrix[this.h-1][col] = 195075;
}
for(int row = 1; row < this.h - 1; row++){
energyMatrix[row][0] = 195075;
energyMatrix[row][this.w-1] = 195075;
}
but is there another (faster) way to do this?
Upvotes: 1
Views: 1995
Reputation: 882156
There may be a number of different ways to achieve the same thing, if you'd just tell us which language you're actually coding it in :-) What you have is valid for (at a minimum) C, C++ and Java.
However, it's unlikely any of them will be much faster than what you have there. It's more likely that you'll get better performance improvements if you think more on a macro level (things like algorithm selection, caching and so on) rather than at this level of detail.
One thing you could try, although I still maintain it'll be of dubious improvement, would be to minimise the size of the second loop by doing more work in the first:
if (this.h >= this.w) {
for (int i = 0; i < this.w; i++) {
energyMatrix[0][i] = 195075;
energyMatrix[this.h-1][i] = 195075;
energyMatrix[i][0] = 195075;
energyMatrix[i][this.w-1] = 195075;
}
for (int i = this.w + 1; i < this.h; i++) {
energyMatrix[i][0] = 195075;
energyMatrix[i][this.w-1] = 195075;
}
} else {
for (int i = 0; i < this.h; i++) {
energyMatrix[i][0] = 195075;
energyMatrix[i][this.w-1] = 195075;
energyMatrix[0][i] = 195075;
energyMatrix[this.h-1][i] = 195075;
}
for (int i = this.h + 1; i < this.w; i++) {
energyMatrix[0][i] = 195075;
energyMatrix[this.h-1][i] = 195075;
}
}
This may remove some of the code overhead in running loops but, as I stated, I don't think you'll get the performance improvement out of this that you expect.
And, as with all optimisation attempts, you should measure, not guess! Try it with real data and, if the benefit doesn't outweigh the cost (of the more complicated code), ditch it.
Upvotes: 1