We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
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 libraryconsttranspose=(m)=>m[0].map((_,i)=>m.map((x)=>x[i]));consthmirror=(m)=>m.map((mr)=>mr.map((_,i,a)=>a[a.length-1-i]));constvmirror=(m)=>transpose(hmirror(transpose(m)));constflatten=(m)=>[].concat.apply([],m);// Eval and output the max sumconstevalMtx=(m,n)=>{// split the matrix into quadrantsconstfirst=m.map((r)=>r.slice(0,n)).slice(0,n);constsecond=m.map((r)=>r.slice(n)).slice(0,n);constthird=m.slice(n).map((r)=>r.slice(0,n));constlast=m.slice(n).map((r)=>r.slice(n));// mirror the quadrants to meet the first quadrant and flatten them allconstm_prime=[first,hmirror(second),vmirror(third),vmirror(hmirror(last))].map((s)=>flatten(s));// console.log(m_prime);returnm_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 programconstinputBuffer=input.split('\n').reverse()constq=parseInt(inputBuffer.pop());Array.from({length:q}).forEach((_)=>{constn=parseInt(inputBuffer.pop());constmtx=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.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Flipping the Matrix
You are viewing a single comment's thread. Return to all 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.
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.