0

(I have no idea what to title this, so apologies if it's vague or inaccurate. I looked around the 'Net for an answer to this, but I wasn't sure what to search for this problem, thus, I came here.)

I need a method to take a string and take the characters from it and put it into a pattern.

So, let's say String s = "abcd". This method needs to take that and print "abcd," "bcd," "abc," "cd," "bc," "ab," "d," "c," "b," "a". I have completely no idea how to make this work, so anything would be useful.

Below is a method that is similar to what I'm trying to achieve.

void printSub3(String s){
    for(int i = 0; i < s.length(); i++){
        for(int j = 0; j < s.length()-i; j++){
            System.out.printf(s.substring(s.length()-j-i-1, s.length()-j)+", ");
        }
    }
}
Conf3tti
  • 29
  • 4
  • I'm voting to close this question as off-topic because Stack Overflow is not a free homework service. – Robert Columbia Oct 22 '16 at 01:26
  • You are almost there, It helps using a help variable `int n = s.length();` for better readability. Turning the j-loop around `for (int j = i; j >= 0; --j) {` for `j` being the start position of the substring, and start with the maximal length `n - i` would do. – Joop Eggen Oct 22 '16 at 01:49

2 Answers2

1

You can construct the list of all sub-sets by counting from 1 to 2n-1, inclusive, and using the numbers as bit patterns to decide which elements of the string to take (ones) and which ones to skip (zeros):

String str = "abcd";
for (int mask = 1 ; mask != 1<<str.length() ; mask++) {
    StringBuilder bld = new StringBuilder();
    for (int i = 0 ; i != str.length() ; i++) {
        if ((mask & 1<<i) != 0) {
            bld.append(str.charAt(i));
        }
    }
    System.out.println(bld);
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

I would recommend to try the question by yourself, using the hints:

Use n-bits as flag for each character's possible presence in resulting string, where n is num of char in the input string. Toggle the flag to cover all values in range [0-(2^n-1)], and produce the string corresponding to those bit pattern.

Good question to learn bitwise shift operation and bit-pattern/masking. So try coding yourself.

Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79