Answer:
See explaination
Explanation:
#include <iostream>
#include <vector>
using namespace std;
// function to print configuration for each pitcher
void printConfig(vector<int> w, int n)
{
cout << "Current configuration: [" << w[0];
for(int i=1; i<n; i++)
{
cout << ", " << w[i];
}
cout << "]" << endl;
}
void getOptions(vector<int> c, vector<int> w, int n, vector<pair<int, pair<int, int>>> &options)
{
// options count
int count = 0;
// fill
for(int i=0; i<n; i++)
{
if(c[i] > w[i] && w[i] >= 0)
{
count ++;
cout << count << ". Fill pitcher " << (i+1) << endl;
// add options to list
options.push_back(make_pair(1, make_pair(i, 0)));
}
}
// empty
for(int i=0; i<n; i++)
{
if(c[i] >= w[i] && w[i] > 0)
{
count++;
cout << count << ". Empty pitcher " << (i+1) << endl;
// add options to list
options.push_back(make_pair(2, make_pair(i, 0)));
}
}
// Pour pitcher i to pitcher j
for(int i=0; i<n; i++)
{
if(c[i] >= w[i] && w[i] > 0)
{
for(int j=0; j<n; j++)
{
if(i!=j && c[j] > w[j] && w[j] >= 0)
{
count++;
cout << count << ". Pour pitcher " << (i+1) << " to " << (j+1) << endl;
// add options to list
options.push_back(make_pair(3, make_pair(i, j)));
}
}
}
}
}
void execute(vector<int> c, vector<int> &w, pair<int, pair<int, int>> option)
{
int i = option.second.first;
// for fill
if(option.first == 1)
{
w[i] = c[i];
}
// empty
else if(option.first == 2)
{
w[i] = 0;
}
// pour
else
{
int j = option.second.second;
if(w[i] >= c[j])
{
w[i] = w[i] - c[j];
w[j] = c[j];
}
else
{
w[j] = w[i];
w[i] = 0;
}
}
}
int main()
{
// required variables
int choice, n, temp, g, flag, moves = 0;
// vectors are dynamic sized arrays
vector<int> c, w;
vector<pair<int, pair<int, int>>> options;
// select puzzle
cout << "Select the puzzle to solve:\n";
cout << "1. Pitchers\n";
cout << "2. Eight puzzle\n";
cout << "Your selection: ";
cin >> choice;
if(choice == 1)
{
// input values required
cout << "Enter the number of pitchers: ";
cin >> n;
// array for pitchers
cout << "Enter the capacities of the " << n << " pitchers (gallons): ";
for(int i=0; i<n; i++)
{
cin >> temp;
c.push_back(temp);
w.push_back(0);
}
cout << "Enter the goal (gallons): ";
cin >> g;
// start game
while(true)
{
// print configuration
printConfig(w, n);
// check for goal state
flag = 0;
for(int i=0; i<n; i++)
{
if(w[i] == g)
{
flag = 1;
break;
}
}
if(flag)
{
cout << "Great! You have reached the goal in " << moves << " moves. Bye." << endl;
break;
}
// get and print options
//empty previous options
options.clear();
getOptions(c, w, n, options);
// ask for user's selection
cout << "Your selection: ";
cin >> choice;
// update moves
moves++;
// perform according to the selection
execute(c, w, options[choice-1]);
}
}
return 0;
}