1staticfinalintN=8;2Button[][] bt =newButton[N][N];34@Override5publicvoidstart(Stage stage)throwsException{6for(int i =0; i < bt.length; i++){7for(int j =0; j < bt.length; j++){8 bt[i][j]=newButton(Integer.toString(i)+9Integer.toString(j));10}11}1213// 0~63までのランダムなインデックスを作る14int[] indices =randomIndices(N*N);1516GridPane gp =newGridPane();1718// 0~63までの一次元のインデックスを二次元のインデックスに読み替えてGrid上へ配置19int index =0;20for(int i =0; i < bt.length; i++){21for(int j =0; j < bt[i].length; j++){22int x = index %N;23int y = index /N;24 index++;25 gp.add(bt[x][y], i, j);26// あるいはこうでもよい27// gp.add(bt[i][j], x, y);28}29}30...31}3233// 0~n-1までの整数をランダムな順番で含む配列を作るメソッド34staticint[]randomIndices(int n){35// 0~n-1の値を持つ配列を作る36int[] indices =newint[n];37for(int i =0; i < n; i++){38 indices[i]= i;39}40// この配列をランダムに並べ替える41Random random =newRandom();42for(int i =0; i < n -1; i++){43int j = i + random.nextInt(n - i);44if(i != j){45int tmp = indices[i];46 indices[i]= indices[j];47 indices[j]= tmp;48}49}50return indices;51}5253// java.util.Collections#shuffleの方が簡単だが54// 最初はまず上のアルゴリズムを学ぶべきだと思う。55// 両方知った上で以下を使うのがよいのではないでしょうか・・・56staticList<Integer>anotherRandomIndices(int n){57List<Integer> list =IntStream.range(0, n).boxed().collect(Collectors.toList());58Collections.shuffle(list);59return list.stream().mapToInt(i->i).toArray();60}
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。