Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created December 28, 2016 22:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/36c0e3efa281f0f4167c99828fb0830b to your computer and use it in GitHub Desktop.
Save jianminchen/36c0e3efa281f0f4167c99828fb0830b to your computer and use it in GitHub Desktop.
Hackerrank week code 27 - Hackonacci - matrix rotation - Java code - full score
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
private static int rotation90(int[][] m) {
int res = 0;
int n = m.length;
for (int i = 0; i < n / 2; i++) {
for (int j = i; j < n - i - 1; j++) {
//left to top
res += (m[i][j] + m[n - 1 - j][i]) % 2;
//bottom to left
res += (m[n - 1 - j][i] + m[n - 1 - i][n - 1 - j]) % 2;
//right to bottom
res += (m[n - 1 - i][n - 1 - j] + m[j][n - 1 - i]) % 2;
//top to right
res += (m[j][n - 1 - i] + m[i][j]) % 2;
}
}
return res;
}
private static int rotation180(int[][] m) {
int res = 0;
int n = m.length;
for (int i = 0; i < n / 2; i++) {
for (int j = i; j < n - i - 1; j++) {
// switch top and bottom values
res += ((m[i][j] + m[n - 1 - i][n - 1 - j]) % 2)*2;
// switch left and right values
res += ((m[n - 1 - j][i] + m[j][n - 1 - i]) % 2)*2;
}
}
return res;
}
private static int rotation270(int[][] m) {
int res = 0;
int n = m.length;
for (int i = 0; i < n / 2; i++) {
for (int j = i; j < n - i - 1; j++) {
//right to top
res += (m[i][j] + m[j][n - 1 - i]) % 2;
//bottom to right
res += (m[j][n - 1 - i] + m[n - 1 - i][n - 1 - j]) % 2;
//left to bottom
res += (m[n - 1 - i][n - 1 - j] + m[n - 1 - j][i]) % 2;
//top to left
res += (m[n - 1 - j][i] + m[i][j]) % 2;
}
}
return res;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int q = in.nextInt();
int[] r = {1, 1, 0, 1, 0, 0, 1};
int[][] m = new int[n][n];
for (int i = 0; i < n; i++) {
int im2 = ((i + 1) % 7) * ((i + 1) % 7);
for (int j = 0; j <= i; j++) {
int jm = (j + 1) % 7;
int v = im2 * jm * jm;
m[i][j] = r[v % 7];
m[j][i] = m[i][j];
}
}
int[] sol = {0, rotation90(m), rotation180(m), rotation270(m)};
for (int i = 0; i < q; i++) {
int a = (in.nextInt() % 360) / 90;
System.out.println(sol[a]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment