javascript - Trouble with a heightmap adjusting algorithm -


i have 2d grid of integers. user can pick location , increase or decrease number one. algorithm should adjust 8 adjacent locations there no more difference of 1 between them.

i've go things working there must edge case i'm missing after making few adjustments 1 of locations can go wonky (much more of difference one).

here screenshot of grid once goes wonky. wonky grid

the javascript is

var movedown = function (x, y) {     var updated = false;     if (x-1 >= 0 && math.abs(grid[x][y] - grid[x-1][y]) > 1) {         grid[x-1][y] -= 1;         updated = true;     }     if (x+1 < size && math.abs(grid[x][y] - grid[x+1][y]) > 1) {         grid[x+1][y] -= 1;         updated = true;     }     if (y-1 >= 0 && math.abs(grid[x][y] - grid[x][y-1]) > 1) {         grid[x][y-1] -= 1;         updated = true;     }     if (y+1 < size && math.abs(grid[x][y] - grid[x][y+1]) > 1) {         grid[x][y+1] -= 1;         updated = true;     }     if (x-1 >= 0 && y-1 >= 0 && math.abs(grid[x][y] - grid[x-1][y-1]) > 1) {         grid[x-1][y-1] -= 1;         updated = true;     }     if (x-1 >= 0 && y+1 < size && math.abs(grid[x][y] - grid[x-1][y+1]) > 1) {         grid[x-1][y+1] -= 1;         updated = true;     }     if (x+1 < size && y-1 >= 0 && math.abs(grid[x][y] - grid[x+1][y-1]) > 1) {         grid[x+1][y-1] -= 1;         updated = true;     }     if (x+1 < size && y+1 < size && math.abs(grid[x][y] - grid[x+1][y+1]) > 1) {         grid[x+1][y+1] -= 1;         updated = true;     }      if (updated) {         if (x-1 >= 0) { movedown(x-1, y); }         if (x+1 < size) { movedown(x+1, y); }         if (y-1 >= 0) { movedown(x, y-1); }         if (y+1 < size) { movedown(x, y+1); }         if (x-1 >= 0 && y-1 >= 0) { movedown(x-1, y-1); }         if (x-1 >= 0 && y+1 < size) { movedown(x-1, y+1); }         if (x+1 < size && y-1 >= 0) { movedown(x+1, y-1); }         if (x+1 < size && y+1 < size) { movedown(x+1, y+1); }     } } 

i've got fiddle here i've been using play things.

how can fix things make work properly?

as pointed out in comments, code recursive, , in situations hits infinite recursion.

when infinite recursion triggered, outcome depends on javascript engine being used. in versions, error message "uncaught rangeerror: maximum call stack size exceeded" appear in error console. (this case chrome.) other javascript engines may handle differently, , maybe in not-so-nice ways.

the unusual numerical values displayed if javascript engine interrupts execution , still refreshes page rendering (without executing code further).

you can implement original idea using for-loops, without using recursion.

you can ideas morphological image processing.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -