 # alexdeas's solution

## to Grains in the Kotlin Track

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

## 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.

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 Kotlin to install the necessary dependencies:

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

## Making the test suite pass

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.

## 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.

### BoardTest.kt

``````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" }

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 ) {
}

// 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
}

// 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)
}``````