Tiny Rick
Tiny Rick

Reputation: 276

Combinations for the a list of Strings

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

Upvotes: 3

Views: 123

Answers (1)

LordAnomander
LordAnomander

Reputation: 1123

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

Upvotes: 2

Related Questions