Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Two Bucket Exercise #636

Merged
merged 6 commits into from
Feb 25, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -1203,6 +1203,14 @@
"practices": [],
"prerequisites": [],
"difficulty": 3
},
{
"slug": "two-bucket",
"name": "Two Bucket",
"uuid": "516250c6-6e1b-4710-b2b9-6bef1716c6d8",
"practices": [],
"prerequisites": [],
"difficulty": 5
}
]
},
Expand Down
46 changes: 46 additions & 0 deletions exercises/practice/two-bucket/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Instructions

Given two buckets of different size and which bucket to fill first, determine how many actions are required to measure an exact number of liters by strategically transferring fluid between the buckets.

There are some rules that your solution must follow:

- You can only do one action at a time.
- There are only 3 possible actions:
1. Pouring one bucket into the other bucket until either:
a) the first bucket is empty
b) the second bucket is full
2. Emptying a bucket and doing nothing to the other.
3. Filling a bucket and doing nothing to the other.
- After an action, you may not arrive at a state where the starting bucket is empty and the other bucket is full.

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 actions it should take to reach the desired number of liters, including the first fill of the starting bucket
- which bucket should end up with the desired number of liters - either bucket one or bucket two
- how many liters are left in the other bucket

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

Example:
Bucket one can hold up to 7 liters, and bucket two can hold up to 11 liters.
Let's say at a given step, bucket one 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 action.
Instead, if you had poured from bucket one into bucket two until bucket two was full, resulting in 4 liters in bucket one and 11 liters in bucket two (4,11), that would also only count as one action.

Another Example:
Bucket one can hold 3 liters, and bucket two can hold up to 5 liters.
You are told you must start with bucket one.
So your first action is to fill bucket one.
You choose to empty bucket one for your second action.
For your third action, you may not fill bucket two, because this violates the third rule -- you may not end up in a state after any action where the starting bucket is empty and the other bucket is full.

Written with <3 at [Fullstack Academy][fullstack] by Lindsay Levine.

[fullstack]: https://www.fullstackacademy.com/
19 changes: 19 additions & 0 deletions exercises/practice/two-bucket/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"authors": [
"tomasnorre"
],
"files": {
"solution": [
"TwoBucket.php"
],
"test": [
"TwoBucketTest.php"
],
"example": [
".meta/example.php"
]
},
"blurb": "Given two buckets of different size, demonstrate how to measure an exact number of liters.",
"source": "Water Pouring Problem",
"source_url": "https://demonstrations.wolfram.com/WaterPouringProblem/"
}
188 changes: 188 additions & 0 deletions exercises/practice/two-bucket/.meta/example.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
<?php

/*
* By adding type hints and enabling strict type checking, code can become
* easier to read, self-documenting and reduce the number of potential bugs.
* By default, type declarations are non-strict, which means they will attempt
* to change the original type to match the type specified by the
* type-declaration.
*
* In other words, if you pass a string to a function requiring a float,
* it will attempt to convert the string value to a float.
*
* To enable strict mode, a single declare directive must be placed at the top
* of the file.
* This means that the strictness of typing is configured on a per-file basis.
* This directive not only affects the type declarations of parameters, but also
* a function's return type.
*
* For more info review the Concept on strict type checking in the PHP track
* <link>.
*
* To disable strict typing, comment out the directive below.
*/

declare(strict_types=1);

class TwoBucket
{
private int $goal;
private array $buckets;

public function __construct(int $sizeBucketOne, int $sizeBucketTwo, int $goal, string $startBucket)
{
$this->goal = $goal;
$this->buckets = [new Bucket('one', $sizeBucketOne), new Bucket('two', $sizeBucketTwo)];

if ($startBucket === 'two') {
$this->buckets = array_reverse($this->buckets);
}

$this->validate();
}

public function solve(): Solution
{
$this->first()->empty();
$this->second()->empty();
$moves = 0;

$this->first()->fill();
$moves++;

if ($this->second()->getSize() === $this->goal) {
$this->second()->fill();
$moves++;
}

while (true) {
if ($this->first()->getAmount() === $this->goal) {
return new Solution(
$moves,
$this->first()->getName(),
$this->second()->getAmount()
);
}

if ($this->second()->getAmount() === $this->goal) {
return new Solution(
$moves,
$this->second()->getName(),
$this->first()->getAmount()
);
}

if ($this->first()->isEmpty()) {
$this->first()->fill();
} elseif ($this->second()->isFull()) {
$this->second()->empty();
} else {
$this->first()->pourInto($this->second());
}

$moves++;
}
}

private function first(): Bucket
{
return $this->buckets[0];
}

private function second(): Bucket
{
return $this->buckets[1];
}

private function validate(): void
{
if ($this->goal > max($this->first()->getSize(), $this->second()->getSize())) {
throw new \RuntimeException('Goal is bigger than the largest bucket.');
}

if ($this->goal % $this->greatestCommonDivisor($this->first()->getSize(), $this->second()->getSize()) !== 0) {
throw new \RuntimeException('Goal must be a multiple of the GCD of the sizes of the two buckets.');
}
}

private function greatestCommonDivisor($a, $b)
{
return $b === 0 ? $a : $this->greatestCommonDivisor($b, $a % $b);
}
}

class Solution
{
public function __construct(
public int $numberOfActions,
public string $nameOfBucketWithDesiredLiters,
public int $litersLeftInOtherBucket,
) {
}
}

