2020 - Households essentially use the closest outlet, make it so the outlet must be within a distance of 20

From TRCCompSci - AQA Computer Science
Jump to: navigation, search

The Issue

Find the following method in the company class:

public void AddVisitToNearestOutlet(int x, int y)
        {
            int nearestOutlet = 0;
            double nearestOutletDistance, currentDistance;
            nearestOutletDistance = Math.Sqrt((Math.Pow(outlets[0].GetX() - x, 2)) + (Math.Pow(outlets[0].GetY() - y, 2)));
            for (int current = 1; current < outlets.Count; current++)
            {
                currentDistance = Math.Sqrt((Math.Pow(outlets[current].GetX() - x, 2)) + (Math.Pow(outlets[current].GetY() - y, 2)));
                if (currentDistance < nearestOutletDistance)
                {
                    nearestOutletDistance = currentDistance;
                    nearestOutlet = current;
                }
            }
            outlets[nearestOutlet].IncrementVisits();
        }

This code calculates the magnitude of the vector between the current location (x and y in the parameters) and each outlet. The shortest distance is used to select a particular outlet.

With the nearest outlet, the method 'IncrementVisits' is run to add a visit for this outlet. The issue is that this could be too far away.

The Solution

We need to add some logic around the 'outlets[nearestOutlet].IncrementVisits()' line. We should check the distance with the distance the household is willing to travel.

Example

Add the following logic around the 'outlets[nearestOutlet].IncrementVisits()' line:

            if (nearestOutletDistance < 20)
            {
                outlets[nearestOutlet].IncrementVisits();
            }