3

Below is the list of Strings i need combinations for with certain conditions.

"MSD" ,"EEE", "RSR", "OCL", "SMS","RTS"

The conditions for the combinations are

  1. Combinations should be having atleast two string (E.g : ("EEE"
    ,"RSR") ,("EEE","RSR","OCL"))
  2. Combinations should be consisting adjacent strings (E.g: ("OCL","SMS"),("MSD","EEE","RSR") are valid. But not ("EEE","OCL"). Since "EEE" and "OCL" are not next to each other)

Java implementation is much welcome for this problem.

public class Dummy {

    public static void main(String[] args) {
        String[] str = { "MSD" ,"EEE", "RSR", "OCL", "SMS","RTS" };
        List<String> list = new ArrayList<>();
        for (int j = 0; j < str.length; j++) {
            String temp = "";
            for (int i = j; i < str.length; i++) {
                temp = temp + " " + str[i];
                list.add(temp);
            }
        }

        for (String string : list) {
            System.out.println(string);
        }
    }
}

Sorry for the late update of my tried code

3
  • and what have you tried? Commented Dec 30, 2015 at 13:03
  • Would wrap-around be valid? Like rts-msd ?
    – Jan
    Commented Dec 30, 2015 at 13:16
  • yes definetly as long as they are adjacent. "eee-rsr" is valid but not "rsr-eee" so "rts-msd" also not valid
    – Tiny Rick
    Commented Dec 30, 2015 at 13:20

1 Answer 1

2
for (int j = 0; j < str.length; j++) {
    String temp = "";
    for (int i = j; i < str.length; i++) {
        if ("".equals(temp))
            temp = str[i]; // assign the String to temp, but do not add to list yet
        else {
            temp = temp + " " + str[i];
            list.add(temp); // now that temp consists of at least two elements
                            // add them to the list
        }
    }
}

Fixes the problem that single entries are listed as well. And thus results in:

MSD EEE
MSD EEE RSR
MSD EEE RSR OCL
MSD EEE RSR OCL SMS
MSD EEE RSR OCL SMS RTS
EEE RSR
EEE RSR OCL
EEE RSR OCL SMS
EEE RSR OCL SMS RTS
RSR OCL
RSR OCL SMS
RSR OCL SMS RTS
OCL SMS
OCL SMS RTS
SMS RTS
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.