MCPcopy Index your code
hub / github.com/careercup/ctci / findElement

Method findElement

java/Chapter 11/Question11_6/QuestionB.java:19–51  ·  view source on GitHub ↗
(int[][] matrix, Coordinate origin, Coordinate dest, int x)

Source from the content-addressed store, hash-verified

17 }
18
19 public static Coordinate findElement(int[][] matrix, Coordinate origin, Coordinate dest, int x) {
20 if (!origin.inbounds(matrix) || !dest.inbounds(matrix)) {
21 return null;
22 }
23 if (matrix[origin.row][origin.column] == x) {
24 return origin;
25 } else if (!origin.isBefore(dest)) {
26 return null;
27 }
28
29 /* Set start to start of diagonal and end to the end of the diagonal. Since
30 * the grid may not be square, the end of the diagonal may not equal dest.
31 */
32 Coordinate start = (Coordinate) origin.clone();
33 int diagDist = Math.min(dest.row - origin.row, dest.column - origin.column);
34 Coordinate end = new Coordinate(start.row + diagDist, start.column + diagDist);
35 Coordinate p = new Coordinate(0, 0);
36
37 /* Do binary search on the diagonal, looking for the first element greater than x */
38 while (start.isBefore(end)) {
39 p.setToAverage(start, end);
40 if (x > matrix[p.row][p.column]) {
41 start.row = p.row + 1;
42 start.column = p.column + 1;
43 } else {
44 end.row = p.row - 1;
45 end.column = p.column - 1;
46 }
47 }
48
49 /* Split the grid into quadrants. Search the bottom left and the top right. */
50 return partitionAndSearch(matrix, origin, dest, start, x);
51 }
52
53 public static Coordinate findElement(int[][] matrix, int x) {
54 Coordinate origin = new Coordinate(0, 0);

Callers 2

partitionAndSearchMethod · 0.95
mainMethod · 0.95

Calls 6

isBeforeMethod · 0.95
setToAverageMethod · 0.95
partitionAndSearchMethod · 0.95
inboundsMethod · 0.80
cloneMethod · 0.45
minMethod · 0.45

Tested by

no test coverage detected