voronoi_diagram.sf 734 B

1234567891011121314151617181920212223242526272829303132
  1. #!/usr/bin/ruby
  2. #
  3. ## https://rosettacode.org/wiki/Voronoi_diagram
  4. #
  5. require('Imager')
  6. func generate_voronoi_diagram(width, height, num_cells) {
  7. var img = %s<Imager>.new(xsize => width, ysize => height)
  8. var (nx,ny,nr,ng,nb) = 5.of { [] }...
  9. for i in ^num_cells {
  10. nx << rand(^width)
  11. ny << rand(^height)
  12. nr << rand(^256)
  13. ng << rand(^256)
  14. nb << rand(^256)
  15. }
  16. for y in ^height {
  17. for x in ^width {
  18. var j = (^num_cells -> min_by {|i| hypot(nx[i]-x, ny[i]-y) })
  19. img.setpixel(x => x, y => y, color => [nr[j], ng[j], nb[j]])
  20. }
  21. }
  22. return img
  23. }
  24. var img = generate_voronoi_diagram(500, 500, 25)
  25. img.write(file => 'VoronoiDiagram.png')