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:
Did you get the tests passing and the code clean? If you want to, these are some additional things you could try:
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 Ruby resources 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:
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.2.0 2ec42ab 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) do Grains.square(0) end end def test_negative_square_raises_an_exception skip assert_raises(ArgumentError) do Grains.square(-1) end end def test_square_greater_than_64_raises_an_exception skip assert_raises(ArgumentError) do Grains.square(65) end 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 end
module Grains def self.square(n) # first we check for a valid square number raise ArgumentError unless n > 0 && n < 65 # following the formula # square n has 2 to the power n-1 grains 2**(n-1) end def self.total # 2**0 + 2**1 + .. + 2**n = 2**(n+1) - 1 2**64 - 1 end end
Two tea to two two two