Avatar of brunnock

brunnock's solution

to Grains in the JavaScript Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

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. Two grains on the next. Four on the third, and so on.

There are 64 squares on a chessboard.

Write code that shows:

  • how many grains were on each square, and
  • the total number of grains

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:

http://exercism.io/languages/javascript/installation

Running the test suite

The provided test suite uses Jasmine. You can install it by opening a terminal window and running the following command:

npm install -g jasmine

Run the test suite from the exercise directory with:

jasmine grains.spec.js

In many test suites all but the first test have been marked "pending". Once you get a test passing, activate the next one by changing xit to it.

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

var BigInt = require('./big-integer');


describe('The big-integer module\'s returned object', function () {
  var bigI;

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

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

  it('is not a number', function () {
    expect(typeof 42).toBe('number');
    expect(typeof bigI).not.toBe('number');
    expect(typeof bigI).toBe('object');
  });

  it('can be compared to a stringified number by calling \'.toString()\'',
    function () {
      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."
    });

  it('is immutable', function () {
    bigI.add(10);
    expect(bigI.toString()).toBe('42');
    bigI.subtract(10);
    expect(bigI.toString()).toBe('42');
  });

  it('can add', function () {
    bigI = bigI.add(42);

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

  it('can perform power operations', function () {
    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! ( :
 */

var Grains = require('./grains');

describe('Grains', function () {
  var grains = new Grains();

  it('square 1', function () {
    expect(grains.square(1)).toBe('1');
  });

  xit('square 2', function () {
    expect(grains.square(2)).toBe('2');
  });

  xit('square 3', function () {
    expect(grains.square(3)).toBe('4');
  });

  xit('square 4', function () {
    expect(grains.square(4)).toBe('8');
  });

  xit('square 16', function () {
    expect(grains.square(16)).toBe('32768');
  });

  xit('square 32', function () {
    expect(grains.square(32)).toBe('2147483648');
  });

  xit('square 64', function () {
    expect(grains.square(64)).toBe('9223372036854775808');
  });

  xit('total', function () {
    expect(grains.total()).toBe('18446744073709551615');
  });
});
var Grains = function() {

  this.square = function(exp) {
    return Math.pow(2,exp-1);
  }

  this.total = function() {
    var total=0;
    for (var x=1; x<65; ++x) {
      total += this.square(x);
    }
    return total;
  }

}

module.exports=Grains;

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?