DEV Community

Discussion on: Daily Challenge #72 - Matrix Shift

Collapse
 
andre000 profile image
André Adriano

Javascript


function mxShift(matrix) {
    const flat = matrix.flat();
    const shiftedFlat = [
        ...matrix.flatMap((d,i) => i === 0 ? [flat.pop(), ...d] : d)
    ].slice(0, flat.length+1);

    const newMatrix = [];
    while (shiftedFlat.length > 0) {
        newMatrix.push(shiftedFlat.splice(0, matrix[0].length));
    }

    return newMatrix;
}

mxShift(a);
// 0: (4) ["h", "a", "b", "c"]
// 1: (4) ["d", "1", "2", "3"]
// 2: (4) ["4", "c", "o", "d"]
// 3: (4) ["e", "b", "l", "a"]

mxShift(b);
// 0: (4) ["g", "d", "u", "d"]
// 1: (4) ["e", "i", "m", "c"]
// 2: (4) ["o", "d", "i", "n"]

mxShift(c);
// 0: (2) ["k", "h"]
// 1: (2) ["i", "o"]