InitialRoute - Add services from a loop

Hiya, trying to set and maintain an entire InitialRoute, but I cannot add jobs in a loop.

// Add all the jobs
         * build services at the required locations, each with a capacity-demand of 1.
        int jobCount = 1;
        for (int i = 0; i < points.size(); i++) {
            int offset = i + 1;
            Service service = Service.Builder.newInstance(String.valueOf(jobCount)).addSizeDimension(WEIGHT_INDEX, 1).setLocation(Location.newInstance(points.get(i), points.get(offset))).build();
        int trigger = 1;
        if(trigger == 1){
            VehicleRoute initialRoute = null;
            for (Job j : vrpBuilder.getAddedJobs()) {
                initialRoute = VehicleRoute.Builder.newInstance(vehicle).addService((Service) j).build();


VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder.newInstance().addVehicle(vehicle).setFleetSize(FleetSize.INFINITE).setRoutingCost(costMatrix).addInitialVehicleRoute(initialRoute).build();

This doesn’t work. How can I delay the .build until I’ve added all jobs?

I’m trying to loop through and services to the route as you would adding jobs to vrpBuilder.

Instead of doing initialRoute = VehicleRoute.Builder.newInstance(vehicle).addService(service1).addService(service2).build();
How do I loop through and add them one at a time?

Trigger is just so I can disable initialRoute if I don’t want to follow sequencing.

Hi @Gregws,

I created a function that gets passed all jobs (services/shipments) and then adds them like this:

 VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance();
 if(services.length > 0) vrpBuilder.addAllJobs(List.of(services));
 if(shipments.length > 0) vrpBuilder.addAllJobs(List.of(shipments));

Hope this helps out. After you can use, in my function I return that as a problem object.

1 Like

Thanks Matt,

I ended up moving away from initialRoutes but will use your suggestion if I need to do initialRoutes again.


Powered by Discourse