Advertisement
Guest User

Untitled

a guest
Dec 7th, 2016
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.75 KB | None | 0 0
  1. case class Point(x: Int, y: Int, alive: Boolean)
  2.  
  3. case class Universe(points: Vector[Point], size: Int) {
  4. def apply(x: Int, y: Int) = points((x % size) * (y % size))
  5. }
  6.  
  7. def aliveNeighbors(u: Universe)(px: Int, py: Int): Int = {
  8. val xs = for {
  9. x <- (py - 1) to (py + 1)
  10. y <- (px - 1) to (px + 1) if x != px && y != py
  11. } yield {
  12. if (u(x, y).alive) 1
  13. else 0
  14. }
  15. xs.sum
  16. }
  17.  
  18. def life(u: Universe): Universe = {
  19. val aliveNeighborsU = aliveNeighbors(u)(_, _)
  20. val liveLimits = 2 to 3
  21. val updatedPoints = u.points map {
  22. case p @ Point(x, y, false) if aliveNeighborsU(x, y) == 3 => p.copy(alive = true)
  23. case p @ Point(x, y, true) if !liveLimits.contains(aliveNeighborsU(x, y)) => p.copy(alive = false)
  24. }
  25. u.copy(points = updatedPoints)
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement