summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authora14m <[email protected]>2020-12-10 21:14:19 +0100
committera14m <[email protected]>2020-12-10 21:14:19 +0100
commit780f85fc9d729735b192db866ad9a19484dc5743 (patch)
tree6ae4da30a67c03517787e28e2ac8e7029bbbb38e
parentb4e9a712549dba1326aa680157574e946e1faa85 (diff)
Add the stable seed generator implementation
-rw-r--r--CLI/ruby/lib/game_of_life/generators/seed.rb37
1 files changed, 36 insertions, 1 deletions
diff --git a/CLI/ruby/lib/game_of_life/generators/seed.rb b/CLI/ruby/lib/game_of_life/generators/seed.rb
index e64a28f..917c9af 100644
--- a/CLI/ruby/lib/game_of_life/generators/seed.rb
+++ b/CLI/ruby/lib/game_of_life/generators/seed.rb
@@ -12,7 +12,42 @@ module GameOfLife
# @option options [Numeric] "height" (floored) and used as the height of the universe
# @return [GameOfLife::Universe] populated with the parsed input
def new(options)
- fail ::NotImplementedError, "Seed option isn't implemented yet, please use --input option"
+ width = options["width"].to_i
+ height = options["height"].to_i
+ seed = options["seed"].to_i
+ input = generate_seed_data(seed: seed, width: width, height: height)
+ populate(input: input, width: width, height: height)
+ end
+
+ # Generate the seeding data for populating the {GameOfLife::Universe}
+ # @param seed [Integer] used to generate {Array<"0"|"1">} using Std ruby {Random}
+ # @param width [Integer] width of the generated cyclic universe
+ # @param height [Integer] height of the generated cyclic universe
+ # @return [Array<Array<True|False>>] covering the defined size of universe
+ # @see ::GameOfLife::Generators::Seed.populate
+ private def generate_seed_data(seed:, width:, height:)
+ # Create a pseudo(stable) random generator from the seed
+ # Generate a sequence of bytes to cover the Game of Life Universe plane
+ # each byte can be unpacked into 8 cells of binary data (ex. "01101011")
+ raw = Random.new(seed).bytes(width * height / 2).unpack1("B*").split("").each_slice(width)
+ raw.map { |row| row.map { |char| char.eql?("1") } }
+ end
+
+ # Populate the {GameOfLife::Universe} with reference to the parsed input 2D array (True/False)
+ # @param input [Array<Array<True|False>>]
+ # @param width [Integer] width of the generated cyclic universe
+ # @param height [Integer] height of the generated cyclic universe
+ # @return [GameOfLife::Universe] populated with the parsed input
+ private def populate(input:, width:, height:)
+ # Generate a universe based on the parsed raw file and fill it with the cells
+ universe = GameOfLife::Universe.new(height: height, width: width)
+ (0...height).each do |i|
+ (0...width).each do |j|
+ cell = { x: j, y: i, alive: input.fetch(i, nil)&.fetch(j, nil) }
+ universe[i][j] = ::GameOfLife::Cell.new(cell)
+ end
+ end
+ universe
end
end
end