Created
January 9, 2022 14:06
-
-
Save ackasaber/fa4881a6b30a8436274fea8cea09f512 to your computer and use it in GitHub Desktop.
Searching in the "roundly" sorted square 2^n x 2^n matrix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static java.nio.charset.StandardCharsets.US_ASCII; | |
import java.io.IOException; | |
import java.nio.file.Files; | |
import java.nio.file.Path; | |
import java.util.Scanner; | |
public class RoundSortSearch { | |
public static void main(String[] args) throws IOException { | |
var reader = Files.newBufferedReader(Path.of("matrix.txt"), US_ASCII); | |
var scanner = new Scanner(reader); | |
var a = readMatrix(scanner); | |
int x = scanner.nextInt(); | |
if (search(a, x)) { | |
System.out.println("Found"); | |
} else { | |
System.out.println("Not found"); | |
} | |
} | |
private static int[][] readMatrix(Scanner scanner) { | |
int n = scanner.nextInt(); | |
var mat = new int[n][n]; | |
for (int i = 0; i < n; ++i) { | |
for (int j = 0; j < n; ++j) { | |
mat[i][j] = scanner.nextInt(); | |
} | |
} | |
return mat; | |
} | |
private static boolean search(int[][] mat, int num) { | |
if (!square(mat)) { | |
throw new IllegalArgumentException("matrix is not square"); | |
} | |
int dim = mat.length; | |
int topRow = 0; | |
int leftColumn = 0; | |
while (dim > 1) { | |
if (dim % 2 != 0) { | |
throw new IllegalArgumentException("matrix dimension is not a power of two"); | |
} | |
int qdim = dim / 2; // quarter dimensions | |
// Order of checks is important. | |
if (num >= mat[topRow + qdim][leftColumn]) { | |
// has to be in the bottom left quarter | |
topRow += qdim; | |
} else if (num >= mat[topRow + qdim][leftColumn + qdim]) { | |
// has to be in the bottom right quarter | |
topRow += qdim; | |
leftColumn += qdim; | |
} else if (num >= mat[topRow][leftColumn + qdim]) { | |
// has to be in the top right quarter | |
leftColumn += qdim; | |
} | |
// If all the conditions above give false, it's in the top left quarter | |
// and topRow and leftColumn don't change. | |
dim = qdim; | |
} | |
return mat[topRow][leftColumn] == num; | |
} | |
private static boolean square(int[][] mat) { | |
int n = mat.length; | |
int i = 0; | |
while (i < n && mat[i].length == n) { | |
++i; | |
} | |
return i == n; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://stackoverflow.com/q/70640297/17695211