Exercism v3 launches on Sept 1st 2021. Learn more! ๐Ÿš€๐Ÿš€๐Ÿš€
Avatar of rootulp

rootulp's solution

to Grains in the Java Track

Published at May 18 2020 · 0 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, 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:

  • how many grains were on a given square, and
  • the total number of grains on the chessboard

For bonus points

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?

Setup

Go through the setup instructions for Java to install the necessary dependencies:

https://exercism.io/tracks/java/installation

Running the tests

You can run all the tests for an exercise by entering the following in your terminal:

$ gradle test

In the test suites all tests but the first have been skipped.

Once you get a test passing, you can enable the next one by removing the @Ignore("Remove to run test") annotation.

Source

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

Submitting Incomplete Solutions

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

GrainsTest.java

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;

import org.junit.Ignore;
import org.junit.Test;

import java.math.BigInteger;

public class GrainsTest {

    private Grains grains = new Grains();
    
    @Test
    public void countAtSquare1() {
        BigInteger result = grains.grainsOnSquare(1);
        assertEquals(new BigInteger("1"), result);
    }

    @Ignore("Remove to run test")
    @Test
    public void countAtSquare2() {
        BigInteger result = grains.grainsOnSquare(2);
        assertEquals(new BigInteger("2"), result);
    }

    @Ignore("Remove to run test")
    @Test
    public void countAtSquare3() {
        BigInteger result = grains.grainsOnSquare(3);
        assertEquals(new BigInteger("4"), result);
    }

    @Ignore("Remove to run test")
    @Test
    public void countAtSquare4() {
        BigInteger result = grains.grainsOnSquare(4);
        assertEquals(new BigInteger("8"), result);
    }

    @Ignore("Remove to run test")
    @Test
    public void countAtSquare16() {
        BigInteger result = grains.grainsOnSquare(16);
        assertEquals(new BigInteger("32768"), result);
    }

    @Ignore("Remove to run test")
    @Test
    public void countAtSquare32() {
        BigInteger result = grains.grainsOnSquare(32);
        assertEquals(new BigInteger("2147483648"), result);
    }

    @Ignore("Remove to run test")
    @Test
    public void countAtSquare64() {
        BigInteger result = grains.grainsOnSquare(64);
        assertEquals(new BigInteger("9223372036854775808"), result);
    }

    @Ignore("Remove to run test")
    @Test
    public void errorOnNullBoardSize() {
        IllegalArgumentException expected =
            assertThrows(
                IllegalArgumentException.class,
                () -> grains.grainsOnSquare(0));

        assertThat(expected)
            .hasMessage("square must be between 1 and 64");
    }

    @Ignore("Remove to run test")
    @Test
    public void errorOnNegativeBoardSize() {
        IllegalArgumentException expected =
            assertThrows(
                IllegalArgumentException.class,
                () -> grains.grainsOnSquare(-1));

        assertThat(expected)
            .hasMessage("square must be between 1 and 64");
    }

    @Ignore("Remove to run test")
    @Test
    public void errorOnExcessiveBoardSize() {
        IllegalArgumentException expected =
            assertThrows(
                IllegalArgumentException.class,
                () -> grains.grainsOnSquare(65));

        assertThat(expected)
            .hasMessage("square must be between 1 and 64");
    }

    @Ignore("Remove to run test")
    @Test
    public void totalNumberOfGrainsOnABoard() {
        BigInteger total = grains.grainsOnBoard();
        assertEquals(new BigInteger("18446744073709551615"), total);
    }

}
import java.math.BigInteger;
import java.util.stream.IntStream;

class Grains {

    private static final int MIN_BOARD_SQUARE = 1;
    private static final int MAX_BOARD_SQUARE = 64;

    BigInteger grainsOnSquare(final int square) {
        if(square < MIN_BOARD_SQUARE || square > MAX_BOARD_SQUARE ){
            throw new IllegalArgumentException(String.format("square must be between %d and %d", MIN_BOARD_SQUARE, MAX_BOARD_SQUARE));
        }
        return new BigInteger("2").pow(square - 1);
    }

    BigInteger grainsOnBoard() {
        return IntStream.rangeClosed(MIN_BOARD_SQUARE, MAX_BOARD_SQUARE).boxed().map(n -> grainsOnSquare(n)).reduce(BigInteger.ZERO, BigInteger::add);
    }

}

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

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?