Java编写的24点纸牌游戏
任意4个1-13数字,加减乘除计算24点。
实现原理:
1)排列组合4个数字
2)计算每次排列组合的可能性
Cal24.java
importjava.util.HashSet; importjava.util.Set; publicclassCal24{ privatestaticfinaldoubleprecision=0.00001; privatestaticfinalinttarget=24; publicString[]execute(String[]inputs){ int[]digits=newint[4]; for(inti=0;i<inputs.length;i++){ digits[i]=Integer.valueOf(inputs[i]); } returnnewString[]{calc(digits)}; } privateStringcalc(finalintdata[]){ finalSet<String>out=newHashSet<String>(); Combinationdigit=newCombination(){ @Override protectedvoidhandle(int[]result){ finalint[]r=result; Combinationoper=newCombination(){ @Override protectedvoidhandle(int[]c){ doublex=r[0]; for(inti=0;i<r.length-1;i++){ x=doCalculate(x,r[i+1],c[i]); } if(Math.abs(Math.abs(x)-target)<precision||Math.abs(Math.abs(1/x)-target)<precision){ StringBuildersb=newStringBuilder(); for(intj=0;j<r.length;j++){ sb.append(r[j]); if(j!=r.length-1){ sb.append(getOperation(c[j])); } } out.add(sb.toString()); } } }; oper.combine(newint[]{0,1,2,3},data.length-1,true); } }; digit.combine(data); StringBuildersb=newStringBuilder(); for(Stringstring:out){ sb.append(string); sb.append("\n"); } returnsb.toString(); } privatedoubledoCalculate(doublex,doubley,intoperation){ switch(operation){ case0: returnx+y; case1: returnx-y; case2: returnx*y; case3: returnx/y; default: return0; } } privatestaticStringgetOperation(intoperation){ switch(operation){ case0: return"+"; case1: return"-"; case2: return"*"; case3: return"/"; default: return""; } } publicstaticvoidmain(String[]args){ System.out.println(newCal24().calc(newint[]{1,5,5,5})); } }
Combination.java
publicabstractclassCombination{ privatebooleanrepeat; privateinttotal=0; publicvoidcombine(intdata[]){ combine(data,data.length,false); } publicvoidcombine(intdata[],intcount){ combine(data,count,false); } publicvoidcombine(intdata[],intcount,booleanrepeat){ this.repeat=repeat; inttimes=data.length; intsize=(int)Math.pow(times,count); for(inti=0;i<size;i++){ int[]result=toArray(data,i,count); if(result!=null){ handle(result); total++; } } } privateint[]toArray(intdata[],inti,intcount){ int[]indices=newint[count]; inttimes=data.length; for(intj=0;j<count;j++){ inttemp=0; if(i>0){ temp=i%times; i=(i-temp)/times; } indices[j]=temp; } if(!repeat){ //removerepetition for(intx=0;x<count;x++){ for(inty=0;y<count;y++){ if(x!=y){ if(indices[x]==indices[y]) returnnull; } } } } int[]result=newint[count]; for(intx=0;x<count;x++){ intselected=data[indices[x]]; result[x]=selected; } returnresult; } publicintgetTotal(){ returntotal; } protectedabstractvoidhandle(int[]result); }
以上所述就是本文的全部内容了,希望大家能够喜欢。