发布于 1970-01-01 08:00
  • 1 个回答
    • 余兴节目。我就直接粘答案了。技巧:

      1. 想象成一个线段,在上边随机选若干个点将其切断。统计每一段的长度相加起来就必然是正确的和值。
      2. 题目不禁止结果中出现0,所以选点的时候允许重复。
      3. 和值为负的时候,翻转成正的处理。
      <?php
      header("Content-Type: text/plain; ");
      
      $input = [1 => 12, 2 => 23];
      $input = [1 => 0, 2 => 0];
      define("TOTAL_SEGMENTS", 5);
      
      $input_sorted = $input; 
      asort($input_sorted);
      
      $segment_counts = [];
      $segment_counts[0] = mt_rand(1, TOTAL_SEGMENTS - 1);
      $segment_counts[1] = TOTAL_SEGMENTS - $segment_counts[0];
      
      $result = [];
      for ($i_slice = 0; $i_slice < 2; $i_slice++) {
          $input_record  = array_slice($input_sorted, -($i_slice + 1), 1, true);
          $record_key    = array_keys($input_record)[0];
          $target_sum    = array_values($input_record)[0];
          $segment_count = $segment_counts[$i_slice];
      
          if ($target_sum < 0) {
              $negative_sum = true;
              $target_sum = -$target_sum; 
          } else { 
              $negative_sum = false;
          }
      
          $positions = [0, $target_sum];
          while (count($positions) < ($segment_count + 1)) {
              $t = mt_rand(0, $target_sum);
              array_push($positions, $t); //不禁止出现0的时候无需判重(如果禁止出现0这个题就麻烦了)
          }
          sort($positions);
      
          for ($i = 0; $i < $segment_count; $i++) {
              $value = $positions[$i + 1] - $positions[$i];
              if ($negative_sum) { $value = -$value; }
              array_push($result, [$record_key, $value]);
          }
      }
      
      foreach ($result as $line) { printf("array(%d, %d), \n", $line[0], $line[1]); }
      
      2022-12-01 17:42 回答
    撰写答案
    今天,你开发时遇到什么问题呢?
    立即提问
    PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
    Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有