0

我正在尝试制作一个能够在数组中旋转给定次数然后返回第一个索引的函数。但我所拥有的真的很慢而且很笨重。看一看:

<?php

/**
 * Get the current userid
 * @return integer
 */
public function getCurrentUser( DateTime $startDate, DateInterval $interval, DateTime $endDate, $currentUser, $users, $rotating )
{

    if ($rotating == 0)
    {
        return $currentUser;
    }

    $usrArray = array();
    $dateRange = new DatePeriod( $startDate, $interval, $endDate);

    // Push userIds to an array
    foreach ($users as $user)
    {
        $usrArray[] = $user->id;
    }

    // Get the number of iterations from startDate to endDate
    $steps = iterator_count($dateRange);

    // Find the initial position of the orignal user
    $key = array_search($currentUser, $usrArray);

    // Set up the array so index 0 == currentUser
    $usr = $usrArray;
    array_splice($usr, $key);
    $slice = array_slice($usrArray, $key);
    $startList = array_merge($slice, $usr);

    // Start rotating the array
    for ($i=0; $i < $steps; $i++)
    {
        array_push($startList, array_shift($startList));
    }

    return $startList[0];
}

这是 PHP 脚本超时之前的 Xdebug 配置文件。 xdebug 配置文件

有没有更好的方法来确定在 x 次旋转后谁是索引 0?

4

1 回答 1

0

你的数组旋转不是那么慢,但可以改进..我相信这是你的旋转代码

你的代码

// Start rotating the array
for ($i=0; $i < $steps; $i++)
{
    array_push($startList, array_shift($startList));
}

return $startList[0];

您可以删除循环将其替换为 mod .. 您仍然可以获得相同结果的方式是解决方案:

解决方案

return $startList[ $steps % count($startList)];

你会得到同样的结果。

简单的基准测试

$steps = 10000; <----------------- 10,000 steps 

set_time_limit(0);
echo "<pre>";
$file = "log.txt";
// Using your current code
function m1($steps) {
    $startList = range("A", "H");
    for($i = 0; $i < $steps; $i ++) {
        array_push($startList, array_shift($startList));
    }
    return $startList[0];
}

// Using InfiniteIterator
function m2($steps) {
    $startList = range("A", "H");
    $n = 0;
    foreach ( new InfiniteIterator(new ArrayIterator($startList)) as $l ) {
        if ($n == $steps) {
            return $l;
            break;
        }
        $n ++;
    }
}

// Simple MOD solution
function m3($steps) {
    $startList = range("A", "H");
    return $startList[ $steps % count($startList)];
}

$result = array('m1' => 0,'m2' => 0,'m3' => 0);

for($i = 0; $i < 1; ++ $i) {
    foreach ( array_keys($result) as $key ) {
        $alpha = microtime(true);
        $key($file);
        $result[$key] += microtime(true) - $alpha;
    }
}

echo '<pre>';
echo "Single Run\n";
print_r($result);
var_dump(m1($steps),m2($steps),m2($steps));
echo '</pre>';

输出

Single Run
Array
(
    [m1] => 0.00012588500976562
    [m2] => 0.00021791458129883
    [m3] => 7.7962875366211E-5   <----------------- Mod solution fastest 
)
string 'A' (length=1)               |
string 'A' (length=1)               |+------------- They all return same result
string 'A' (length=1)               |
于 2012-11-24T09:16:41.127 回答