Answer to Question #100128 in C++ for unique

Question #100128
2. Create a class box, each box has an int ID, and an east and west side, these are represented as Booleans, all of these are randomly assigned true or false. If true you can pass through that side. These are ONE WAY doors. If false it is a wall. Create a ROW of 8 random boxes. Determine which box has the maximum reachability. Use : to represent a door and a | to represent a wall in your display, example follows:

|0| :1| :2: |3: |4| |5: :6: |7:
Box 0 you can go no where
Box 1 you can visit 0 ((box 1 has a West door))
Box 2 you can visit 1 and 0 AND 3 and 4
Box 3 you can visit 4
Box 4 you can go no where
Box 5 you can visit 6 and 7
Box 6 you can visit 5 and 7
Box 7 you can go no where
The box with maximum reachability is box 2 where you can reach 0,1,3,4
1
Expert's answer
2019-12-11T10:58:48-0500
#include <iostream>
#include <vector>


using namespace std;


class Box
{
public:
	int ID;
	bool west, east;
	Box(int id)
	{
		ID = id;
		west = rand() % 2;
		east = rand() % 2;
	}
};










int main()
{
	vector<Box> box;
	Box box1(1);
	box.push_back(box1);
	Box box2(2);
	box.push_back(box2);
	Box box3(3);
	box.push_back(box3);
	Box box4(4);
	box.push_back(box4);
	Box box5(5);
	box.push_back(box5);
	Box box6(6);
	box.push_back(box6);
	Box box7(7);
	box.push_back(box7);
	Box box8(8);
	box.push_back(box8);


	for (int i = 0; i < 8; i++)
	{
		if (box[i].west)
			cout << ":";
		else
			cout << "|";
		cout << i + 1;
		if (box[i].east)
			cout << ":";
		else
			cout << "|";
	}


	int num = 0;
	int count = 0;
	for (int i = 0; i < 8; i++)
	{
		int m = i;
		int n = i;
		int mi = 0, ni = 0;
		while (true)
		{
			if (m < 8)
			{
				if (box[m].east == true)
				{
					m++;
					mi++;
				}
				else
				{
					break;
				}
			}
			else
				break;
		}


		while (true)
		{
			if ((n >= 0))
			{
				if (box[n].west == true)
				{
					n--;
					ni++;
				}
				else
				{
					break;
				}
			}
			else
				break;
		}
		if (ni + mi > count)


		{
			num = i;
			count = ni + mi;
		}
	}
	vector<int> rooms;
	int ma = num, na = num;


	while (true)
	{
		if (ma < 8)
		{
			if (box[ma].east == true)
			{
				ma++;
				rooms.push_back(ma);
			}
			else
			{
				break;
			}
		}
		else
			break;
	}
	while (true)
	{
		if ((na >= 0))
		{
			if (box[na].west == true)
			{
				na--;
				rooms.push_back(na);
			}
			else
			{
				break;
			}
		}
		else
			break;


	}


	cout << "\n The box with maximum reachability is box " << num << " where you can reach ";
	int s = rooms.size();
	for (int i = 0; i < s; i++)
		cout << i + 1 << ",";


}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS