Vim Buffer Problem
- 2 minutes read - 214 wordsA few weeks back I tackled the following programming challenge from my colleague Josh Branchaud:
Vim Buffer
I open up a new Vim buffer and type all the numbers 1 to 10,000, separated by spaces. Then, my cat walks on the keyboard and somehow activates a substitution command that replaces all the ‘0’ digits (zeros) with spaces. If I now sum up all the numbers in the buffer, as delineated by spaces, what is the total?
Solution
Here’s my solution, also available as a Gist.
def vim_buffer(start = 1, limit)
(start..limit).flat_map do |num|
num.to_s.gsub('0', ' ').split
end.map(&:to_i).reduce(:+)
end
# vim_buffer(10000)
# => 37359001
And the test showing how it works:
class TestVimBuffer < Minitest::Test
def test_ten
assert_equal(46, vim_buffer(10))
end
def test_eleven
assert_equal(57, vim_buffer(11))
end
def test_ten_twelve
assert_equal(69, vim_buffer(12))
end
end
What I Like
I like that this solution is tested! I like that it allows me to override the range minimum if I want, although I don’t remember why that was a feature.
What I Don’t Like
I don’t like that it uses to_s
; type coercion feels like cheating. And I
don’t like that it’s brute force. That’s fine for this problem, running ~0.042
seconds on my new (2022) computer, but it’s inelegant.
Thanks again Josh for posting these challenges to the Hashrocket team.