Matrix arrangement issues in php

前端 未结 6 1137
闹比i
闹比i 2021-02-20 13:07

I would like to know some solutions to such a problem.

It is given a number lets say 16 and you have to arrange a matrix this way

1  2  3  4
12 13 14 5
         


        
6条回答
  •  渐次进展
    2021-02-20 13:52

    in java

    
       public static void main(final String args[]) {
          int numbercnt = 16;
          int dim = (int) Math.sqrt(numbercnt);
          int[][] numbers = new int[dim][dim];
          ArrayList < Integer > ref = new ArrayList < Integer >();
          for (int i = 0; i < numbercnt; i++) {
             ref.add(i);
          }
          for (int i = 0; i < numbers.length; i++) {
             for (int j = 0; j < numbers[i].length; j++) {
                int pos = (int) (Math.random() * ref.size());
                numbers[j][i] = ref.get(pos);
                ref.remove(pos);
             }
          }
          for (int i = 0; i < numbers.length; i++) {
             for (int j = 0; j < numbers[i].length; j++) {
                System.out.print(numbers[j][i] + " ");
             }
             System.out.println();
          }
       }
    

提交回复
热议问题