通过代码将所有号码写出来,然后模拟两亿人买彩票,最后把没有人买的遗珠彩票挑选出来,快来试试吧
package com.jd.jdt.actvisual.admin.web.handler.JSFAuth;
import java.util.*;
public class Lottery5Million {
public static final int RED_MAX = 33;
public static final int RED_TOTAL = 6;
public static final int BLUE_MAX = 16;
public static final int BUY_TIMES = 200_000_000;
public static final int PRINT_TIMES = 5;
public static final int WANT_BUY = 1;
public static final String UNDERLINE = "_";
public static void main(String[] args) {
Random random = new Random();
Map<String, Integer> allMap = new HashMap<>(17721088);
List<Integer> red = new ArrayList<>();
for(int i = 1; i <= RED_MAX; i++) {
red.add(i);
}
List<Integer> now = new LinkedList<>();
generateAll(allMap, red, now, 0);
System.out.println("生成了所有可能的组合,总共 " + allMap.size() + " 种组合。");
for(int i = 0; i < BUY_TIMES; i++) {
mockSomeoneBuy(allMap, random);
if(i > 0 && i % (BUY_TIMES / PRINT_TIMES) == 0) {
System.out.println("已有 " + i + " 人买了彩票。");
}
}
allMap.entrySet().removeIf(kv -> kv.getValue() > 0);
List<String> goodLotteryList = new ArrayList<>(allMap.keySet());
for(int i = 0; i < WANT_BUY; i++) {
int index = random.nextInt(goodLotteryList.size());
String shot = goodLotteryList.get(index);
System.out.println("你可以买这一注 ==> " + printLottery(shot));
goodLotteryList.remove(index);
}
}
public static String printLottery(String lottery) {
String[] numbers = lottery.split(UNDERLINE);
StringBuilder result = new StringBuilder();
result.append("红球:");
int i = 0;
for(; i < RED_TOTAL; i++) {
result.append(numbers[i]).append(" ");
}
result.append("蓝球:").append(numbers[i]);
return result.toString();
}
public static void generateAll(Map<String, Integer> allMap, List<Integer> red, List<Integer> now, int nextIndex) {
if(now.size() == RED_TOTAL) {
String redString = redString(now);
for(int blue = 1; blue <= BLUE_MAX; blue++) {
allMap.put(redString + blue, 0);
}
return;
}
for(int i = nextIndex; i < red.size(); i++) {
int redNum = red.get(i);
now.add(redNum);
generateAll(allMap, red, now, i + 1);
now.remove(now.size() - 1);
}
}
public static void mockSomeoneBuy(Map<String, Integer> allMap, Random random) {
List<Integer> red = new ArrayList<>();
for(int i = 1; i <= RED_MAX; i++) {
red.add(i);
}
List<Integer> buy = new ArrayList<>();
for(int i = 0; i < RED_TOTAL; i++) {
int rand = random.nextInt(red.size());
buy.add(red.get(rand));
red.remove(rand);
}
Collections.sort(buy);
String mockString = redString(buy);
mockString += random.nextInt(BLUE_MAX) + 1;
allMap.put(mockString, allMap.get(mockString) + 1);
}
public static String redString(List<Integer> red) {
StringBuilder redString = new StringBuilder();
for (Integer num : red) {
redString.append(num).append(UNDERLINE);
}
return redString.toString();
}
}