java生成一个数字的所有组合并随机返回一个

package net.iqulian.exchange_backend.util;

import java.util.*;

public class Composition extends ArrayList {

@Override
public boolean equals(Object other){
    Composition comp = (Composition)other;
    Collections.sort(this);
    Collections.sort(comp);
    if(this.isEmpty() || comp.isEmpty() || this.size() != comp.size())
        return false;
    for(int i=0; i set = calc(n);
    Object[] arr  = set.toArray();
    Composition c =  (Composition)arr[2];
    System.out.println(c);
    for (Integer i: c) {
        System.out.println(i);
    }
    System.out.println(toStr(calc(n)));
}

/**
 * 从所有组合中随机获取一个组合
 * @param num
 * @return
 */
public static Composition getRandomComposition(Integer num){
    Set set = calc(num);
    Object[] arr  = set.toArray();
    int randomNum = new Random().nextInt(arr.length);
    return  (Composition)arr[randomNum];
}

public static Set calc(int n) {
    Set possibility = new HashSet();
    Composition composition = new Composition();
    switch (n) {
        case 1:
            composition.add(1);
            possibility.add(composition);
            return possibility;
        case 2:
            composition.add(1);
            composition.add(1);
            possibility.add(composition);
            return possibility;
        default:
            for (int i = 1; i <= n / 2; i++) {
                composition = new Composition();
                composition.add(i);
                composition.add(n - i);
                possibility.add(composition);
                if (i <= n - i) {
                    Set partialPos = calc(n - i);
                    for (Composition pos : partialPos) {
                        pos.add(i);
                        possibility.add(pos);
                    }
                }
            }
            return possibility;
    }
}
public static String toStr(Set possibility) {
    String str = "total : " + possibility.size() + "\n";
    for (Composition pos : possibility)
        str += toStr(pos);
    return str;
}
public static String toStr(Composition composition) {
    String str = composition.get(0) + "";
    for (int i = 1; i < composition.size(); i++)
        str += (" + " + composition.get(i));
    str += "\n";
    return str;
}

}

你可能感兴趣的:(java生成一个数字的所有组合并随机返回一个)