HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Bridge Crossing - Classic Puzzle

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
bridgecrossingpuzzleclassic

Problem

Problem - The classic puzzle of finding the minimum amount of time required to cross a bridge given that only two people can cross the bridge at any one time.
Since they have only one flashlight (it's dark and they need the flashlight), the two people move at the speed of the slower one.

Constraints - Upto 6 people (although it should work for a higher number of people)

Input - Number of people (up to 6 tested) & Sorted vector of time required by each person to cross the bridge.

Output - Minimum time possible

int main()
{
  vector v; int n; int time;
  int items;
  int k = 2;
  cin>>items;
  for (int i = 0; i > n;
    v.push_back(n);
   }

  if (v.size() == 1)
  {
    cout = 2)
  {
    time += v[0] + v[last - k];
    k++;
  }
  time = time + v[1];

  cout << time;
  return 0;
}


Note : Code will not work for 2 people, missed a special case.

Solution

The overwhelming first impression I get from your code is that without the text description above, I wouldn't have a clue what it is you're trying to do. A lot of these types of problems have some kind of prompting which helps, however your code doesn't have that, its only output is time after it's finished.

The two main improvements I'd suggest are:

  • Put your code in a function that defines an interface.



  • Use variable names that have some kind of meaning.



Implementing these two basics would go a long way to making your code easier to follow.

For example, your vector v might be people?!?

You could have a method calculate_minimum_time_to_cross_bridge, which took in a list of people and returned the time.

Whilst your variable names might have meaning to you, they have no meaning a new reader without context.

One final point is that whilst you can do this:

vector v; int n; int time;


It's generally considered bad form. One declaration per line means the declarations are less likely to get lost.

Code Snippets

vector<int> v; int n; int time;

Context

StackExchange Code Review Q#149418, answer score: 4

Revisions (0)

No revisions yet.