一个领导者选举算法
[java]根据Matrix67的"囚徒与灯泡"文章而写:根据Matrix67的"囚徒与灯泡"文章而写:[java]public class Wakeup {static class People {//记录第一次进入时确定的位置 0未确定,-1 左边 1右边.public int Position;//手上的球public int BallNum;//标识public int Id;//是否还在参与跷跷板游戏public boolean OnLine;public People(int Id) {this.Id = Id;Position = 0;BallNum = 2;OnLine = true;}}private static int PeopleCount=100;//参与者人数private static boolean BoxIsEmpty = true;// 盒子是否是空的private static boolean LeftIsWeight = false;//跷跷板左边低public static void main(String[] args) {People[] thePeoples = new People[100];for (int i = 0; i < PeopleCount; i++) {thePeoples[i] = new People(i);}boolean finished = false;int k = 0;int i = 0;int outNum = 0;while (!finished) {k++;i = (new Random().nextInt(PeopleCount)) % PeopleCount;People theP = thePeoples[i];if (theP.OnLine) {if (theP.Position == 0) {theP.Position = LeftIsWeight ? -1 : 1;LeftIsWeight = !LeftIsWeight;} else {if (theP.Position == -1) {if (LeftIsWeight) { // 左边本侧低,如果有球则取if (!BoxIsEmpty) {BoxIsEmpty = true;theP.BallNum++;}} else {// 本侧高,空就放球if (BoxIsEmpty) {if (theP.BallNum > 0) {theP.BallNum--;BoxIsEmpty = false;}}}} else {if (LeftIsWeight) {// 本侧高,空就放球if (BoxIsEmpty) {if (theP.BallNum > 0) {theP.BallNum--;BoxIsEmpty = false;}}} else {// 本侧低,非空就取球if (!BoxIsEmpty) {BoxIsEmpty = true;theP.BallNum++;}}}}//如果没有球,则退出,什么都不做if (theP.BallNum <= 0) {LeftIsWeight = !LeftIsWeight;theP.OnLine = false;&补充:软件开发 , Java ,
上一个:策略模式
下一个:java创建对象的四种方法
- 更多JAVA疑问解答:
- java怎么在线读取ftp服务器上的文件内容
- 关于程序员的职业规划
- HTML和JSP矛盾吗?
- java小程序如何打包?
- java怎么split路径文件名?
- jsp+javaBean中Column 'ordersPrice' specified twice的错误
- Java TCP/IP Socket网络编程系列
- 大家来讨论一下我到底该用什么好?Swing 还是 JavaFX
- 关于Hibernate实体自身多对一的抓取问题
- 关于apache2+tomcat群集出现的问题
- spring 获取上下文问题
- SSH 导入导出excel 谁有这块的资料吗?
- Ext TreePanel 刷新问题
- springmvc 加载一个jsp页面执行多个方法 报404
- checkbox数组action怎么向页面传值