Jake Worth

Jake Worth

Vim Buffer Problem

Published: March 06, 2016 • Updated: July 26, 2023 2 min read

  • vim

A 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?


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

# vim_buffer(10000)
# => 37359001

And the test showing how it works:

class TestVimBuffer < Minitest::Test
  def test_ten
    assert_equal(46, vim_buffer(10))

  def test_eleven
    assert_equal(57, vim_buffer(11))

  def test_ten_twelve
    assert_equal(69, vim_buffer(12))

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.

What are your thoughts on this solution? Let me know!

Join 100+ engineers who subscribe for advice, commentary, and technical deep-dives into the world of software.