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;
}
}