Published at Oct 07 2019
·
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

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?

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

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

Execute the tests with:

```
$ gradlew test
```

Use

`gradlew.bat`

if you're on Windows

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`

annotation.

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.

```
import org.junit.Ignore
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExpectedException
import java.math.BigInteger
import kotlin.test.assertEquals
class BoardTest {
@Rule
@JvmField
var expectedException: ExpectedException = ExpectedException.none()
@Test
fun testSquare1ContainsCorrectNumberOfGrains() {
assertEquals(BigInteger.ONE, Board.getGrainCountForSquare(1))
}
@Ignore
@Test
fun testSquare2ContainsCorrectNumberOfGrains() {
assertEquals(BigInteger.valueOf(2), Board.getGrainCountForSquare(2))
}
@Ignore
@Test
fun testSquare3ContainsCorrectNumberOfGrains() {
assertEquals(BigInteger.valueOf(4), Board.getGrainCountForSquare(3))
}
@Ignore
@Test
fun testSquare4ContainsCorrectNumberOfGrains() {
assertEquals(BigInteger.valueOf(8), Board.getGrainCountForSquare(4))
}
@Ignore
@Test
fun testSquare16ContainsCorrectNumberOfGrains() {
assertEquals(BigInteger.valueOf(32768), Board.getGrainCountForSquare(16))
}
@Ignore
@Test
fun testSquare32ContainsCorrectNumberOfGrains() {
assertEquals(BigInteger.valueOf(2147483648), Board.getGrainCountForSquare(32))
}
@Ignore
@Test
fun testSquare64ContainsCorrectNumberOfGrains() {
assertEquals(BigInteger("9223372036854775808"), Board.getGrainCountForSquare(64))
}
@Ignore
@Test
fun testSquare0IsInvalid() {
expectedException.expect(IllegalArgumentException::class.java)
expectedException.expectMessage("Only integers between 1 and 64 (inclusive) are allowed")
Board.getGrainCountForSquare(0)
}
@Ignore
@Test
fun testNegativeSquareIsInvalid() {
expectedException.expect(IllegalArgumentException::class.java)
expectedException.expectMessage("Only integers between 1 and 64 (inclusive) are allowed")
Board.getGrainCountForSquare(-1)
}
@Ignore
@Test
fun testSquareGreaterThan64IsInvalid() {
expectedException.expect(IllegalArgumentException::class.java)
expectedException.expectMessage("Only integers between 1 and 64 (inclusive) are allowed")
Board.getGrainCountForSquare(65)
}
@Ignore
@Test
fun testBoardContainsCorrectNumberOfGrains() {
assertEquals(BigInteger("18446744073709551615"), Board.getTotalGrainCount())
}
}
```

```
package main.kotlin
import java.math.BigInteger
object Board {
fun getGrainCountForSquare(n : Int) : BigInteger {
require(n in 1..64) { "Only integers between 1 and 64 (inclusive) are allowed" }
// readable: loop through squares, add grains each time
var readable : BigInteger = BigInteger.ONE
// Starting the range at 2 means that the loop is skipped for the first square
for (i in 2 .. n ) {
readable = readable.plus(readable)
}
// Kotliny approach: Create a sequence of BigIntegers for each square up to n,
// then add them together. Sequences give a bit of a speed boost but it's still
// calculating all the squares up to the one we're looking at
val sequence= generateSequence (BigInteger.ONE) { acc -> acc.plus(acc) }.take(n).last()
// Fast: We can just calculate the number of grains on a square as 2^(n - 1)
val formula = BigInteger.valueOf(2).pow(n-1)
// Fastest: Precalculate all the values
// The full map would be 64 lines, but for brevity let's just have the ones
// in the test
val precalculated = when (n) {
1 -> BigInteger.ONE
2 -> BigInteger("2")
3 -> BigInteger("4")
4 -> BigInteger("8")
// ...
16 -> BigInteger("32768")
// ...
32 -> BigInteger("2147483648")
// ...
64 -> BigInteger("9223372036854775808")
else -> BigInteger.ZERO
}
// values: readable, sequence, formula, precalculated
return precalculated
}
private fun getTotalGrainCountAt(n: Int) : BigInteger {
// Readable: Calculate the grains on each square and add them up
// Combined with the most readable way to calculate squares, this
// is O(n^2) which is awful
var readable : BigInteger = BigInteger.ZERO
for (i in 1 .. n ) {
// This relies on the method above not being on precalculated,
// since the mapping isn't full yet
readable = readable.plus(getGrainCountForSquare(i))
}
// Kotliny Approach: Calculate the squares in a sequence, then add up the result
// Still pretty slow though
val sequence = generateSequence (BigInteger.ONE) { acc -> acc.plus(acc) }.take(n).fold(BigInteger.ZERO){ acc, current -> acc.plus(current)}
// Fast: Use a formula (2^n) - 1
val formula = BigInteger.valueOf(2).pow(n).subtract(BigInteger.ONE)
// Fastest: Precalculate the totals. As with the number of grains on a square
// the total number at any position is fixed, so just return that
val precalculated = when (n) {
1 -> BigInteger.ONE
2 -> BigInteger("3")
3 -> BigInteger("7")
4 -> BigInteger("15")
// ...
16 -> BigInteger("65535")
// ...
32 -> BigInteger("4294967295")
// ...
64 -> BigInteger("18446744073709551615")
else -> BigInteger.ZERO
}
// values: readable, sequence, formula, precalculated
return precalculated
}
fun getTotalGrainCount() = getTotalGrainCountAt(64)
}
```

I explored four solutions to this problem:

1. Readable approach using a for loop. This calculates the number of grains on each square up to the square of interest, then sums them as necessary. The for loop should be familiar to most programmers, although can be up to O(n^2) if used to calculate the total grains on the board.

2. Kotlin approach using a sequence and functions. This methods generates a sequence of the number of grains on each square, and sums them where necessary. This method takes advantage of chaining functions, so it seemed like the most Kotlin approach although isn't much faster than the readable one. For calculating the full board it's at least capped at O(n) if I remember my Big-O calculations.

3. Fomula approach: The number of grains on a square can be calculated with a formula, so there is no need to calculate the grains on each square. This reduces calculation to O(1).

4. Precalculated formula approach: Following the formula approach, values can be precalculated since there are only 64 of them. This saves a little on BigInteger arithmetic, although is probably only worth the effort if a significant number of grain checks need to be peformed.

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

## Community comments