ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

Published at Jul 13 2018
·
3 comments

Instructions

Test suite

Solution

Calculate the number of grains of wheat on a chessboard given that the number on each square doubles.

There once was a wise servant who saved the life of a prince. The king promised to pay whatever the servant could dream up. Knowing that the king loved chess, the servant told the king he would like to have grains of wheat. One grain on the first square of a chess board. Two grains on the next. Four on the third, and so on.

There are 64 squares on a chessboard.

Write code that shows:

- how many grains were on each square, and
- the total number of grains

Did you get the tests passing and the code clean? If you want to, these are some additional things you could try:

- Optimize for speed.
- Optimize for readability.

Then please share your thoughts in a comment on the submission. Did this experiment make the code better? Worse? Did you learn anything from it?

For installation and learning resources, refer to the exercism help page.

For running the tests provided, you will need the Minitest gem. Open a terminal window and run the following command to install minitest:

```
gem install minitest
```

If you would like color output, you can `require 'minitest/pride'`

in
the test file, or note the alternative instruction, below, for running
the test file.

Run the tests from the exercise directory using the following command:

```
ruby grains_test.rb
```

To include color from the command line:

```
ruby -r minitest/pride grains_test.rb
```

JavaRanch Cattle Drive, exercise 6 http://www.javaranch.com/grains.jsp

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

```
require 'minitest/autorun'
require_relative 'grains'
# Common test data version: 1.0.0 2e0e77e
class GrainsTest < Minitest::Test
def test_1
# skip
assert_equal 1, Grains.square(1)
end
def test_2
skip
assert_equal 2, Grains.square(2)
end
def test_3
skip
assert_equal 4, Grains.square(3)
end
def test_4
skip
assert_equal 8, Grains.square(4)
end
def test_16
skip
assert_equal 32_768, Grains.square(16)
end
def test_32
skip
assert_equal 2_147_483_648, Grains.square(32)
end
def test_64
skip
assert_equal 9_223_372_036_854_775_808, Grains.square(64)
end
def test_square_0_raises_an_exception
skip
assert_raises(ArgumentError) { Grains.square(0) }
end
def test_negative_square_raises_an_exception
skip
assert_raises(ArgumentError) { Grains.square(-1) }
end
def test_square_greater_than_64_raises_an_exception
skip
assert_raises(ArgumentError) { Grains.square(65) }
end
def test_returns_the_total_number_of_grains_on_the_board
skip
assert_equal 18_446_744_073_709_551_615, Grains.total
end
# Problems in exercism evolve over time, as we find better ways to ask
# questions.
# The version number refers to the version of the problem you solved,
# not your solution.
#
# Define a constant named VERSION inside of the top level BookKeeping
# module, which may be placed near the end of your file.
#
# In your file, it will look like this:
#
# module BookKeeping
# VERSION = 1 # Where the version number matches the one in the test.
# end
#
# If you are curious, read more about constants on RubyDoc:
# http://ruby-doc.org/docs/ruby-doc-bundle/UsersGuide/rg/constants.html
def test_bookkeeping
skip
assert_equal 1, BookKeeping::VERSION
end
end
```

```
### geometric_series.rb #######################################################
class GeometricSeries
attr_reader :first_term, :common_ratio
def initialize(options)
@first_term = options.fetch(:first_term, 1)
@common_ratio = options.fetch(:common_ratio, 2)
end
def nth(n)
fail ArgumentError, "ArgumentError: invalid n (#{n} for (0..+))." if n < 0
first_term * common_ratio**n
end
def sum_upto(n)
fail ArgumentError, "ArgumentError: invalid n (#{n} for (0..+))." if n < 0
first_term * ((1 - common_ratio**n) / (1 - common_ratio))
end
end
### grains.rb #################################################################
class Grains
CHESSBOARD = (1..64) # squares
def initialize
@series = GeometricSeries.new(first_term: 1, common_ratio: 2)
end
def square(n)
unless CHESSBOARD.include? n
fail ArgumentError,
"ArgumentError: n must lie on the board (#{n} for #{CHESSBOARD})."
end
@series.nth(n - 1) # Minus 1 for zero-indexing.
end
def total
@series.sum_upto(CHESSBOARD.last)
end
end
```

A huge amount can be learned from reading other peopleâ€™s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

- What compromises have been made?
- Are there new concepts here that you could read more about to improve your understanding?

Level up your programming skills with 3,394 exercises across 50 languages, and insightful discussion with our volunteer team of welcoming mentors.
Exercism is
**100% free forever**.

## Community comments

I wanted to try something different for a change.

I love it. Methods are short and very readable, it's obvious that the Grains problem is an instance of a geometric series and the GeometricSeries class is reusable. It's also very logical to check if the square we are being asked about is even on the chessboard, I'm kinda jealous that I didn't think of it myself ;).

@angelikatyborska Thanks. The error handling on lines 31-34 is still a bit ugly. I guess I could extract it to a helper method.