-
-
Save tbuehlmann/5387960 to your computer and use it in GitHub Desktop.
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
Write a program that reads a text file that contains groups of integers | |
that start with the word "next". For each group, the program computes and writes out | |
the sum of integers in that group. There may be any number of groups. Example data set: | |
5 89 | |
next | |
1 1 1 1 1 1 | |
next | |
next | |
1 1 1 1 1 1 1 1 1 | |
next | |
10 11 | |
12 13 | |
7 8 | |
9 | |
next next | |
next | |
For this data the program writes: | |
Sum of group 1 is 6. | |
Group 2 contains no data. | |
Sum of group 3 is 9. | |
Sum of group 4 is 70. | |
Group 5 contains no data. | |
Group 6 contains no data. | |
Group 7 contains no data. | |
The logic of this program is quite tricky. |
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
filepath = File.join(__dir__, 'data.txt') | |
contents = File.read(filepath) | |
contents = contents[/next\s*\d.+/mi].sub('next', '') | |
contents.gsub!(/\n/, ' ') | |
contents = contents.split('next').map(&:split) | |
contents.map! do |array| | |
array.map!(&:to_i) | |
array.inject { |sum, n| sum + n } | |
end | |
contents.each_with_index do |sum, i| | |
if sum | |
puts "Sum of group #{i+1} is #{sum}." | |
else | |
puts "Group #{i+1} contains no data." | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment