// SYSC 2002 Winter 2011 Assignment #1 #include "stdstuff.h" // function finds the closest distance between the patrol boat and the smuggler, given the speed of // the patrol boat (m/s), time the smuggler starts (s), smuggler speed (m/s), and smuggler heading (radians). double closestApproach (double patrolSpeed, int smugglerStartTime, double smugglerSpeed, double smugglerHeading, bool debug) { const double riverWidth = 6000, patrolRadius = 2000; double cosHeading = cos (smugglerHeading), sinHeading = sin (smugglerHeading), smugglerX, smugglerY, patrolX, patrolY, distance, smallestDistance; int t = smugglerStartTime; for (;;) { smugglerX = -(riverWidth / 2) + smugglerSpeed * (t - smugglerStartTime) * cosHeading; if (smugglerX > riverWidth / 2) { return smallestDistance; } smugglerY = smugglerSpeed * (t - smugglerStartTime) * sinHeading; patrolX = patrolRadius * cos (patrolSpeed * t / patrolRadius); patrolY = patrolRadius * sin (patrolSpeed * t / patrolRadius); distance = sqrt (pow(smugglerX - patrolX, 2) + pow(smugglerY - patrolY, 2)); if (t == smugglerStartTime || distance < smallestDistance) { smallestDistance = distance; } // output debug info every minute) if (debug && ((t - smugglerStartTime) % 60 == 0)) { cout << "t = " << t << " patrol pos = [" << patrolX << ", " << patrolY << "] smuggler pos = [" << smugglerX << ", " << smugglerY << "]\n"; } t++; } } int main () { double patrolSpeed, smugglerSpeed, smugglerHeading, distance; int smugglerStartTime; bool debug; char option; cout << "**** Instructor's solution. ****\n"; cout << "Do you want debug output (Y/N): "; cin >> option; debug = toupper(option) == 'Y'; // first get a valid patrol speed for (;;) { cout << "Enter patrol speed: "; cin >> patrolSpeed; if (patrolSpeed >= 10 && patrolSpeed <= 50) { break; } cout << "Invalid values ignored." << endl; } // now get the smuggler details (loop until all 0s entered) for (;;) { cout << "Enter smuggler departure time, speed, and heading.\n(0 0 0 to stop): "; cin >> smugglerStartTime >> smugglerSpeed >> smugglerHeading; if (smugglerStartTime == 0 && smugglerSpeed == 0 && smugglerHeading == 0) { break; } // check for invalid values if (smugglerStartTime < 0 || smugglerSpeed < 10 || smugglerSpeed > 50 || smugglerHeading > 20 || smugglerHeading < -20) { cout << "Invalid values ignored." << endl; } else { // calculate closest distance and output it distance = closestApproach (patrolSpeed * (1000.0 / 3600), smugglerStartTime, smugglerSpeed * (1000.0 / 3600), smugglerHeading * (M_PI / 180.0), debug); cout << "That smuggler will come within " << distance << " m of the patrol boat." << endl; } } pause(); return 0; }