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<this.size(); i++)
        if(this.get(i) != comp.get(i))
            return false;
    return true;
}
@Override
public int hashCode() {
    return 0;
}

public static void main(String[] args) {
    int n = 6;
    Set<Composition> 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<Composition> set = calc(num);
    Object[] arr  = set.toArray();
    int randomNum = new Random().nextInt(arr.length);
    return  (Composition)arr[randomNum];
}

public static Set<Composition> calc(int n) {
    Set<Composition> possibility = new HashSet<Composition>();
    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<Composition> partialPos = calc(n - i);
                    for (Composition pos : partialPos) {
                        pos.add(i);
                        possibility.add(pos);
                    }
                }
            }
            return possibility;
    }
}
public static String toStr(Set<Composition> 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;
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值