diff --git a/lib/challenge.rb b/lib/challenge.rb index f7130bc..d708d32 100644 --- a/lib/challenge.rb +++ b/lib/challenge.rb @@ -1,19 +1,34 @@ require "time" class Challenge - attr_reader :earliest_time - attr_reader :latest_time - attr_reader :peak_year + attr_reader :earliest_time, :latest_time, :peak_year + # Initializer def initialize(file_path) @file_path = File.expand_path(file_path) end + # Parse method which sets the class properties def parse - # Parse the file located at @file_path and set three attributes: - # - # earliest_time: the earliest time contained within the data set - # latest_time: the latest time contained within the data set - # peak_year: the year with the most number of timestamps contained within the data set + all_rows = {} + peak = {} + # Parsing the file and iterating over the rows + File.open(@file_path, 'r').each_line do |row| + row_time = Time.parse(row) + all_rows[row_time.to_i] = row_time + # Check if year exists in the hash + if(peak.has_key?(row_time.year)) + peak[row_time.year] += 1 # if exist Increase the count + else + peak[row_time.year] = 1 # if not assign the one + end + end + + # Minimum timestamp in the all_rows will be earliest time + @earliest_time = all_rows[all_rows.keys.min] + # Maximum timestamp in the all_rows will be latest time + @latest_time = all_rows[all_rows.keys.max] + # Peak Year with maximum row counts + @peak_year = peak.key(peak.values.max) end end