Avatar of PatrickMcSweeny

PatrickMcSweeny's solution

to Grains in the JavaScript Track

Published at Aug 21 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.
  • 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 Javascript to install the necessary dependencies:

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

Requirements

Install assignment dependencies:

$ npm install

Making the test suite pass

Execute the tests with:

$ npm 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 changing xtest to test.

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.

big-integer.spec.js

import BigInt from './lib/big-integer';

describe('The big-integer module\'s returned object', () => {
  let bigI;

  beforeEach(() => {
    bigI = BigInt(42);
  });

  afterEach(() => {
    bigI = null;
  });

  test('is not a number', () => {
    expect(typeof 42).toBe('number');
    expect(typeof bigI).not.toBe('number');
    expect(typeof bigI).toBe('object');
  });

  test('can be compared to a stringified number by calling \'.toString()\'', () => {
    expect(bigI).not.toBe(42);
    expect(bigI).not.toBe('42');
    expect(bigI.toString()).toBe('42');
    // NOTE:
    // The '==' operator calls '.toString()' here in order to compare.
    expect(bigI == '42').toBe(true);
    // While the line above is easier to write and read, we will use the
    // 'expect(bigI.toString()).toBe(expected)' way so that test failure
    // messages will be more informative. Eg,
    // "Expected '84' to be '42'." instead of
    // "Expected false to be true."
  });

  test('is immutable', () => {
    bigI.add(10);
    expect(bigI.toString()).toBe('42');
    bigI.subtract(10);
    expect(bigI.toString()).toBe('42');
  });

  test('can add', () => {
    bigI = bigI.add(42);

    expect(bigI.toString()).toBe('84');
  });

  test('can perform power operations', () => {
    bigI = BigInt(10);
    bigI = bigI.pow(2);
    expect(bigI.toString()).toBe('100');
  });

  // ...see the official docs for more info, if you want.
  // The "Methods" section of the README is especially useful:
  //
  // https://github.com/peterolson/BigInteger.js#methods
});

grains.spec.js

/**
 * In JavaScript, integers beyond +/- 9007199254740991 cannot be accurately
 * represented. To see this in action, console.log() out the expected number
 * of grains on square #64:
 *
 * console.log(9223372036854775808);
 * // =>       9223372036854776000
 * //                         ^^^^
 *
 * This is because, in JavaScript, integers are represented as 64-bit floating
 * point numbers. If you want to learn more, see:
 *
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
 * http://stackoverflow.com/questions/307179/what-is-javascripts-highest-integer-value-that-a-number-can-go-to-without-losin
 *
 * So, an accurate solution to this problem requires the use of a
 * "big integer" type. There are multiple ways to use big integer types.
 * We have provided you with BigInteger.js. You can read more about it here:
 *
 * https://github.com/peterolson/BigInteger.js
 * ^--- The "Methods" section of the README will be especially helpful.
 *
 * https://github.com/peterolson/BigInteger.js/blob/master/spec/spec.js
 * ^--- Tests are a good way to understand, in addition to the README.
 *
 * To get you started, this folder has a file of the big-integer module.
 * See its tests in this folder for a quick primer on how to use it! ( :
 */

import { Grains } from './grains';

describe('Grains', () => {
  const grains = new Grains();

  test('square 1', () => {
    expect(grains.square(1)).toBe('1');
  });

  xtest('square 2', () => {
    expect(grains.square(2)).toBe('2');
  });

  xtest('square 3', () => {
    expect(grains.square(3)).toBe('4');
  });

  xtest('square 4', () => {
    expect(grains.square(4)).toBe('8');
  });

  xtest('square 16', () => {
    expect(grains.square(16)).toBe('32768');
  });

  xtest('square 32', () => {
    expect(grains.square(32)).toBe('2147483648');
  });

  xtest('square 64', () => {
    expect(grains.square(64)).toBe('9223372036854775808');
  });

  xtest('total', () => {
    expect(grains.total()).toBe('18446744073709551615');
  });
});
import BigInt from './lib/big-integer';

const NUMBER_OF_SQUARES = 64;

export class Grains {
  square(number) {
    return BigInt(2).pow(number - 1).toString();
  }

  total() {
    let total = BigInt(0);

    for(let i = 1; i <= NUMBER_OF_SQUARES; i++){
      total = total.add(this.square(i));
    }
    return total.toString();
  }
}

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?