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.
For something different, here's a parallelizable solution for Java 17.
/* * Maximize the upper-left quadrant of an even-length matrix, * using only vertical and horizontal reflections. * https://www.hackerrank.com/challenges/flipping-the-matrix * * Works by selecting the "foci" or reflectant axes of our * sub-matrix, and choosing the largest ones. * https://en.wikipedia.org/wiki/Focus_(geometry) * * 𝚯(N/P) runtime, for n cells and 'p' processors. * Parallelizable. */publicstaticintflippingMatrix(finalList<List<Integer>>matrix){finalintn=matrix.size()/2;returnpositionsOf(n).parallel().mapToInt(p->maxFocus(matrix,p)).sum();}/* Find largest of the reflectant foci, for this cell of the matrix. */privatestaticintmaxFocus(List<List<Integer>>matrix,Pointp){finalintm=matrix.size()-1;// let m = 2nList<Point>reflectant=List.of(p,// ULnewPoint(p.x,m-p.y),// URnewPoint(m-p.x,p.y),// LLnewPoint(m-p.x,m-p.y));// LRreturnreflectant.stream().mapToInt(f->elementAt(matrix,f)).max().orElseThrow();}/* Coordinates for all cells in a matrix of given 'length' in (row, col) format */staticStream<Point>positionsOf(intlength){returnrange(0,length).boxed().flatMap(r->range(0,length).boxed().map(c->newPoint(c,r)));}privatestaticintelementAt(List<List<Integer>>matrix,Pointp){returnmatrix.get(p.y).get(p.x);}
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 →
For something different, here's a parallelizable solution for Java 17.