最近偶有机缘接触到八卦五行,有个校友在做紫微斗数,于是乎就想做个计算生辰八字五行算法的C#代码,说到底占卜命理这种理论笔者觉得最终还是基于统计学的,这个可能有很多学派很多师傅有不同的理论,不过算生辰八字还算是通用的,不过不能乱算,笔者最不喜欢的就是搞个不靠谱的误人子弟,于是乎研究了一圈,发现有篇潘爱民写的还算比较可靠,但是是基于c语言的,于是笔者在这基础上写了个C#版的,本着源于网络回馈网络的精神下面是C#改写的代码,望大家交流,有其他占卜相关的算法也可以一起研究,其实这和大数据还真的能结合一起。
public class BaziAlgorithm
{
//==================================
//以下为http://blog.csdn.net/panaimin/article/details/8544489
//计算五行
const string TianGan = "甲乙丙丁戊己庚辛壬癸";
const string DiZhi = "子丑寅卯辰巳午未申酉戌亥";
public bool CheckBazi(string bazi)
{
int baziLen;
int i, j;
baziLen = bazi.Length;
if (baziLen != 6 && baziLen != 8) return false;
for (i = 0; i < baziLen;)
{
char ch = bazi[i];
for (j = 0; j < 10; j++)
if (ch == TianGan[j]) break;
if (j >= 10) return false;
i++;
ch = bazi[i];
for (j = 0; j < 12; j++)
if (ch == DiZhi[j]) break;
if (j >= 12) return false;
i++;
}
return true;
}
/*
根据出生日子的天干,通过下表来查算时辰干支:
时辰干支查算表
时间时辰 五行纪日干支
甲己 乙庚 丙辛 丁壬 戊癸
23-01 子/水 甲子 丙子 戊子 庚子 壬子
01-03 丑/土 乙丑 丁丑 己丑 辛丑 癸丑
03-05 寅/木 丙寅 戊寅 庚寅 壬寅 甲寅
05-07 卯/木 丁卯 己卯 辛卯 癸卯 乙卯
07-09 辰/土 戊辰 庚辰 壬辰 甲辰 丙辰
09-11 巳/火 己巳 辛巳 癸巳 己巳 丁巳
11-13 午/火 庚午 壬午 甲午 丙午 戊午
13-15 未/土 辛未 癸未 乙未 丁未 己未
15-17 申/金 壬申 甲申 丙申 戊申 庚申
17-19 酉/金 癸酉 乙酉 丁酉 己酉 辛酉
19-21 戊/土 甲戌 丙戌 戊戌 庚戌 壬戌
21-23 亥/水 乙亥 丁亥 己亥 辛亥 癸亥
*/
string[][] cTimeGanZhi_Table = new string[12][]
{
new string[] {"甲子","丙子","戊子","庚子","壬子"},
new string[] {"乙丑","丁丑","己丑","辛丑","癸丑"},
new string[] {"丙寅","戊寅","庚寅","壬寅","甲寅"},
new string[] {"丁卯","己卯","辛卯","癸卯","乙卯"},
new string[] {"戊辰","庚辰","壬辰","甲辰","丙辰"},
new string[] {"己巳","辛巳","癸巳","己巳","丁巳"},
new string[] {"庚午","壬午","甲午","丙午","戊午"},
new string[] {"辛未","癸未","乙未","丁未","己未"},
new string[] {"壬申","甲申","丙申","戊申","庚申"},
new string[] {"癸酉","乙酉","丁酉","己酉","辛酉"},
new string[] {"甲戌","丙戌","戊戌","庚戌","壬戌"},
new string[] {"乙亥","丁亥","己亥","辛亥","癸亥"}
};
static string sBuf; // 用作八字结果缓冲区
// 根据出生年月日的干支计算时辰干支
// 输入参数:bazi,年月日的干支,即八字中的前六个字
// 输入参数:hour,出生时间的小时数,-1~22
// 输出结果:八字字符串,Unicode编码
public string ComputeTimeGan(string bazi, int hour)
{
if (hour > 22) hour -= 24;
char dayGan = bazi[4];
int indexX, indexY;
int i;
for (i = 0; i