-1

I got array of points:

array(
    array('x' => ...,'y' => ...), 
    array('x' => ...,'y' => ...) 
    ...
    )

What is the best way to make those points one, that is in "avarge" position? Is pairing and then pairing and then pairing... a good algorithm?

I would give myself -1 for this question, as it seems to be really easy, but I am working on project for more than 20 hours now, and my brain went off.

Hmm... is it as simple as counting avarge x and avarge y?

4

3 回答 3

1

最好的解决方案是关闭计算机并睡几个小时。然后醒来休息并准备好进行新的编程会议。该解决方案基于您分配给该项目的那 20 个小时没有任何适当休息的假设。

虽然这不是您问题的直接答案,但它肯定会帮助您自己到达那里。不要低估小睡的力量。

于 2013-09-15T12:37:00.180 回答
1

看看我编写的这个函数,它循环遍历多维数组的所有元素,并在将所有元素加在一起后返回它们的平均值。

print_r(getAveragePoints(array(array('x' => 1,'y' => 3),array('x' => 2,'y' => 4))));

function getAveragePoints($arrays = array()) {
   if(!empty($arrays)) {
      $i=0;
      $x = 0;
      $y = 0;
      foreach($arrays as $array) {
        // this would take avg 
        $x += $array['x']; // x
        $y += $array['y'];   // y
        $i++;
      }
      $avgX = $x / $i; 
      $avgY = $y / $i;

      return array($avgX,$avgY);
   } else {
      return array(0,0);
   }
}
于 2013-09-15T12:37:27.483 回答
1

简单平均选项:

$pointArray = array(
    array('x' => 1,'y' => 2), 
    array('x' => 2,'y' => 5),
    array('x' => 3,'y' => 3) ,
    array('x' => 4,'y' => 6) ,
    array('x' => 4,'y' => 5) ,
);

$valueCount = count($pointArray);
$midpoint = array_map(
    function($value) use($valueCount) {
        return $value / $valueCount;
    },
    array_reduce(
        $pointArray,
        function($summary, $value) {
            return array(
                'x' => $summary['x'] += $value['x'],
                'y' => $summary['y'] += $value['y']
            );
        },
        array('x' => 0, 'y' => 0)
    )
);

var_dump($midpoint);
于 2013-09-15T12:39:26.507 回答