[Amazon] Random Generator
Given random generator from 1 – 5 with equal possibility. Design Random generator 1 – 7
设计一个5×5矩阵, 然后把1-7放进去, 多的地方放0. 随机选i和j, 如果选0 就重新选, 如果没有 就返回.
import java.util.*; public class RandomGenerator { public int rnd5(){ return new Random().nextInt(5)+1; } public int rnd7() { int[][] m = new int[][]{ {1,2,3,4,5}, {6,7,1,2,3}, {4,5,6,7,1}, {2,3,4,5,6}, {7,0,0,0,0} }; int result = 0; while (result == 0) { int i = rnd5(); int j = rnd5(); result = m[i-1][j-1]; } return result; } public static void main(String[] args) { for (int i = 0; i < 100; i++) System.out.println(new RandomGenerator().rnd7()); } }
Leave A Comment