publicclassDiscreteDistribution{publicstaticvoidmain(String[] args){int m =Integer.parseInt(args[0]);int n = args.length -1;int[] a =newint[n +1];for(int i =1; i <= n; i++){
a[i]=Integer.parseInt(args[i]);}intSn=0;int[] s =newint[n +1];for(int i =1; i <= n; i++){
s[i]= s[i -1]+ a[i];Sn+= a[i];}while((m--)>0){int r =(int)(Math.random()*Sn);for(int i =1; i <= n; i++){if(r < s[i]){System.out.print(i +" ");break;}}}}}
ThueMorse.java (ThueMorse序列常见于图像设计和音乐作品)
publicclassThueMorse{publicstaticvoidmain(String[] args){int n =Integer.parseInt(args[0]);char[] seq =newchar[2* n];int index =0;
seq[index++]='0';for(int i =1; i < n; i <<=1){for(intJ= index, j =0; j <J; j++){
seq[index++]= seq[j]=='0'?'1':'0';}}// System.out.println(seq);for(int i =0; i < n; i++){for(int j =0; j < n; j++){if(seq[i]== seq[j]){System.out.print("+ ");}else{System.out.print("- ");}}System.out.println();}}}
Birthday.java (23人之中,有50%的概率两人生日在同一天)
publicclassBirthday{publicstaticvoidmain(String[] args){int n =Integer.parseInt(args[0]);int trials =Integer.parseInt(args[1]);int[] count =newint[n +2];boolean[] flag =newboolean[n];for(int t =0; t < trials; t++){for(int i =0; i < n; i++){
flag[i]=false;}int people =0;while(true){
people++;int date =(int)(Math.random()* n);if(flag[date]){break;}
flag[date]=true;}
count[people]++;}double fraction =0.0;for(int i =1, sum =0; fraction <0.5; i++){
sum += count[i];
fraction =1.0* sum / trials;System.out.println(i +"\t"+ count[i]+"\t"+ fraction);}}}
Minesweeper.java (扫雷小程序)
publicclassMinesweeper{publicstaticvoidmain(String[] args){int m =Integer.parseInt(args[0]);int n =Integer.parseInt(args[1]);int k =Integer.parseInt(args[2]);boolean[][] mines =newboolean[m][n];int total = m * n;int[] array =newint[total];for(int i =0; i < total; i++){
array[i]= i;}for(int i =0; i < k; i++){int r = i +(int)(Math.random()*(total - i));int t = array[i];
array[i]= array[r];
array[r]= t;}for(int i =0; i < k; i++){
mines[array[i]/ n][array[i]% n]=true;}for(int i =0; i < m; i++){for(int j =0; j < n; j++){if(mines[i][j]){System.out.print("* ");}else{int count =0;if(i -1>=0&& j -1>=0&& mines[i -1][j -1]) count++;if(i +1< m && j -1>=0&& mines[i +1][j -1]) count++;if(i -1>=0&& j +1< n && mines[i -1][j +1]) count++;if(i +1< m && j +1< n && mines[i +1][j +1]) count++;if(j +1< n && mines[i][j +1]) count++;if(j -1>=0&& mines[i][j -1]) count++;if(i +1< m && mines[i +1][j]) count++;if(i -1>=0&& mines[i -1][j]) count++;System.out.print(count +" ");}}System.out.println();}}}