彩票問題(lottery drawing)

  1. import java.util.Arrays;
  2. import java.util.Scanner;


  3. public class LotteryDrawing {

  4.     /**
  5.      * @param args
  6.      */
  7.     public static void main(String[] args) {
  8.         // TODO Auto-generated method stub
  9.         Scanner in = new Scanner(System.in);
  10.         System.out.println("How many numbers do you need to draw?");
  11.         int k = in.nextInt();
  12.         
  13.         System.out.println("What is the heigh number you can draw?");
  14.         int n = in.nextInt();
  15.         
  16.         //fill an array with numbers 1,2,3...n
  17.         int[] numbers = new int[n];
  18.         for (int i = 0; i < numbers.length; i++) {
  19.             numbers[i] = i + 1;
  20.         }
  21.         
  22.         //draw k numbers and put them into a second array
  23.         int[] result = new int[k];
  24.         for (int i = 0; i < result.length; i++) {
  25.             //make a random index between 0 and n-1
  26.             int r = (int)(Math.random() * n);
  27.             
  28.             //pick the element at the random location
  29.             result[i] = numbers[r];
  30.             
  31.             //move the last element into random location,很巧妙的替換方法,把最後一個數替換到已選出數的位置,數組上限  再減一
  32.             numbers[r] = numbers[n-1];
  33.             n--;
  34.         }
  35.         
  36.         // print the sorted array,數組排序簡單排序方法,順序排序
  37.         Arrays.sort(result);
  38.         System.out.println("Bet the following combination. It'll make you rich!");
  39.         for(int r : result) {
  40.             System.out.println(r);
  41.         }
  42.     }

  43. }
摘自core java第七版

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章