Exercism v3 launches on Sept 1st 2021. Learn more! ๐๐๐

Published at Feb 10 2019
·
1 comment

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?

In order to run the tests for this track, you will need to install DUnitX. Please see the installation instructions for more information.

If Delphi is properly installed, and `*.dpr`

file types have been associated with Delphi, then double clicking the supplied `*.dpr`

file will start Delphi and load the exercise/project. `control + F9`

is the keyboard shortcut to compile the project or pressing `F9`

will compile and run the project.

Alternatively you may opt to start Delphi and load your project via. the `File`

drop down menu.

We monitor the Pascal-Delphi support room on gitter.im to help you with any questions that might arise.

Note that, when trying to submit an exercise, make sure the exercise file you're submitting is in the `exercism/delphi/<exerciseName>`

directory.

For example, if you're submitting `ubob.pas`

for the Bob exercise, the submit command would be something like `exercism submit <path_to_exercism_dir>/delphi/bob/ubob.pas`

.

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

It's possible to submit an incomplete solution so you may receive assistance from a mentor.

```
unit uGrainsTests;
interface
uses
DUnitX.TestFramework;
const
CanonicalVersion = '1.1.0';
type
[TestFixture]
TgrainsTests = class(TObject)
public
[Test]
// [Ignore('Comment the "[Ignore]" statement to run the test')]
procedure Test_square_1;
[Test]
[Ignore]
procedure Test_square_2;
[Test]
[Ignore]
procedure Test_square_3;
[Test]
[Ignore]
procedure Test_square_4;
[Test]
[Ignore]
procedure Test_square_16;
[Test]
[Ignore]
procedure Test_square_32;
[Test]
[Ignore]
procedure Test_square_64;
[Test]
[Ignore]
procedure Square_0_raises_an_exception;
[Test]
[Ignore]
procedure Negative_square_raises_an_exception;
[Test]
[Ignore]
procedure Square_greater_than_64_raises_an_exception;
[Test]
[Ignore]
procedure Returns_the_total_number_of_grains_on_the_board;
end;
implementation
uses System.SysUtils, uGrains;
procedure TgrainsTests.Test_square_1;
var expected: UInt64;
begin
expected := 1;
Assert.AreEqual(expected, Grains.Square(1));
end;
procedure TgrainsTests.Test_square_2;
var expected: UInt64;
begin
expected := 2;
Assert.AreEqual(expected, Grains.Square(2));
end;
procedure TgrainsTests.Test_square_3;
var expected: UInt64;
begin
expected := 4;
Assert.AreEqual(expected, Grains.Square(3));
end;
procedure TgrainsTests.Test_square_4;
var expected: UInt64;
begin
expected := 8;
Assert.AreEqual(expected, Grains.Square(4));
end;
procedure TgrainsTests.Test_square_16;
var expected: UInt64;
begin
expected := 32768;
Assert.AreEqual(expected, Grains.Square(16));
end;
procedure TgrainsTests.Test_square_32;
var expected: UInt64;
begin
expected := 2147483648;
Assert.AreEqual(expected, Grains.Square(32));
end;
procedure TgrainsTests.Test_square_64;
var expected: UInt64;
begin
expected := 9223372036854775808;
Assert.AreEqual(expected, Grains.Square(64));
end;
procedure TgrainsTests.Square_0_raises_an_exception;
var MyProc: TTestLocalMethod;
begin
MyProc := procedure
begin
Grains.Square(0);
end;
Assert.WillRaise(MyProc, ERangeError);
end;
procedure TgrainsTests.Negative_square_raises_an_exception;
var MyProc: TTestLocalMethod;
begin
MyProc := procedure
begin
Grains.Square(-1);
end;
Assert.WillRaise(MyProc, ERangeError);
end;
procedure TgrainsTests.Square_greater_than_64_raises_an_exception;
var MyProc: TTestLocalMethod;
begin
MyProc := procedure
begin
Grains.Square(65);
end;
Assert.WillRaise(MyProc, ERangeError);
end;
procedure TgrainsTests.Returns_the_total_number_of_grains_on_the_board;
var expected: UInt64;
begin
expected := 18446744073709551615;
Assert.AreEqual(expected, Grains.Total);
end;
initialization
TDUnitX.RegisterTestFixture(TgrainsTests);
end.
```

```
unit uGrains;
interface
type
TGrains = class
private
const TotalSquares = 64;
public
// Calculates the number of grains on each square from 1 through
// SquareNumber while summing grains on all calculated squares.
// If ReturnTotal, then the total number of grains on all squares through
// SquareNumber is returned, otherwise the grain count on SquareNumber is
// returned.
function Square(SquareNumber: Int64; ReturnTotal: Boolean = False): UInt64;
// Returns the total number of grains on all squares.
function Total: UInt64;
end;
var
Grains: TGrains;
implementation
uses
SysUtils, Math;
{ TGrains }
function TGrains.Square(SquareNumber: Int64; ReturnTotal: Boolean = False): UInt64;
var
SquareIndex, SquareGrainCount, TotalGrainCount: UInt64;
begin
// Validate input
if not (SquareNumber in [1..TotalSquares]) then
raise ERangeError.Create('Invalid Square Number : ' + IntToStr(SquareNumber));
// Initialize variables
SquareGrainCount := 1;
TotalGrainCount := 0;
// Loop through squares
for SquareIndex := 1 to SquareNumber do begin
SquareGrainCount := SquareGrainCount * Min(2, SquareIndex);
TotalGrainCount := TotalGrainCount + SquareGrainCount;
end;
// Set Result to requested value
if ReturnTotal then
Result := TotalGrainCount
else
Result := SquareGrainCount;
end;
function TGrains.Total: UInt64;
begin
Result := Square(TotalSquares, True);
end;
end.
```

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?

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

## Community comments

The part I consider 'clever' (read confusing) is the usage of

`Min(2, SquareIndex)`

instead of a conditional statement.I think this looks neater that an

`if then`

block, and is easier to mentally abstract away during a quick read-through if that isn't what you want to focus on. I realize this may affect comprehensibility, and introduces a library dependency.A class constant was used to hold the 'magic number' 64 which contributes to maintainability.

I am unsure whether having

`Square`

produce different output based on a Boolean parameter was a good idea, but it was more DRY than other ideas I had.