Advertisement
Guest User

Untitled

a guest
Mar 3rd, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Julia 1.82 KB | None | 0 0
  1. module LandscapeColouring
  2.  
  3.   global color_count = 0
  4.   global dx = [1, -1, 0, 0]
  5.   global dy = [0, 0, 1, -1]
  6.   global lookforminima = true
  7.   # TODO: pass less variables.
  8.  
  9.   # Return true if moving in the direction of the neighbour corresponds to moving
  10.   # towards a 'well'.
  11.   function moving_towards_well(source, neighbour)
  12.     return lookforminima ? (source >= neighbour) : (source <= neighbour)
  13.   end
  14.  
  15.   function df_search(i, j)
  16.     global dx, dy, color_count
  17.     visited[i, j] = true
  18.     for d = 1:4
  19.       x = i + dx[d]
  20.       y = j + dy[d]
  21.       # Not interested in points beyond matrix bounds.
  22.       if (x == 0 || y == 0 || x > n || y > m) continue end
  23.       # Not interested in neighbouring point if the gradient is positive.
  24.       if (!moving_towards_well(z_values[i, j], z_values[x, y])) continue end
  25.       if (z_color[x, y] == 0 && visited[x, y] == false)
  26.         df_search(x, y)
  27.       end
  28.       # This may overwrite previous color in (i, j), but it doesn't matter since
  29.       # for saddle point we pick at random.
  30.       z_color[i, j] = z_color[x, y]
  31.     end
  32.     # If point was not colored after looking at all neighbours, the point has no
  33.     # neighbours with non-positive gradient, so is a local minima.
  34.     if (z_color[i, j] == 0)
  35.       color_count += 1
  36.       z_color[i, j] = color_count
  37.     end
  38.   end
  39.  
  40.   function color_landscape(_z_values, _lookforminima)
  41.     global color_count = 0
  42.     global z_values = _z_values
  43.     global lookforminima = _lookforminima
  44.     global n = size(z_values)[1]
  45.     global m = size(z_values)[2]
  46.     global visited = fill(false, n, m)
  47.     global z_color = fill(0, n, m)
  48.     for i = 1:n
  49.       for j = 1:m
  50.         if (z_color[i, j] == 0)
  51.           df_search(i, j)
  52.         end
  53.       end
  54.     end
  55.     return z_color, color_count
  56.   end
  57.  
  58. end # module LandscapeColouring
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement