-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathanswer.rb
70 lines (51 loc) · 1.27 KB
/
answer.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
require 'pry'
lines = File.read("numbers.csv").lines
# 1. sum of first line - 569
def sum_one_line l
numbers_as_strings = l.chomp.split ","
running_total = 0
numbers_as_strings.each do |n|
running_total += n.to_f
end
return running_total
end
s = sum_one_line lines.first
puts "Sum of the first line is: #{s}"
# 2. sum of all the lines - 10170
running_total = 0
lines.each do |line|
s = sum_one_line line
running_total += s
end
# lines.map { |l| l.split(",").map { |n| n.to_i } }.flatten.reduce(:+)
puts "Sum of file: #{running_total}"
# 3. how many numbers in this file
all_tokens = lines.map { |l| l.split(",") }.flatten
all_numbers = all_tokens.map { |t| t.to_i }
number_of_numbers = 0
lines.each do |i|
number_of_numbers += i.split(",").count
end
# Other functional options
n2 = lines.map { |l| l.split(",") }.flatten.count
n3 = lines.map { |l| l.split(",").count }.reduce :+
n4 = all_numbers.count
# 4. how many are even? divisible by 7?
evens = []
all_numbers.each do |n|
if n.even?
evens.push n
end
end
# evens.count => 102 even numbers
sevens = []
all_numbers.each do |n|
if n % 7 == 0
sevens.push n
end
end
# sevens.count => 28
# Functionally -
all_numbers.select { |n| n.even? }.count
all_numbers.select { |n| n % 7 == 0 }.count
binding.pry