PageRenderTime 45ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/cgol.clj

http://github.com/VivienBarousse/cgol
Clojure | 99 lines | 85 code | 13 blank | 1 comment | 21 complexity | fbe02f1fc1357776b0456b3f8f724db1 MD5 | raw file
  1. (use '[clojure.string :only (split-lines)])
  2. (defn readBoard
  3. [filename]
  4. (defn readLine
  5. [line]
  6. (for [c (.toCharArray line)]
  7. (if (= (int c) 35) ; 35 is #
  8. 1
  9. 0
  10. )
  11. )
  12. )
  13. (map readLine (split-lines (slurp filename)))
  14. )
  15. (defn cgol
  16. [brd]
  17. (defn line
  18. [y]
  19. (nth brd y))
  20. (defn cell
  21. [x y]
  22. (nth (line y) x))
  23. (defn neighbours
  24. [x y]
  25. (for [i [(- x 1) x (+ x 1)]
  26. j [(- y 1) y (+ y 1)]
  27. :when (and
  28. (or (not (= x i)) (not (= y j)))
  29. (>= i 0)
  30. (>= j 0)
  31. (< j (count brd))
  32. (< i (count (nth brd j)))
  33. (= 1 (cell i j)))]
  34. [i j]
  35. )
  36. )
  37. (defn neighboursCount
  38. [x y]
  39. (count (neighbours x y))
  40. )
  41. (defn buildLine
  42. [y]
  43. (for [x (range (count (line y)))]
  44. (if
  45. (or (and
  46. (= 1 (cell x y))
  47. (= 2 (neighboursCount x y)))
  48. (= 3 (neighboursCount x y)))
  49. 1 0))
  50. )
  51. (defn buildBoard
  52. []
  53. (for [i (range (count brd))]
  54. (buildLine i)
  55. )
  56. )
  57. (buildBoard)
  58. )
  59. (defn formatBoard
  60. [brd]
  61. (defn formatLine
  62. [line]
  63. (defn formatChar
  64. [ch]
  65. (if (= 0 ch) "." "#")
  66. )
  67. (str (apply str (map formatChar line)) "\n")
  68. )
  69. (apply str (map formatLine brd))
  70. )
  71. (defn playGol
  72. [occurences, brd]
  73. (def newBrd (cgol brd))
  74. (println (formatBoard newBrd))
  75. (if
  76. (<= occurences 1)
  77. "Done!"
  78. (playGol (- occurences 1) newBrd)
  79. )
  80. )
  81. ;; This function parses an integer in a string using the JDK bultin operations
  82. (defn parse-integer
  83. [str]
  84. (Integer/parseInt str)
  85. )
  86. (println (playGol (parse-integer (nth *command-line-args* 1)) (readBoard (nth *command-line-args* 0))))