PTN
PTN

Reputation: 1692

Combine for loops with different end points

I have a DurationBetween class that represents the travel duration between an original location and a destination. The class has three attributes, int dur, String orig, and String dest.

I am trying to get the duration between a set of locations. I have already done the calculation for that.

I have 3 array lists that looks like this:

listOrig: current, dest1, dest2, dest3
listDest: dest1, dest2, dest3
listDur: 2, 3, 5, 0, 1, 3, 9, 0, 2, 3, 2, 0

listDur is generated by getting the duration from current to dest1, dest2, dest3, then dest1 to dest1, dest2, dest3, then dest2 to dest1, dest2, dest3, etc. Which makes a total of 12. Note that duration = 0 when the original location is the same as the destination.

Now I need to initiate a bunch of DurationBetween classes to store pairs of orig and dest. So something like

DurationBetween durationBetween = new DurationBetween(2, current, dest1);
DurationBetween durationBetween = new DurationBetween(3, current, dest2);
DurationBetween durationBetween = new DurationBetween(5, current, dest3);
DurationBetween durationBetween = new DurationBetween(1, dest1, dest2);
...

I'm having trouble initializing the classes because the lists have different sizes. The code I have right now gives me the pairs of orig and dest, but I cannot get the dur to update accordingly to the pairs.

This is what I have:

// create classes of dur, orig, dest
// one orig will go to multiple dest and have multiple dur
for (int i = 0; i < listOrig.size(); i++) {
    for (int j = 0; j < listDest.size(); j++) {
        String orig = listOrig.get(i);
        String dest = listDest.get(j);

        // DEFINITELY NOT RIGHT
        for (int k = 0; k < listDur.size(); k++) {
            int dur = Integer.parseInt(listDur.get(k));

            if (dur != 0) { // skip instances where orig and dest are the same
               DurationBetween durationBetween = new DurationBetween(dur, orig, dest);
               listDurBtwn.add(durationBetween);
            }
        }
    }
}

public class DurationBetween {
    private int dur;
    private String orig;
    private String dest;

    public DurationBetween(int dur, String orig, String dest) {
        this.dur = dur;
        this.orig = orig;
        this.dest = dest;
    }
}

Upvotes: 0

Views: 52

Answers (1)

eugenioy
eugenioy

Reputation: 12403

I think you need to replace the part that is "DEFINITELY NOT RIGHT" with this:

    int k = (i * listDest.size()) + j;
    int dur = Integer.parseInt(listDur.get(k));
    if (dur != 0) { // skip instances where orig and dest are the same
        DurationBetween durationBetween = new DurationBetween(dur, orig, dest);
        listDurBtwn.add(durationBetween);
    }

Upvotes: 1

Related Questions