Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combinations for the a list of Strings

Tags:

java

math

puzzle

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

like image 484
Tiny Rick Avatar asked Jan 27 '26 03:01

Tiny Rick


1 Answers

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
like image 66
LordAnomander Avatar answered Jan 29 '26 17:01

LordAnomander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!