How do you rotate a two dimensional array?

后端 未结 30 3140
耶瑟儿~
耶瑟儿~ 2020-11-22 02:43

Inspired by Raymond Chen\'s post, say you have a 4x4 two dimensional array, write a function that rotates it 90 degrees. Raymond links to a solution in pseudo code, but I\'d

30条回答
  •  青春惊慌失措
    2020-11-22 03:21

    PHP:

    0)
    {
        $b[count($a[0])-1][] = array_shift($a[0]);
        if (count($a[0])==0)
        {
             array_shift($a);
        }
    }
    

    From PHP5.6, Array transposition can be performed with a sleak array_map() call. In other words, columns are converted to rows.

    Code: (Demo)

    $array = [
        [1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 0, 1, 2],
        [3, 4, 5, 6]
    ];
    $transposed = array_map(null, ...$array);
    

    $transposed:

    [
        [1, 5, 9, 3],
        [2, 6, 0, 4],
        [3, 7, 1, 5],
        [4, 8, 2, 6]
    ]
    

提交回复
热议问题