【问题标题】:random logic to print numbers in following pattern随机逻辑以以下模式打印数字
【发布时间】:2014-08-07 12:08:50
【问题描述】:

目前,我有一个数组 r[1]r[12]

现在,我需要这样打印:

r[10]    r[11]    r[12]
r[7]     r[8]     r[9]
r[4]     r[5]     r[6]
r[1]     r[2]     r[3]

【问题讨论】:

    标签: php arrays if-statement for-loop


    【解决方案1】:
    for (int i = 0; i < 4; i++){
       for(int j = 0; j < 3; j++){
           print("%d", r[ 12 - (i * 3) + j]);
       }
    }
    

    如果您需要任何其他数字而不是概括解决方案

    for (int i = 0; i < count / interval; i++){
       for(int j = 0; j < interval; j++){
           print("%d", r[ count - (i * interval) + j]);
       }
    

    【讨论】:

      【解决方案2】:

      假设你有一个包含 n 个元素的数组,并且你想将它们显示在 3 个元素的行中,你可以这样进行(在 php 中):

      // this is your array, it starts with 1 and could end with n (but it must be divisible by 3)
      $array = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
      
      // check if the number of the elements is ok for the script
      if (count($array) % 3) {
          echo "The array must be divisible for the number of the element in a row!";
          exit;
      }
      
      // for each row, from 1 to number of the elements in array...
      for ($row = 1; $row <= count($array) / 3; $row++){
      
         // ... and for each column (with a max of 3 columns)
         for($column = 0; $column < 3; $column++){
      
             // print out the last element, less current row multipled by 3 plus the number of the column (which was started with 1).
             echo $array[count($array) - ($row * 3) + $column] . " ";
      
         }
      
         // another row is finished, move the cursor to the next line
         echo "<br />";
      
      }
      

      【讨论】:

      • 其实数组不限于12个,可以无限大
      • 对我来说是个好消息。我的老板现在不想要那个功能。无论如何感谢你们所有人
      • 我修改了,看看新脚本是否适合你
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-08
      • 1970-01-01
      • 2014-01-14
      相关资源
      最近更新 更多