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, with the number of grains doubling on each successive square.
There are 64 squares on a chessboard (where square 1 has one grain, square 2 has two grains, and so on).
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?
Refer to the Installing Elm page for information about installing elm.
The first time you start an exercise, you'll need to ensure you have the appropriate dependencies installed. Thankfully, Elm makes that easy for you and will install dependencies when you try to run tests or build the code.
Execute the tests with:
Automatically run tests again when you save changes:
$ elm-test --watch
As you work your way through the test suite, be sure to remove the
calls from each test until you get them all passing!
JavaRanch Cattle Drive, exercise 6 http://www.javaranch.com/grains.jsp
It is possible to submit an incomplete solution so you can see how others have completed the exercise.
module Grains exposing (square) square : Int -> Maybe Int square n = if validChessboardSquare n then Just (calculateSquare n) else Nothing -- PRIVATE validChessboardSquare : Int -> Bool validChessboardSquare n = let chessboard = List.range 1 64 in chessboard |> List.member n calculateSquare : Int -> Int calculateSquare n = let base = 2 offset = 1 in base ^ (n - offset)
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.