-1

私は配列を持っています:

Array
(
    [1] => 25
    [2] => 50
    [3] => 25
)

私はそれを作りたい:

Array
(
    [1] => 50
    [2] => 50
)

これを行うために、中間値を 1 と 3 の間で分割します。これは、分割が 50,50 である最も単純な例です。15 要素の配列を 6 要素まで減らしたいと考えています。

何か案は?

追加の例 [10, 15, 20, 25] 2 つの要素に縮小: 25(10 + 15),45(20 + 25) [10, 10, 10, 10, 11] 2 つの要素に縮小: 25(10 + 10 + (10/2)),26((10/2) + 10 + 11)

4

3 に答える 3

2

ピーターのソリューションで追加のテストを行った後、サイズの縮小が奇数の場合、期待した結果が得られないことに気付きました。これが私が思いついた機能です。また、要求されたサイズよりも小さいデータ セットを膨張させます。

   <?php
        function reduceto($data,$r) {
            $c = count($data);

            // just enough data
            if ($c == $r) return $data;

            // not enough data
            if ($r > $c) {
                $x = ceil($r/$c);
                $temp = array();
                foreach ($data as $v) for($i = 0; $i < $x; $i++) $temp[] = $v;
                $data = $temp;
                $c = count($data);
            }

            // more data then needed
            if ($c > $r) {
                $temp = array();
                foreach ($data as $v) for($i = 0; $i < $r; $i++) $temp[] = $v;
                $data = array_map('array_sum',array_chunk($temp,$c));
            }
            foreach ($data as $k => $v) $data[$k] = $v / $r;
            return $data;
        }
    ?>
于 2009-07-10T21:40:24.307 に答える
0

これがあなたの問題への私の刺し傷です

<pre>
<?php

class Thingy
{
  protected $store;
  protected $universe;

  public function __construct( array $data )
  {
    $this->store = $data;
    $this->universe = array_sum( $data );
  }

  public function reduceTo( $size )
  {
    //  Guard condition incase reduction size is too big
    $storeSize = count( $this->store );
    if ( $size >= $storeSize )
    {
      return $this->store;
    }

    //  Odd number of elements must be handled differently
    if ( $storeSize & 1 )
    {
      $chunked = array_chunk( $this->store, ceil( $storeSize / 2 ) );
      $middleValue = array_pop( $chunked[0] );

      $chunked = array_chunk( array_merge( $chunked[0], $chunked[1] ), floor( $storeSize / $size ) );

      //  Distribute odd-man-out amonst other values
      foreach ( $chunked as &$chunk )
      {
        $chunk[] = $middleValue / $size;
      }
    } else {
      $chunked = array_chunk( $this->store, floor( $storeSize / $size ) );
    }

    return array_map( 'array_sum', $chunked );
  }

}

$tests = array(
    array( 2, array( 25, 50, 25 ) )
  , array( 2, array( 10, 15, 20, 25 ) )
  , array( 2, array( 10, 10, 10, 10, 11 ) )
  , array( 6, array_fill( 0, 15, 1 ) )
);

foreach( $tests as $test )
{
  $t = new Thingy( $test[1] );
  print_r( $t->reduceTo( $test[0] ) );
}

?>
</pre>
于 2009-07-10T18:18:26.447 に答える
0

array_sum() を使用して値を合計し、結果の配列に含める要素の数に応じて、その合計を除算し、保持するすべての要素を除算の結果で埋めることができます。

(ここでは、2 番目の配列を使用することを前提としていますが、必要に応じて不要な配列を設定解除することもできます)。

于 2009-07-10T16:51:24.530 に答える