From 9869e5ee5a67b867fd43d67f1c20ffa8f98737a9 Mon Sep 17 00:00:00 2001 From: Hitendra Singh Date: Fri, 15 Jul 2022 22:10:33 +0530 Subject: [PATCH 1/2] Setting the properties for the Challenge class --- lib/challenge.rb | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/lib/challenge.rb b/lib/challenge.rb index f7130bc..9539529 100644 --- a/lib/challenge.rb +++ b/lib/challenge.rb @@ -1,19 +1,27 @@ require "time" class Challenge - attr_reader :earliest_time - attr_reader :latest_time - attr_reader :peak_year + attr_reader :earliest_time, :latest_time, :peak_year def initialize(file_path) @file_path = File.expand_path(file_path) end 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 = {} + File.open(@file_path, 'r').each_line do |row| + row_time = Time.parse(row) + all_rows[row_time.to_i] = row_time + if(peak.has_key?(row_time.year)) + peak[row_time.year] += 1 + else + peak[row_time.year] = 1 + end + end + + @earliest_time = all_rows[all_rows.keys.min] + @latest_time = all_rows[all_rows.keys.max] + @peak_year = peak.key(peak.values.max) end end From 33cd11fb189f862e4747d7f98783aad5d75022f1 Mon Sep 17 00:00:00 2001 From: Hitendra Singh Date: Fri, 15 Jul 2022 22:22:36 +0530 Subject: [PATCH 2/2] Documenting the code --- lib/challenge.rb | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/lib/challenge.rb b/lib/challenge.rb index 9539529..d708d32 100644 --- a/lib/challenge.rb +++ b/lib/challenge.rb @@ -3,25 +3,32 @@ class Challenge 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 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 + peak[row_time.year] += 1 # if exist Increase the count else - peak[row_time.year] = 1 + 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