Zig-zag scan an N x N array

前端 未结 8 1378
暗喜
暗喜 2021-01-30 08:40

I have a simple array. The array length always has a square root of an integer. So 16, 25, 36 etc.

$array = array(\'1\', \'2\', \'3\', \'4\' ... \'25\');
         


        
8条回答
  •  盖世英雄少女心
    2021-01-30 09:18

    I wrote it in C# so didn't compile/parse it in PHP but this logic should work:

    List newList = new List();
    double i = 1;
    
    double root = Math.Sqrt(oldList.Count);
    bool direction = true;
    
    while (newList.Count < oldList.Count)
    {
        newList.Add(oldList[(int)i - 1]);
        if (direction)
        {
            if (i + root > root * root)
            {
                i++;
                direction = false;
            }
            else if (i % root == 1)
            {
                i += 5;
                direction = false;
            }
            else
            {
                i += root - 1;
            }
        }
        else
        {
            if (i - root <= 0)
            {
                direction = true;
                if (i % root == 0)
                {
                    i += root;
                }
                else
                {
                    i++;
                }
                direction = true;
            }
            else if (i % root == 0)
            {
                direction = true;
                i += root;
            }
            else
            {
                i += 1 - root;
            }
        }
    }
    

    the PHP version would look something like this:

    $oldList = ...
    $newList = [];
    $i = 1;
    
    $root = sqrt(Count($oldList);
    $direction = true;
    
    while (count($newList) < count($oldList)
    {
        $newList[] = $oldList[$i - 1];
        if ($direction)
        {
            if ($i + $root > $root * $root)
            {
                $i++;
                $direction = false;
            }
            else if ($i % $root == 1)
            {
                $i += 5;
                $direction = false;
            }
            else
            {
                $i += $root - 1;
            }
        }
        else
        {
            if ($i - $root <= 0)
            {
                $direction = true;
                if ($i % $root == 0)
                {
                    $i += $root;
                }
                else
                {
                    i++;
                }
                direction = true;
            }
            else if ($i % $root == 0)
            {
                $direction = true;
                $i += $root;
            }
            else
            {
                $i += 1 - $root;
            }
        }
    }
    

提交回复
热议问题