原理:利用猴子排序随机次数的期望值等于排序数字个数的阶乘。
(猴子排序详情请参考猴子排序详解-CSDN博客)
下面是计算5的阶乘的
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
public class MKTest {
public static void main(String[] args) {
int value = 5;
int result = computeFactorial(value);
System.out.println(result);
}
private static int computeFactorial(int value) {
int n = 1000000;
int sum =0;
for (int i = 0; i < n; i++) {
MkResult result = mkNumberSort(1, 1000, value);
int times = result.getTimes();
sum = sum + times;
}
return (int) Math.round(sum * 1.0 / n);
}
private static MkResult mkNumberSort(int min, int max, int count) {
List<Integer> aList = RandomIntegerUtils.getRandomIntegers(min, max + 1, count);
return mkSort(aList);
}
private static MkResult mkSort(List<Integer> list) {
int times = 0;
while (true){
times++;
int size = list.size();
List<Integer> indexRandomList = RandomIntegerUtils.getRandomIntegers(0, size, size);
List<Integer> sortList = new ArrayList<>();
for (Integer index : indexRandomList) {
Integer value = list.get(index);
sortList.add(value);
}
Integer lastValue = null;
boolean sort = true;
for (Integer value : sortList) {
if (lastValue != null && lastValue > value){
sort = false;
break;
}
lastValue = value;
}
if (sort){
return new MkResult(list, sortList, times);
}
}
}
@Data
private static final class MkResult{
private final List<Integer> rawList;
private final List<Integer> sortList;
private final int times;
public MkResult(List<Integer> rawList, List<Integer> sortList, int times) {
this.rawList = rawList;
this.sortList = sortList;
this.times = times;
}
}
}
执行结果:
其中的工具类RandomIntegerUtils请参考猴子排序详解-CSDN博客