class Bucket
{
private string $name;
private int $size;
private int $amount;

public function __construct(string $name, int $size)
{
$this->name = $name;
$this->size = $size;
$this->amount = 0;
}

public function getName(): string
{
return $this->name;
}

public function getSize(): int
{
return $this->size;
}

public function getAmount(): int
{
return $this->amount;
}

public function getAvailable(): int
{
return $this->size - $this->amount;
}

public function isFull(): bool
{
return $this->amount === $this->size;
}

public function isEmpty(): bool
{
return $this->amount === 0;
}

public function fill(): void
{
$this->amount = $this->size;
}

public function empty(): void
{
$this->amount = 0;
}

public function pourInto(Bucket $other): void
{
$quantity = min($this->amount, $other->getAvailable());
$this->amount -= $quantity;
$other->add($quantity);
}

private function add($quantity): void
{
$this->amount += $quantity;
}
}
37 changes: 37 additions & 0 deletions exercises/practice/two-bucket/.meta/tests.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# This is an auto-generated file.
#
# Regenerating this file via `configlet sync` will:
# - Recreate every `description` key/value pair
# - Recreate every `reimplements` key/value pair, where they exist in problem-specifications
# - Remove any `include = true` key/value pair (an omitted `include` key implies inclusion)
# - Preserve any other key/value pair
#
# As user-added comments (using the # character) will be removed when this file
# is regenerated, comments can be added via a `comment` key.

[a6f2b4ba-065f-4dca-b6f0-e3eee51cb661]
description = "Measure using bucket one of size 3 and bucket two of size 5 - start with bucket one"

[6c4ea451-9678-4926-b9b3-68364e066d40]
description = "Measure using bucket one of size 3 and bucket two of size 5 - start with bucket two"

[3389f45e-6a56-46d5-9607-75aa930502ff]
description = "Measure using bucket one of size 7 and bucket two of size 11 - start with bucket one"

[fe0ff9a0-3ea5-4bf7-b17d-6d4243961aa1]
description = "Measure using bucket one of size 7 and bucket two of size 11 - start with bucket two"

[0ee1f57e-da84-44f7-ac91-38b878691602]
description = "Measure one step using bucket one of size 1 and bucket two of size 3 - start with bucket two"

[eb329c63-5540-4735-b30b-97f7f4df0f84]
description = "Measure using bucket one of size 2 and bucket two of size 3 - start with bucket one and end with bucket two"

[449be72d-b10a-4f4b-a959-ca741e333b72]
description = "Not possible to reach the goal"

[aac38b7a-77f4-4d62-9b91-8846d533b054]
description = "With the same buckets but a different goal, then it is possible"

[74633132-0ccf-49de-8450-af4ab2e3b299]
description = "Goal larger than both buckets is impossible"
38 changes: 38 additions & 0 deletions exercises/practice/two-bucket/TwoBucket.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

/*
* By adding type hints and enabling strict type checking, code can become
* easier to read, self-documenting and reduce the number of potential bugs.
* By default, type declarations are non-strict, which means they will attempt
* to change the original type to match the type specified by the
* type-declaration.
*
* In other words, if you pass a string to a function requiring a float,
* it will attempt to convert the string value to a float.
*
* To enable strict mode, a single declare directive must be placed at the top
* of the file.
* This means that the strictness of typing is configured on a per-file basis.
* This directive not only affects the type declarations of parameters, but also
* a function's return type.
*
* For more info review the Concept on strict type checking in the PHP track
* <link>.
*
* To disable strict typing, comment out the directive below.
*/

declare(strict_types=1);

class TwoBucket
mk-mxp marked this conversation as resolved.
Show resolved Hide resolved
{
public function __construct(int $sizeBucketOne, int $sizeBucketTwo, int $goal, string $startBucket)
{
throw new \BadMethodCallException(sprintf('Implement the %s method', __FUNCTION__));
}

public function solve()
{
throw new \BadMethodCallException(sprintf('Implement the %s method', __FUNCTION__));
}
Copy link
Collaborator

@neenjaw neenjaw Feb 24, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This interface is an improvement from the last, but since we don't have a meaning for what the buckets mean before the solve method is called, I think we should take one of these two options:

// Option A

class TwoBucket
{
    // drop the constructor, class properties

    public function solve(int $sizeBucketOne, int $sizeBucketTwo, int $goal, string $startBucket)
    {
        // perform the solution for the parameters provided, return a solution object
    }
}

// or Option B

class TwoBucket
{
    public function __construct(int $sizeBucketOne, int $sizeBucketTwo, int $goal, string $startBucket)
    {
        // initialize and solve the solution, making the buckets available in getters
    }

    // drop the solve method
}

Currently we have an object that requires its public methods to be called in a specific order before it is considered valid -- this is a cumbersome pattern that shifts the burden of implementation to the consumers of this object to understand the inner state of the object to use it correctly rather than the object being the expert on itself.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for pointing that out. It is inherently a procedural problem, "input, process, output". Which means, the only feasable way to implement it is just a single function or method call.

Copy link
Contributor Author

@tomasnorre tomasnorre Feb 24, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I opt for option A. I like that approach more than having the logic in the constructor. For me, the constructor is for setting up the Class/Object, not doing any logic.

I think I'll manage to have it adjusted one of the following days, if neither of you opt against it.

}
Loading