Thursday, 1 November 2018

Incomprehensible condition and incorrect operation of the function

There is the following code (demo here), the function (with recursion) go the matrix in a spiral collecting values:

function spiralmatrix($arr)
{
    return  $arr 
            ? array_merge(
                    array_shift($arr), 
                    spiralmatrix(array_reverse(transpose($arr)))
            )
            : $arr;
}

function transpose($arr)
{ 
    return $arr
            ? count($arr) == 1
                ? array_chunk($arr[0], 1) 
                : array_map(null, ...$arr)
            : $arr;
}

I understand that using multiple ternary expressions contributes to unreadable code. But there is more predominant sporting interest for code-Golf.

And so, to the question, is it possible to somehow change the condition to cut more characters? Can use any methods.

I would also like to ask, it is strange that the following works fine (demo):

function transpose($arr)
{ 
    return $arr
            ? count($arr) == 1
                ? array_chunk($arr[0], 1) 
                : array_map(null, ...$arr)
            : $arr;
}

And the expression works a little wrong (demo):

function transpose($arr)
{ 
    return count($arr) > 1 ? array_map(null, ...$arr) : $arr; 
}

Although, in separate tests (not in this function spiralmatrix) they show the same results what can is this problem? (demo comparisons). Grateful for any help..



from Incomprehensible condition and incorrect operation of the function

No comments:

Post a Comment