[Java] I implemented the combination.

I tried to implement a combination of math in Java

I implemented in Java a combination that takes different r out of n different. I've seen implementations that loop as many as r, I thought about various things so that it would be okay if r pieces changed.

Source code

The code below is designed to take 3 out of 5.

import java.util.ArrayList;
import java.util.List;

public class Trial {

    public static void main(String[] args) {
        Trial me = new Trial();
        me.exec(args);
    }

    public void exec(String[] args) {
        //Array of strings
        String[] strArray = new String[] { "a", "b", "c", "d", "e" };
        //Get the combination
        String[][] combinations = getCombinations(strArray, 3);
        //Result output
        for (String[] combination : combinations) {
            for (String str : combination) {
                System.out.print("  " + str);
            }
            System.out.println();
        }
    }

    private String[][] getCombinations(String[] strArray, int selectCount) {
        //List for packing results
        List<String[]> list = new ArrayList<>();
        //I use it a little, so I keep it in a variable
        int len = strArray.length;
        //Find the maximum value in binary from the length of the array.
        int dec = 0;
        for (int i = 0; i < len; i++) {
            dec += Math.pow(2, i);
        }
        //Decrement from the maximum value.
        for (int num = dec; 0 < num; num--) {
            //Make it a character string in binary notation. (0 is not filled)
            String bin = Integer.toBinaryString(num);
            if (!isCombination(bin, selectCount)) {
                //Ignore if the number of 1s does not match the selection.
                continue;
            }
            int j = bin.length() - 1;
            int tmplen = len - bin.length();
            String[] combination = new String[selectCount];
            int idx = selectCount - 1;
            for (int i = len - 1; tmplen <= i; i--) {
                if (bin.charAt(j--) == '1') {
                    combination[idx--] = strArray[i];
                }
            }
            list.add(combination);
        }
        return list.toArray(new String[0][0]);
    }

    private boolean isCombination(String str, int selectCount) {
        int sum = 0;
        for (int i = 0; i < str.length(); i++) {
            sum += Character.getNumericValue(str.charAt(i));
        }
        if (sum == selectCount) {
            return true;
        }
        return false;
    }
}

Execution result

  a  b  c
  a  b  d
  a  b  e
  a  c  d
  a  c  e
  a  d  e
  b  c  d
  b  c  e
  b  d  e
  c  d  e

The combination of 5 to 3 is 5! / (2! * (5-2)!) = 10 Maybe it fits.

Finally

I think there is a lot of room for improvement when considering performance and dealing with large numbers.

that's all

Recommended Posts

[Java] I implemented the combination.
I studied the constructor (java)
I tried the Java framework "Quarkus"
I tried the new era in Java
[day: 5] I summarized the basics of Java
[Java] I personally summarized the basic grammar.
I went to the Java Women's Club # 1
I compared the characteristics of Java and .NET
Why Java was the target language I hate
I touched on the new features of Java 15
Try the free version of Progate [Java I]
Combination calculation (Pascal's triangle) (Java)
[Java] I implemented the combination.
Generate CloudStack API URL in Java
Java
Java
I first touched Java ②
I first touched Java ③
I first touched Java ④
I first touched Java
[Java] I want to calculate the difference from the date
I summarized the types and basics of Java exceptions
I tried to implement the Euclidean algorithm in Java
What I researched about Java 8
I investigated the enclosing instance.
I started Java Gold (Chapter 1-1)
I didn't understand the behavior of Java Scanner and .nextLine ().
[Java] ArrayList → Should I specify the size in array conversion?
[JDBC] I tried to access the SQLite3 database from Java.
I tried to summarize the basics of kotlin and java
I summarized the collection framework.
I made roulette in Java.
[Rails] I implemented the validation error message by asynchronous communication!
I investigated Java primitive types
The Java Primer passed the blockage
I took Java SE8 Gold.
I tried Drools (Java, InputStream)
Combination calculation (Pascal's triangle) (Java)
I want to use the Java 8 DateTime API slowly (now)
I tried the Docker tutorial!
I tried the VueJS tutorial!
What I researched about Java 7
I tried using Java REPL
I read the Kotlin startbook
I tried the FizzBuzz problem
Java concurrency I don't understand
I tried using the CameraX library with Android Java Fragment
Java is the 5th day
I tried metaprogramming in Java
[Java] I thought about the merits and uses of "interface"
I want to simplify the conditional if-else statement in Java
What I researched about Java 5
Input to the Java console
I implemented the code to learn multiple images at once in the Watson Visual Recognition Collection in Java.
I made the "Sunshine Ikezaki game" I saw on Twitter in Java.
Java14 came out, so I tried record for the time being
I want to return to the previous screen with kotlin and java!
I tried the input / output type of Java Lambda ~ Map edition ~
I tried to translate the error message when executing Eclipse (Java)
I tried to summarize the methods of Java String and StringBuilder
[Java] I want to perform distinct with the key in the object
I tried to move the Java compatible FaaS form "Fn Project"
I passed the Oracle Java Bronze, so I summarized the outline of the exam.
I tried to display the calendar on the Eclipse console using Java.
Access the network interface in Java