简体   繁体   中英

How to get n/2-digit combinations from n digit number

I'm struggling with this algorithm. It should work like this:

If I input fe 6880, my program should output 80 86 80 86 60 68 68.

As you can see, combinations are repeating. That's because it looks at every digit as it is a different object. In my program it's correct.

Here is my code:

public static Set<Integer> get2DCombinations(List<Integer> digits) {
    Set<Integer> combinations = new TreeSet<>();

    int t = 0;
    for(Integer i : digits) {
        for (Integer j : digits) {
            t = i * 10 + j;
            if (t / 10 >= 1) {
                combinations.add(t);
            }
        }
    }

    return combinations;
}

It returns a specific set of combinations where all combinations have 2 digits.

It works perfectly, but only with 4-digit numbers. Of course, I can use one more for-each loops, but is there a way to automate it?

So if I input 6-digit number it should output all possible 3-digit combinations of its digits, and if I input 8-digit number, it should output all possible 4-digit combinations. Input numbers always have even amount of digits.

Could you please point out for me how to do so?

You need a recursive program that will generate all the combinations for your input. Here's a solution of mine. My method accepts a String as input (it's just shorted program and easier, you can adapt it to your needs):

public static Set<String> get2DCombinations(String input) {
    return backtracking("", input, input.length() / 2) ;
}

public static Set<String> backtracking(String actual, String remaining, int length) {
    if (actual.length() == length) {
        return new HashSet<>(Arrays.asList(actual));
    }

    Set<String> result = new HashSet<>();
    for(int i = 0; i < remaining.length(); i++) {
        result.addAll(backtracking(actual + remaining.charAt(i), remaining.substring(0, i) + remaining.substring(i + 1), length));
    }
    return result;
}

And you call the method like so:

System.out.println(get2DCombinations(input));

Result:

[88, 68, 06, 80, 08, 60, 86]

As I mentioned in the comment, your are missing some of the combinations. This solution generates all of them.

Try calculating n / 2 first. So, if n is 6, then n / 2 = 3. Then you know before you start fining the combinations that you are looking for combinations of 3 digits. Then you want to find the right algorithm to find the combinations. Part of problem solving is breaking down problems to smaller problems. That is what I did here. I can not solve it for you, however, because it is better for you to solve yourself, and second, there details that you dind't provide so it is hard to give the right solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM