Created
March 30, 2011 17:25
-
-
Save basicxman/894833 to your computer and use it in GitHub Desktop.
All we do is win win win
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env ruby | |
| # Problem 4 | |
| # ECOO 2011 Perimeter Trees | |
| # Andrew Horsman | |
| class Point < Struct.new(:x, :y); end | |
| class Line | |
| def initialize(x1, y1, x2, y2) | |
| @x1, @y1, @x2, @y2 = x1.to_f, y1, x2, y2 | |
| calculate_slope | |
| end | |
| def calculate_slope | |
| @m = (@y2 - @y1) / (@x2 - @x1) | |
| end | |
| def calculate_y(x) | |
| @m * x - @x1 * @m + @y1 | |
| end | |
| def check_above(x, y) | |
| y > calculate_y(x) | |
| end | |
| def check_below(x, y) | |
| y < calculate_y(x) | |
| end | |
| end | |
| class Run | |
| def initialize(data) | |
| lines = data.split("\n") | |
| groves = [] | |
| until lines.length == 0 | |
| num_lines = lines.slice!(0).to_i | |
| data_set = [] | |
| num_lines.times { data_set << lines.slice!(0).strip } | |
| groves << data_set | |
| end | |
| groves.each { |grove| run grove } | |
| end | |
| def run(data_set) | |
| trees = data_set.map { |xy| Point.new(*xy.split(" ").map { |arg| arg.to_i }) } | |
| number_of_perimeter_trees = 0 | |
| trees.each_with_index do |tree_for_checking, index_one| | |
| is_perimeter_tree = false | |
| other_trees = trees.dup | |
| other_trees.slice! index_one | |
| other_trees.each_with_index do |tree_for_line, index_two| | |
| number_of_above_trees = 0 | |
| number_of_below_trees = 0 | |
| line = Line.new(tree_for_checking.x, tree_for_checking.y, tree_for_line.x, tree_for_line.y) | |
| non_line_trees = other_trees.dup | |
| non_line_trees.slice! index_two | |
| non_line_trees.each do |check_tree| | |
| if line.check_above(check_tree.x, check_tree.y) | |
| number_of_above_trees += 1 | |
| elsif line.check_below(check_tree.x, check_tree.y) | |
| number_of_below_trees += 1 | |
| end | |
| break if number_of_above_trees > 0 and number_of_below_trees > 0 | |
| end | |
| is_perimeter_tree = !(number_of_above_trees > 0 and number_of_below_trees > 0) | |
| break if is_perimeter_tree | |
| end | |
| number_of_perimeter_trees += 1 if is_perimeter_tree | |
| end | |
| puts "There are #{number_of_perimeter_trees} perimeter trees in a grove of #{trees.length} trees." | |
| end | |
| end | |
| %w( | |
| data41.txt | |
| test.txt | |
| ).each do |file_name| | |
| puts "Running #{file_name}" | |
| run = Run.new(File.read(file_name)) | |
| end |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Proving to @ProgrammerMike that my method would've worked.