Skip to content

Instantly share code, notes, and snippets.

@alcedo
Last active February 8, 2018 23:38
Show Gist options
  • Save alcedo/6334323 to your computer and use it in GitHub Desktop.
Save alcedo/6334323 to your computer and use it in GitHub Desktop.
Java function snippets, Matrix, LCM, GCD
// used to print format print. %n is new line. dont use \n
// http://docs.oracle.com/javase/tutorial/java/data/numberformat.html
System.out.format("The value of sum is: %.2f%n", 4650/100);
//Rotates a matrix right
public static void rotateRight(char[][] matrix) {
int cols = matrix[0].length;
int rows = matrix.length;
char[][] tmp = new char[matrix.length][matrix.length];
// rotate
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++) {
tmp[j][rows-1-i] = matrix[i][j];
}
}
// copy back
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++) {
matrix[i][j] = tmp[i][j];
}
}
}
//prints n by n matrix
public static void printMatrix(int[][] matrix) {
int cols = matrix[0].length;
int rows = matrix.length;
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println("");
}
}
// GCD for arrays
public static int gcd(int[] input) {
int result = input[0];
for(int i = 1; i < input.length; i++) result = gcd(result, input[i]);
return result;
}
//FAST GCD due to bitwise manipulations
public static int gcd(int a, int b)
{
while(b>0) b ^= a ^= b ^= a %= b;
return a;
}
// Normal euclidean GCD
public static int GCD(int a, int b) {
if (b==0) return a;
return GCD(b,a%b);
}
//GCD LONG
public static long gcd(long[] input) {
long result = input[0];
for(int i = 1; i < input.length; i++) result = GCD(result, input[i]);
return result;
}
public static long GCD(long a, long b) {
if (b==0) return a;
return GCD(b,a%b);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment