2009-07-10 76 views
0

我有一個數組:平滑數據陣列PHP

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

我想使之變成:

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

爲此I 1和3之間劃分的中間值這是最簡單的例子,其中分裂是50,50。我希望能夠將15個元素的數組降至6個元素。

任何想法?

其他例子 [10,15,20,25]簡化爲兩個元素:25(10 + 15),45(20 + 25) [10,10,10,11]簡化爲兩個元素:25(10 + 10 +(10/2)),26((10/2)+ 10 + 11)

+0

將15個元素減少到6個怎麼樣? – cletus 2009-07-10 16:37:39

+0

我假設這是作業嗎? – cletus 2009-07-10 16:38:10

+0

算法看起來如何? – Gumbo 2009-07-10 16:38:59

回答

1

彼得的解決方案做額外的測試後,我發現它並沒有讓我我所期待的,如果減少大小是奇數。這是我想出的功能。它還會擴大比所需大小更小的數據集。

<?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; 
     } 
    ?> 
0

你可以使用array_sum()求和,然後根據你想要的元素數量在你的結果數組中,除以該總和並填充你想要保留的每個元素與你的分割結果。

(這裏我假設你會使用第二個數組,但是如果你喜歡這種方式,你可以取消不需要的設置)。

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>