3 ms·
That looks like a nice solution to me, some of the Javascript idioms I'm not familiar with, but after looking at it for a while it seems you're using what I'd c
by roel_v 14y ago
That looks like a nice solution to me, some of the Javascript idioms I'm not familiar with, but after looking at it for a while it seems you're using what I'd consider the 'best' method of generating it - looping over each cell and calculating the height based on the distance to the 'top' (or 'center', depending on how you look at it).
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), but funnily enough nobody ever went that route, not even my colleagues who did it.
- 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.