Problem Solving: The Bottle Filling Example
Learn to solve a problem with the help of a real-world example.
Eat an elephant one bite at a time
Even the longest journey requires us to take one step at a time. We write complex code to solve many computational problems. Those problems might look daunting now, but we just need to solve them step by step. To solve a complicated word problem, start by writing steps in simple English.
Measuring problems
We’ll start with a simple problem—measuring water with the help of two odd containers.
We only have two bottles, a and a .
Tasks
We have the following tasks:
- Measure 2 liters of water.
- Measure 1 liter of water.
- Measure 4 liters of water.
Rules
- We have as much water as we need.
- We may fill and pour any bottle into any other bottle or drain a bottle entirely as many times as needed.
Remember: We can’t fill a bottle halfway, and there are no 1 liter, 2 liter, or 4 liter bottles.
Task 1: Measure 2 liters
The first task is to measure 2 liters of water.
Tip: Start by filling the 5 liter bottle.
Task 2: Measure 1 liter
The next task is to measure 1 liter of water.
Tip: Start by filling the 3 liter bottle.
Task 3: Measure 4 liters
The next task is to measure 4 liters of water.
Tip: Start by filling the 3 liter bottle.
Program
A program is a finite number of steps or activities that attain an objective. All of the solutions above are essentially programs that solve their respective problems. Each one is a list of instructions that are used to solve a problem.
Variable
A variable is a quantity that may change within the context of a problem or solution. In the examples above, the bottles are variables. The following demonstration can help us understand how the solution above works.
The same problem with another solution
There are multiple ways to solve a problem. For example, the same problem can also be solved by filling the first.
In the following widget, the correct steps are written in random order. Drag and drop the steps to arrange them into the correct sequence.