这是一个面向对象的解决方案,具有易于遵循的 reduce 方法和多个示例。
class CountByTwoArrayReducer {
public function __construct($array) {
$this->array = $array;
$this->size = count($array);
}
public function reduce() {
$this->initialize();
while($this->hasMultipleItems()) {
$this->next();
$this->removeCurrentItem();
$this->next();
}
return $this->finalItem();
}
protected function initialize() {
$this->current = 1;
$this->removed = array();
$this->remaining = $this->size;
}
protected function hasMultipleItems() {
return ($this->remaining > 1);
}
protected function next($start = null) {
$next = ($start === null) ? $this->current : $start;
do {
$next++;
} while(isset($this->removed[$next]));
if($next > $this->size)
$this->next(0);
else
$this->current = $next;
}
protected function removeCurrentItem() {
$this->removed[$this->current] = 1;
$this->remaining--;
}
protected function finalItem() {
return $this->array[$this->current - 1];
}
}
$examples = array(
array('A', 'B', 'C', 'D', 'E'),
range(1, 100),
range(1, 1000),
range(1, 10000)
);
foreach($examples as $example) {
$start = microtime(true);
$reducer = new CountByTwoArrayReducer($example);
$result = $reducer->reduce();
$time = microtime(true) - $start;
echo "Found {$result} in {$time} seconds.\n";
}