Avatar of andytson-inviqa

andytson-inviqa's solution

to Two Bucket in the TypeScript Track

Published at Sep 20 2019 · 0 comments
Instructions
Test suite
Solution

Given two buckets of different size, demonstrate how to measure an exact number of liters by strategically transferring liters of fluid between the buckets.

Since this mathematical problem is fairly subject to interpretation / individual approach, the tests have been written specifically to expect one overarching solution.

To help, the tests provide you with which bucket to fill first. That means, when starting with the larger bucket full, you are NOT allowed at any point to have the smaller bucket full and the larger bucket empty (aka, the opposite starting point); that would defeat the purpose of comparing both approaches!

Your program will take as input:

  • the size of bucket one
  • the size of bucket two
  • the desired number of liters to reach
  • which bucket to fill first, either bucket one or bucket two

Your program should determine:

  • the total number of "moves" it should take to reach the desired number of liters, including the first fill
  • which bucket should end up with the desired number of liters (let's say this is bucket A) - either bucket one or bucket two
  • how many liters are left in the other bucket (bucket B)

Note: any time a change is made to either or both buckets counts as one (1) move.

Example: Bucket one can hold up to 7 liters, and bucket two can hold up to 11 liters. Let's say bucket one, at a given step, is holding 7 liters, and bucket two is holding 8 liters (7,8). If you empty bucket one and make no change to bucket two, leaving you with 0 liters and 8 liters respectively (0,8), that counts as one "move". Instead, if you had poured from bucket one into bucket two until bucket two was full, leaving you with 4 liters in bucket one and 11 liters in bucket two (4,11), that would count as only one "move" as well.

To conclude, the only valid moves are:

  • pouring from one bucket to another
  • emptying one bucket and doing nothing to the other
  • filling one bucket and doing nothing to the other

Written with <3 at Fullstack Academy by Lindsay Levine.

Setup

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

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

Requirements

Install assignment dependencies:

$ yarn install

Making the test suite pass

Execute the tests with:

$ yarn 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 xit to it.

Source

Water Pouring Problem http://demonstrations.wolfram.com/WaterPouringProblem/

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

two-bucket.test.ts

import { TwoBucket, Bucket } from "./two-bucket"

describe("TwoBucket", () => {
  describe("works for input of 3, 5, 1", () => {
    const buckOne = 3
    const buckTwo = 5
    const goal = 1

    it("starting with bucket one", () => {
      const starterBuck = Bucket.One // indicates which bucket to fill first
      const twoBucket = new TwoBucket(buckOne, buckTwo, goal, starterBuck)
      expect(twoBucket.moves()).toEqual(4) // includes the first fill
      expect(twoBucket.goalBucket).toEqual("one") // which bucket should end up with the desired # of liters
      expect(twoBucket.otherBucket).toEqual(5) // leftover value in the "other" bucket once the goal has been reached
    })

    xit("starting with bucket two", () => {
      const starterBuck = Bucket.Two
      const twoBucket = new TwoBucket(buckOne, buckTwo, goal, starterBuck)
      expect(twoBucket.moves()).toEqual(8)
      expect(twoBucket.goalBucket).toEqual("two")
      expect(twoBucket.otherBucket).toEqual(3)
    })
  })

  describe("works for input of 7, 11, 2", () => {
    const buckOne = 7
    const buckTwo = 11
    const goal = 2

    xit("starting with bucket one", () => {
      const starterBuck = Bucket.One
      const twoBucket = new TwoBucket(buckOne, buckTwo, goal, starterBuck)
      expect(twoBucket.moves()).toEqual(14)
      expect(twoBucket.goalBucket).toEqual("one")
      expect(twoBucket.otherBucket).toEqual(11)
    })

    xit("starting with bucket two", () => {
      const starterBuck = Bucket.Two
      const twoBucket = new TwoBucket(buckOne, buckTwo, goal, starterBuck)
      expect(twoBucket.moves()).toEqual(18)
      expect(twoBucket.goalBucket).toEqual("two")
      expect(twoBucket.otherBucket).toEqual(7)
    })
  })
})
interface Bucket {
  capacity: number;
  reference: string;
}

interface Path {
  moves: number;
  endState: State;
}

type PathGenerator = Generator<Path, void, undefined>;

type State = number[];

type StateTransition = (state: State) => State;

export class TwoBucket {
  buckets: Bucket[] = [];
  currentMoves = 0;
  goalBucket: string = '';
  otherBucket: number = 0;

  constructor(buckOne: number, buckTwo: number, goal: number, starterBuck: string) {
    this.setupBuckets([buckOne, buckTwo]);

    const initialState = this.buckets.map(() => 0);

    const exploredStates = [
      initialState,
      this.buckets.map(bucket => (bucket.reference == starterBuck ? 0 : bucket.capacity))
    ];

    const initialPath: Path = { moves: 0, endState: initialState };
    const actions = this.getPotentialMoves();
    const paths = this.findPaths([initialPath], exploredStates, actions);

    this.determineOutcome(paths, goal);
  }

  *findPaths(paths: Path[], exploredStates: State[], actions: StateTransition[]): PathGenerator {
    while (paths.length > 0) {
      paths = paths.reduce((paths: Path[], path) => {
        return paths.concat(
          actions
            .map((action): Path => ({ moves: path.moves + 1, endState: action(path.endState) }))
            .filter(
              newPath =>
                !exploredStates.some(
                  exploredState => JSON.stringify(exploredState) == JSON.stringify(newPath.endState)
                )
            )
        );
      }, []);
      yield* paths;
      exploredStates = exploredStates.concat(paths.map(path => path.endState));
    }
  }

  moves(): number {
    return this.currentMoves;
  }

  private setupBuckets(quantities: number[]): void {
    this.addBucket('one', quantities[0]);
    this.addBucket('two', quantities[1]);
  }

  private determineOutcome(paths: PathGenerator, goal: number): void {
    for (const path of paths) {
      if (path.endState.some(level => level == goal)) {
        this.goalBucket = this.buckets[path.endState.indexOf(goal)].reference;
        const otherBucket = path.endState.find((level: number) => level !== goal);
        if (otherBucket) {
          this.otherBucket = otherBucket;
        }
        this.currentMoves = path.moves;
        break;
      }
    }
  }

  private getPotentialMoves(): StateTransition[] {
    return this.buckets.reduce((acc: StateTransition[], bucket, index) => {
      acc.push(state => this.fill(index, state));
      acc.push(state => this.empty(index, state));

      this.buckets.forEach((innerBucket: Bucket, innerIndex: number) => {
        if (bucket == innerBucket) {
          return;
        }
        acc.push(state => this.pour(index, innerIndex, state));
      });
      return acc;
    }, []);
  }

  private addBucket(reference: string, capacity: number): void {
    this.buckets.push({
      capacity,
      reference
    });
  }

  private update(state: State, index: number, quantity: number): State {
    const newState = state.slice(0);
    newState[index] = quantity;
    return newState;
  }

  private fill(index: number, state: State): State {
    return this.update(state, index, this.buckets[index].capacity);
  }

  private pour(from: number, to: number, state: State): State {
    const availableInDestination = this.buckets[to].capacity - state[to];
    const fill = Math.min(availableInDestination, state[from]);

    return this.update(this.update(state, from, state[from] - fill), to, state[to] + fill);
  }

  private empty(index: number, state: State): State {
    return this.update(state, index, 0);
  }
}

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?