• + 0 comments

    SPOILER ALLERT: this post contains a solution to the problem.

    Just to share a fun functional apporach in JS, and yes it could be even simplier with python.

    // Matrix library
    const transpose = (m) => m[0].map((_, i) => m.map((x) => x[i]));
    const hmirror = (m) => m.map((mr) => mr.map((_, i, a) => a[a.length - 1 - i]));
    const vmirror = (m) => transpose(hmirror(transpose(m)));
    const flatten = (m) => [].concat.apply([], m);
    // Eval and output the max sum
    const evalMtx = (m, n) => {
      // split the matrix into quadrants
      const first = m.map((r) => r.slice(0, n)).slice(0, n);
      const second = m.map((r) => r.slice(n)).slice(0, n);
      const third = m.slice(n).map((r) => r.slice(0, n));
      const last = m.slice(n).map((r) => r.slice(n));
      // mirror the quadrants to meet the first quadrant and flatten them all
      const m_prime = [first, hmirror(second), vmirror(third), vmirror(hmirror(last))]
        .map((s) => flatten(s));
      // console.log(m_prime);
      return m_prime[0].reduce((sum, _, i) => sum + 
        m_prime.map((q) => q[i]).reduce((max, v) => v > max ? v : max, 0)
        , 0);
    }
    
    // input parsing and main program
    const inputBuffer = input.split('\n').reverse()
    const q = parseInt(inputBuffer.pop());
    Array.from({ length: q }).forEach((_) => {
      const n = parseInt(inputBuffer.pop());
      const mtx = Array.from({ length: n + n })
        .map((_) => inputBuffer.pop().split(' ').map((i) => parseInt(i)));
      // console.log(mtx)
      console.log(evalMtx(mtx, n))
    })
    

    To understand this appoach you'd have to realize that each cell in the first quadrant can be 1 of the 4 cells from each quadrant in the fixed positions.

    Array.from({ length: n }) creates an array of n elements.

    Ragarding to the reduce functions, the outter one is a sum and the inner one is a max function.