Ad

We are working for a Delivery company.This Kata requires the user to calculate the closest daily routes for Delivery based on the nearest location first to be delivered in the daily routes of deliveries to be made.

There is a single method - public List<List> ClosestXDestinations(int numDestinations,
List<List> allLocations, int numDeliveries), which takes in 3 parameters.

  1. numDestinations - the number of destinations for the driver to deliver products to for today.
  2. allLocations - A list of list having all locations of x and y coordinates of locations.
  3. numDeliveries - the number of deliveries to be made today.
  
The closest destination is calculated as below.

Example:
--------
input:

numDestinations = 3
allLocations = [[1,2],[3,4],[1,-1]]
numDeliveries = 1

Output:

[[1,-1]]

Explanation:
The distance of the truck from location [1,2] is squareroot(5) = 2.236
The distance of the truck from location [3,4] is squareroot(25) = 5
The distance of the truck from location [1,-1] is squareroot(2) = 1.141
numDeliveries is 1, hence the output is [1,-1]
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeMap;

public class NearestDelivery {

	Integer val = 0;
	int x = 0, y = 0;

	public List<List<Integer>> ClosestXDestinations(int numDestinations,
			List<List<Integer>> allLocations, int numDeliveries) {
		TreeMap<Double, List<Integer>> sortedMap = new TreeMap<>();
		for (int i = 0; i < allLocations.size(); i++) {
			List<Integer> list = allLocations.get(i);
			if (!list.isEmpty()) {
				if (list.size() == 1) {
					x = ((Integer) list.get(0)).intValue();
					y = 0;
				} else if (list.size() == 2) {
					x = ((Integer) list.get(0)).intValue();
					y = ((Integer) list.get(1)).intValue();
				}

				val = x * x + y * y;
				double dVal = Math.sqrt(val);
				sortedMap.put(dVal, list);
			}
		}
		ArrayList<List<Integer>> as = new ArrayList<>(sortedMap.values());
		while (as.size() > numDeliveries) {
			as.remove(as.size() - 1);
		}
		return as;
	}


}