2 ms·
>Personally I consider the 'naive' version (as in: the first, easy to manually verify version one would bang out as a prototype) to be one where a matrix is pre
by Hupo 14y ago
>Personally I consider the 'naive' version (as in: the first, easy to manually verify version one would bang out as a prototype) to be one where a matrix is pre-allocated and each ring is filled in from the outside inwards (so first assign all 1's, then all 2's, and so on)
I'd consider the 'naive' version (and the first solution that popped to my mind pretty much instantly) to be where you first fill the grid with 1's, then then loop over the next level and add 1 and repeat until you're on the top. So like this for example:
function(a) {
a = a | 1; // add 1 to even numbers
var b = new Array(a),
i, y, x,
s = 0;
// initialize the array
for(y = 0; y < a; y++) {
b[y] = new Array(a);
for(x = 0; x < a; x++) {
b[y][x] = 0;
}
}
// turn it into a pyramid heightmap
for(i = a; i > 0; i--) {
for(y = s; y < i; y++) {
for(x = s; x < i; x++) {
b[y][x]++;
}
}
s++;
}
return b;
}
Though in JavaScript it's a bit more complex than it might otherwise be since you can't just declare a multi-dimensional int array in a single line. Anyway, I discarded this solution about as fast as I came up with it because I knew there'd be more clever ways to go about it, and came up with the offset calculation method a couple minutes after that. And amusingly enough I had to actually test and iterate this 'naive' version a bit before I got it running right, whereas my 'complex' solution worked on the first try. Funny how that goes.