想实现天干地支与数值的互换算法,在网上找到了一些相关信息,于是开工实现了。
目标:
已知 甲子 求得结果 1
已知 丙辰 求得结果 53
已知 55 求得结果 戊午
对应码表:
1.甲子 2.乙丑 3.丙寅 4.丁卯 5.戊辰 6.己巳 7.庚午 8.辛未
9.壬申 10.癸酉 11.甲戌 12.乙亥 13.丙子 14.丁丑 15.戊寅 16.己卯
17.庚辰 18.辛巳 19.壬午 20.癸未 21.甲申 22.乙酉 23.丙戌 24.丁亥
25.戊子 26.己丑 27.庚寅 28.辛卯 29.壬辰 30.癸巳 31.甲午 32.乙未
33.丙申 34.丁酉 35.戊戌 36.己亥 37.庚子 38.辛丑 39.壬寅 40.癸卯
41.甲辰 42.乙巳 43.丙午 44.丁未 45.戊申 46.己酉 47.庚戌 48.辛亥
49.壬子 50.癸丑 51.甲寅 52.乙卯 53.丙辰 54.丁巳 55.戊午 56.己未
57.庚申 58.辛酉 59.壬戌 60.癸亥
代码实现如下:
/**
* <url>http://en.wikipedia.org/wiki/Sexagenary_cycle</url>
*/
public class Sexagenary {
/**
* 输入干支,输出对应数值。
*/
public static int getValue(Stems stems, Branches branches) {
int s = stems.ordinal() + 1;
int b = branches.ordinal() + 1;
int value = (6 * s - 5 * b + 60) % 60;
return value;
}
/**
* 输入数值,输出对应干支(String)
*/
public static String getStemsBranches(int num) {
if (num < 1 || num > 60) {
throw new IllegalArgumentException("Error input, num:" + num);
}
int s = ((num % 10) == 0) ? 10 : (num % 10);
int b = ((num % 12) == 0) ? 12 : (num % 12);
Stems stems = Stems.values()[s - 1];
Branches branches = Branches.values()[b - 1];
return "" + stems + branches;
}
public static void main(String[] args) {
System.out.println(Sexagenary.getStemsBranches(1)); // 甲子
System.out.println(Sexagenary.getStemsBranches(53)); // 丙辰
System.out.println("" + Sexagenary.getValue(Stems.甲, Branches.子)); // 1
System.out.println("" + Sexagenary.getValue(Stems.丙, Branches.辰)); // 53
System.out.println("" + Sexagenary.getValue(Stems.戊, Branches.午)); // 55
}
}
enum Stems {
甲, 乙, 丙, 丁, 戊, 己, 庚, 辛, 壬, 癸;
}
enum Branches {
子, 丑, 寅, 卯, 辰, 巳, 午, 未, 申, 酉, 戌, 亥;
}
此外使用了 中文 作为枚举类型名(Java 支持 Unicode 的),并借助了枚举来替代数组的存储结构,简化了相关操作。