Enumeration of combination patterns using List

1. Overview

Until now, when acquiring all patterns of combinations, permutations were listed in an anagram format for each character. For example, in A.B.C, the following 3! (= 6) patterns

ABC
ACB
BAC
BCA
CAB
CBA

Reference: Enumeration of all combinations Java

However, the above method did not work when I wanted to treat a value of two or more characters as one element. (* For example, in the case of 4.8.10, I want to use 10 as one element, but since recombination occurs in character units, it is listed in the 4! Pattern of 4.8.1.0 as shown below).

4810
4801
4180
4108
4081
4018
8410
8401
8140
8104...
The following is omitted

Therefore, I wondered if it would be possible to somehow realize the enumeration of permutations regardless of the number of characters.

2. List of elements using List

In the above reference, the combination patterns are listed using String, which is a set of chars, and if so, the pattern enumeration should be feasible even if the set is an array. In the above reference, since the size of the element is modulated in the method, I came up with the idea of using List, which is a variable length array.

Below, the created code


    public static void main(String[] args) {
        String[] sArray = {"4", "8", "10"};
        List<String> sList = new LinkedList<>(Arrays.asList(sArray));
        List<String> cList = new LinkedList<>();
        permutation(sList, cList);
    }
    
    private static void permutation(List<String> sList, List<String> cList) {
    	for (int i = 0; i < sList.size(); i++) {
    		if (sList.size() == 1) {
    			cList.addAll(sList);
    			System.out.println(cList);
    		} else {
    			List<String> base = new LinkedList<>(sList);
    			List<String> container = new LinkedList<>(cList);
    			container.add(base.get(i));
    			base.remove(i);
    			permutation(base, container);
    		}
    	}
    }  

Below, output

[4, 8, 10]
[4, 10, 8]
[8, 4, 10]
[8, 10, 4]
[10, 4, 8]
[10, 8, 4]

We realized the permutation enumeration regardless of the number of characters that was the purpose.

3. Summary

Since I coded it in a hurry, there may be a better way to write it.

Since I am a beginner in programming and Qiita is also the first post, I would appreciate it if you could give me any suggestions.

Recommended Posts

Enumeration of combination patterns using List
[Android] Display of input candidates using List Popup Window
Example of using vue.config.js
List of beginners (List) memo
Summary of using FragmentArgs
Try using F # list
Summary of using DBFlow
Example of params using where
Summary of using Butter Knife
Example of using abstract class
Combination of search and each_with_index
Rate-Limiting using RateLimiter of Resilience4j
[Ruby] List of basic commands
Enumeration of all combinations Java
List of hosts file locations
[Java] Summary of design patterns