----网址导航插件----
链接地址:(用于链接型文章)
获取标题/ico
http://www.360doc.com/showweb/0/0/1148232929.aspx
访问次数: 0
### **专属前端输入格式化模板(优化版)**
为了进一步提升用户体验并确保信息的完整性和准确性,以下是优化后的前端输入格式化模板。该模板结合了用户友好的界面设计、动态提示功能以及高级功能模块,旨在为用户提供更便捷、更智能的健康管理服务。
---
#### **1. 用户信息输入模块(优化版)**
**功能增强**:
- **自动农历转换**: 支持公历和农历日期的自动转换,并提供实时验证。
- **时辰选择优化**: 提供时辰选择的下拉菜单,并显示每个时辰的五行属性和宜忌事项。
- **出生地点智能提示**: 根据用户输入的出生地点,提供相关建议和提示。
**示例界面**:
```html
```
---
#### **2. 查询需求输入模块(优化版)**
**功能增强**:
- **需求关联推荐**: 根据用户选择的主要需求,自动推荐相关的辅助需求。
- **动态提示信息**: 提供动态提示,帮助用户更好地理解每个需求的含义和作用。
**示例界面**:
```html
辅助需求:
根据您选择的主要需求,我们推荐以下辅助需求:
- 如果您选择了“黄历查询”,我们建议您同时选择“时辰建议”以获得更全面的指导。
- 如果您选择了“健康管理”,我们建议您选择“五行分析”以深入了解您的健康状况。
```
---
#### **3. 应用方法选择模块(优化版)**
**功能增强**:
- **方法关联推荐**: 根据用户选择的应用方法,自动推荐相关的其他方法。
- **方法说明与示例**: 提供每个方法的详细说明和示例,帮助用户更好地理解其应用。
**示例界面**:
```html
应用方法:
根据您选择的应用方法,我们推荐以下方法:
- 如果您选择了“数字八卦起卦法”,我们建议您同时选择“梅花易数八卦起卦”以获得更全面的分析。
- 如果您选择了“时间八卦起卦法”,我们建议您选择“紫薇斗数算法”以深入了解您的命盘信息。
```
---
#### **4. 输出结果展示模块(优化版)**
**功能增强**:
- **多维度结果展示**: 将不同方法的结果进行整合,并以多维度的方式进行展示。
- **可视化图表增强**: 使用更丰富的图表类型和交互功能,例如动态图表、图表联动等。
- **个性化建议优化**: 根据用户的健康数据和需求,提供更精准、更个性化的建议。
**示例界面**:
```html
综合分析结果:
数字八卦起卦法:
本卦为坤为地卦,象征柔顺、承载。
变卦为坤为地卦,动爻为第四爻,卦象不变。
启示:需以柔顺的态度应对当前局势,保持稳定和耐心。
时间八卦起卦法:
本卦为雷天大壮卦,象征积极进取、充满活力。
变卦为泽天夬卦,象征果断决策、排除障碍。
启示:当前宜积极进取,果断行动,但需注意避免过于急躁。
个性化建议:
饮食建议: 根据您的五行分析结果,建议多食用健脾益胃的食物,如山药、莲子、红枣、薏米、小米等。
运动建议: 结合您的健康数据和目标,建议选择适度的有氧运动,例如散步、慢跑、太极拳、瑜伽等。
健康提示: 您当前需要注意脾胃健康,避免过度劳累,建议定期进行健康检查。
可视化图表:
五行能量分布图: 显示您当前五行能量的分布情况,帮助您了解自身的五行平衡状态。
健康趋势分析图: 分析您的健康数据趋势,识别潜在的健康风险和趋势。
```
**JavaScript代码示例**:
```javascript
const ctx1 = document.getElementById('五行能量分布图').getContext('2d');
const 五行能量分布图 = new Chart(ctx1, {
type: 'bar',
data: {
labels: ['木', '火', '土', '金', '水'],
datasets: [{
label: '能量值',
data: [7.2, 6.5, 5.8, 8.0, 6.2],
backgroundColor: ['rgba(75, 192, 192, 0.6)', 'rgba(255, 99, 132, 0.6)', 'rgba(255, 206, 86, 0.6)', 'rgba(54, 162, 235, 0.6)', 'rgba(153, 102, 255, 0.6)'],
borderColor: ['rgba(75, 192, 192, 1)', 'rgba(255, 99, 132, 1)', 'rgba(255, 206, 86, 1)', 'rgba(54, 162, 235, 1)', 'rgba(153, 102, 255, 1)'],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
const ctx2 = document.getElementById('健康趋势分析图').getContext('2d');
const 健康趋势分析图 = new Chart(ctx2, {
type: 'line',
data: {
labels: ['Week 1', 'Week 2', 'Week 3', 'Week 4', 'Week 5'],
datasets: [{
label: '健康指数',
data: [75, 78, 80, 82, 85],
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 2,
fill: false
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
```
---
#### **5. 用户隐私与数据安全(优化版)**
**功能增强**:
- **数据加密增强**: 采用更高级的加密算法,例如AES-256,确保数据的安全性。
- **访问控制细化**: 根据用户角色和权限级别,细化访问控制策略。
- **隐私政策透明化**: 提供详细的隐私政策说明,并提供用户友好的界面来管理数据隐私设置。
**示例界面**:
```html
```
---
### **总结**
通过以上优化后的前端输入格式化模板,用户可以更便捷、更直观地输入信息,系统可以更高效地处理和分析数据,最终提供更精准、更个性化的健康管理建议。该模板旨在提升用户体验,确保信息的完整性和准确性,并为用户提供更丰富的互动和可视化功能。
---
### **未来展望**
- **人工智能与中医理论的深度融合**: 进一步深化AI算法与中医理论的结合,开发更智能、更精准的健康管理工具。
- **多学科交叉与跨领域合作**: 加强与生物医学,#lang racket
;; Function to get the trigram based on a number
(define (get-gua-number number)
(define gua-map (hash 1 "乾" 2 "兑" 3 "离" 4 "震" 5 "巽" 6 "坎" 7 "艮" 0 "坤"))
(hash-ref gua-map number ""))
;; Function to perform the Mei Hua Yishu calculation
(define (meihua-yishu year month day hour)
(define earth-branches '(0 1 2 3 4 5 6 7 8 9 10 11))
(define branch-names '("子" "丑" "寅" "卯" "辰" "巳" "午" "未" "申" "酉" "戌" "亥"))
(define last-char (string->symbol (substring year (- (string-length year) 1))))
(define year-branch (index-of branch-names last-char))
(define upper-trigram-sum (+ year-branch month day))
(define upper-trigram-remainder (modulo upper-trigram-sum 8))
(define lower-trigram-sum (+ upper-trigram-sum hour))
(define lower-trigram-remainder (modulo lower-trigram-sum 8))
(define moving-line-remainder (modulo lower-trigram-sum 6))
(define original-hexagram (string-append (get-gua-number upper-trigram-remainder) (get-gua-number lower-trigram-remainder)))
(define changed-hexagram (get-changed-hexagram original-hexagram moving-line-remainder))
(values original-hexagram changed-hexagram moving-line-remainder))
;; Function to determine the changed hexagram
(define (get-changed-hexagram hexagram moving-line)
(define hexagrams '(("乾" . "兌") ("兑" . "離") ("離" . "震") ("震" . "巽")
("巽" . "坎") ("坎" . "艮") ("艮" . "坤") ("坤" . "乾")))
(define gua1 (substring hexagram 0 2))
(define gua2 (substring hexagram 2 4))
(define (find-new-gua gua)
(for/or ([pair hexagrams])
(when (equal? (car pair) gua)
(cdr pair))))
(cond
[(= moving-line 1) (string-append (find-new-gua gua1) gua2)]
[(= moving-line 2) (string-append gua1 (find-new-gua gua2))]
[else (string-append gua1 gua2)]))
;; Function to perform the Wu Xing analysis
(define (wuxing-analysis birth-year birth-month birth-day birth-hour)
(define year-stems '("甲" "乙" "丙" "丁" "戊" "己" "庚" "辛" "壬" "癸"))
(define year-branches '("子" "丑" "寅" "卯" "辰" "巳" "午" "未" "申" "酉" "戌" "亥"))
(define year-index (modulo (- birth-year 4) 60))
(define year-stem (list-ref year-stems (quotient year-index 12)))
(define year-branch (list-ref year-branches (modulo year-index 12)))
(define month-offsets '(0 0 11 12 1 2 3 4 5 6 7 8 9 10))
(define month-index (+ (list-ref month-offsets birth-month) (quotient year-index 12)))
(define month-stem (list-ref year-stems (modulo month-index 10)))
(define month-branch (list-ref year-branches (modulo (+ year-index (list-ref month-offsets birth-month)) 12)))
(define base-date 693901)
(define days-in-month '(0 31 28 31 30 31 30 31 31 30 31 30 31))
(for ([y (in-range 1900 birth-year)])
(set! base-date (+ base-date (if (or (and (= (modulo y 4) 0) (not (= (modulo y 100) 0))) (= (modulo y 400) 0)) 366 365))))
(for ([m (in-range 1 birth-month)])
(set! base-date (+ base-date (list-ref days-in-month m)))
(when (and (= m 2) (or (and (= (modulo birth-year 4) 0) (not (= (modulo birth-year 100) 0))) (= (modulo birth-year 400) 0)))
(set! base-date (+ base-date 1))))
(set! base-date (+ base-date birth-day))
(define day-index (modulo (+ base-date 1) 60))
(define day-stem (list-ref year-stems (quotient day-index 12)))
(define day-branch (list-ref year-branches (modulo day-index 12)))
(define time-branches '("子" "丑" "寅" "卯" "辰" "巳" "午" "未" "申" "酉" "戌" "亥"))
(define time-branch-index (quotient (- birth-hour 1) 2))
(define time-branch (list-ref time-branches time-branch-index))
(define ba-zi (format "~a~a ~a~a ~a~a ~a" year-stem year-branch month-stem month-branch day-stem day-branch time-branch))
(define elements '("甲" "乙" "丙" "丁" "戊" "己" "庚" "辛" "壬" "癸"))
(define element-types '("木" "木" "火" "火" "土" "土" "金" "金" "水" "水"))
(define element-counts (make-vector 5 0))
(for ([char (string->list ba-zi)])
(define char-str (string char))
(for ([j (in-range (length elements))])
(when (equal? char-str (list-ref elements j))
(case (list-ref element-types j)
[("木") (vector-set! element-counts 0 (+ (vector-ref element-counts 0) 1))]
[("火") (vector-set! element-counts 1 (+ (vector-ref element-counts 1) 1))]
[("土") (vector-set! element-counts 2 (+ (vector-ref element-counts 2) 1))]
[("金") (vector-set! element-counts 3 (+ (vector-ref element-counts 3) 1))]
[("水") (vector-set! element-counts 4 (+ (vector-ref element-counts 4) 1))]))))
(define health-suggestions (open-output-string))
(when (< (vector-ref element-counts 2) 2)
(displayln "土弱:需注意脾胃功能,饮食宜温补(如山药、小米),避免生冷。n" health-suggestions))
(when (< (vector-ref element-counts 0) 2)
(displayln "木弱:可增加绿色蔬菜摄入,适度运动疏肝。n" health-suggestions))
(when (> (vector-ref element-counts 3) 2)
(displayln "金旺:需防止过劳,注意肺部健康。n" health-suggestions))
(when (< (vector-ref element-counts 1) 2)
(displayln "火弱:适当食用辛辣食物,保持身体温暖。n" health-suggestions))
(when (< (vector-ref element-counts 4) 2)
(displayln "水弱:多喝水,保持体内水分充足。n" health-suggestions))
(values ba-zi (vector->list element-counts) (get-output-string health-suggestions)))
;; Main function to execute the program
(define birth-year 1981)
(define birth-month 8)
(define birth-day 19)
(define birth-hour 14) ; 未时(13:00-15:00)
(define query-year "乙巳")
(define query-month 2)
(define query-day 12)
(define query-hour 8) ; 卯时(5:00-7:00)
(define-values (original-hexagram changed-hexagram moving-line-remainder) (meihua-yishu query-year query-month query-day query-hour))
(define-values (ba-zi element-counts health-suggestions) (wuxing-analysis birth-year birth-month birth-day birth-hour))
(printf "本卦: ~a, 变卦: ~a, 动爻位置: ~an" original-hexagram changed-hexagram moving-line-remainder)
(printf "八字: ~an" ba-zi)
(displayln "五行分布: ")
(printf "木: ~a n" (list-ref element-counts 0))
(printf "火: ~a n" (list-ref element-counts 1))
(printf "土: ~a n" (list-ref element-counts 2))
(printf "金: ~a n" (list-ref element-counts 3))
(printf "水: ~a n" (list-ref element-counts 4))
(displayln health-suggestions)
import scala.collection.mutable.ListBuffer
// Function to get the trigram based on a number
def getGuaNumber(number: Int): String = {
val guaMap = Map(
1 -> "乾",
2 -> "兑",
3 -> "离",
4 -> "震",
5 -> "巽",
6 -> "坎",
7 -> "艮",
0 -> "坤"
)
guaMap.getOrElse(number, "")
}
// Function to perform the Mei Hua Yishu calculation
def meihuaYishu(year: String, month: Int, day: Int, hour: Int): (String, String, Int) = {
val earthBranches = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
val branchNames = Array("子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥")
val lastChar = year.last.toString
val yearBranch = branchNames.indexOf(lastChar)
val upperTrigramSum = yearBranch + month + day
val upperTrigramRemainder = upperTrigramSum % 8
val lowerTrigramSum = upperTrigramSum + hour
val lowerTrigramRemainder = lowerTrigramSum % 8
val movingLineRemainder = lowerTrigramSum % 6
val originalHexagram = getGuaNumber(upperTrigramRemainder) + getGuaNumber(lowerTrigramRemainder)
val changedHexagram = getChangedHexagram(originalHexagram, movingLineRemainder)
(originalHexagram, changedHexagram, movingLineRemainder)
}
// Function to determine the changed hexagram
def getChangedHexagram(hexagram: String, movingLine: Int): String = {
val hexagrams = Array(
("乾", "兌"), ("兑", "離"), ("離", "震"), ("震", "巽"),
("巽", "坎"), ("坎", "艮"), ("艮", "坤"), ("坤", "乾")
)
val gua1 = hexagram.take(2)
val gua2 = hexagram.drop(2)
var changedHexagram = ""
if (movingLine == 1) {
for (pair <- hexagrams) {
if (pair._1 == gua1) {
changedHexagram += pair._2
return changedHexagram
}
}
} else if (movingLine == 2) {
for (pair <- hexagrams) {
if (pair._1 == gua2) {
changedHexagram += pair._2
return changedHexagram
}
}
}
changedHexagram += gua2
changedHexagram
}
// Function to perform the Wu Xing analysis
def wuxingAnalysis(birthYear: Int, birthMonth: Int, birthDay: Int, birthHour: Int): (String, Array[Int], String) = {
val yearStems = Array("甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸")
val yearBranches = Array("子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥")
val yearIndex = (birthYear - 4) % 60
val yearStem = yearStems(yearIndex / 12)
val yearBranch = yearBranches(yearIndex % 12)
val monthOffsets = Array(0, 0, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val monthIndex = monthOffsets(birthMonth) + yearIndex / 12
val monthStem = yearStems(monthIndex % 10)
val monthBranch = yearBranches((yearIndex % 12 + monthOffsets(birthMonth)) % 12)
var baseDate = 693901
val daysInMonth = Array(0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
for (y <- 1900 until birthYear) {
if ((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0)) {
baseDate += 366
} else {
baseDate += 365
}
}
for (m <- 1 until birthMonth) {
baseDate += daysInMonth(m)
if (m == 2 && ((birthYear % 4 == 0 && birthYear % 100 != 0) || (birthYear % 400 == 0))) {
baseDate += 1
}
}
baseDate += birthDay
val dayIndex = (baseDate + 1) % 60
val dayStem = yearStems(dayIndex / 12)
val dayBranch = yearBranches(dayIndex % 12)
val timeBranches = Array("子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥")
val timeBranchIndex = (birthHour - 1) / 2
val timeBranch = timeBranches(timeBranchIndex)
val baZi = s"$yearStem$yearBranch $monthStem$monthBranch $dayStem$dayBranch $timeBranch"
val elements = Array("甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸")
val elementTypes = Array("木", "木", "火", "火", "土", "土", "金", "金", "水", "水")
val elementCounts = Array.fill(5)(0)
for (char <- baZi.toCharArray) {
val charStr = char.toString
for (j <- elements.indices) {
if (charStr == elements(j)) {
elementTypes(j) match {
case "木" => elementCounts(0) += 1
case "火" => elementCounts(1) += 1
case "土" => elementCounts(2) += 1
case "金" => elementCounts(3) += 1
case "水" => elementCounts(4) += 1
case _ =>
}
}
}
}
var healthSuggestions = new StringBuilder()
if (elementCounts(2) < 2) {
healthSuggestions.append("土弱:需注意脾胃功能,饮食宜温补(如山药、小米),避免生冷。n")
}
if (elementCounts(0) < 2) {
healthSuggestions.append("木弱:可增加绿色蔬菜摄入,适度运动疏肝。n")
}
if (elementCounts(3) > 2) {
healthSuggestions.append("金旺:需防止过劳,注意肺部健康。n")
}
if (elementCounts(1) < 2) {
healthSuggestions.append("火弱:适当食用辛辣食物,保持身体温暖。n")
}
if (elementCounts(4) < 2) {
healthSuggestions.append("水弱:多喝水,保持体内水分充足。n")
}
(baZi, elementCounts, healthSuggestions.toString())
}
// Main function to execute the program
val birthYear = 1981
val birthMonth = 8
val birthDay = 19
val birthHour = 14 // 未时(13:00-15:00)
val queryYear = "乙巳"
val queryMonth = 2
val queryDay = 12
val queryHour = 8 // 卯时(5:00-7:00)
val (originalHexagram, changedHexagram, movingLineRemainder) = meihuaYishu(queryYear, queryMonth, queryDay, queryHour)
val (baZi, elementCounts, healthSuggestions) = wuxingAnalysis(birthYear, birthMonth, birthDay, birthHour)
println(s"本卦: $originalHexagram, 变卦: $changedHexagram, 动爻位置: $movingLineRemainder")
println(s"八字: $baZi")
println("五行分布: ")
println(s"木: ${elementCounts(0)} ")
println(s"火: ${elementCounts(1)} ")
println(s"土: ${elementCounts(2)} ")
println(s"金: ${elementCounts(3)} ")
println(s"水: ${elementCounts(4)}n")
println(healthSuggestions)
import Foundation
// Function to get the trigram based on a number
func getGuaNumber(_ number: Int) -> String {
let guaMap: [Int: String] = [
1: "乾",
2: "兑",
3: "离",
4: "震",
5: "巽",
6: "坎",
7: "艮",
0: "坤"
]
return guaMap[number] ?? ""
}
// Function to perform the Mei Hua Yishu calculation
func meihuaYishu(year: String, month: Int, day: Int, hour: Int) -> (String, String, Int) {
let earthBranches = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
let branchNames = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"]
guard let lastChar = year.last else { return ("", "", 0) }
let yearBranch = branchNames.firstIndex(of: String(lastChar)) ?? 0
let upperTrigramSum = yearBranch + month + day
let upperTrigramRemainder = upperTrigramSum % 8
let lowerTrigramSum = upperTrigramSum + hour
let lowerTrigramRemainder = lowerTrigramSum % 8
let movingLineRemainder = lowerTrigramSum % 6
let originalHexagram = getGuaNumber(upperTrigramRemainder) + getGuaNumber(lowerTrigramRemainder)
let changedHexagram = getChangedHexagram(hexagram: originalHexagram, movingLine: movingLineRemainder)
return (originalHexagram, changedHexagram, movingLineRemainder)
}
// Function to determine the changed hexagram
func getChangedHexagram(hexagram: String, movingLine: Int) -> String {
let hexagrams: [(String, String)] = [
("乾", "兌"), ("兑", "離"), ("離", "震"), ("震", "巽"),
("巽", "坎"), ("坎", "艮"), ("艮", "坤"), ("坤", "乾")
]
let gua1 = String(hexagram.prefix(2))
let gua2 = String(hexagram.suffix(2))
var changedHexagram = ""
if movingLine == 1 {
for pair in hexagrams {
if pair.0 == gua1 {
changedHexagram.append(pair.1)
break
}
}
} else if movingLine == 2 {
for pair in hexagrams {
if pair.0 == gua2 {
changedHexagram.append(pair.1)
break
}
}
}
changedHexagram.append(gua2)
return changedHexagram
}
// Function to perform the Wu Xing analysis
func wuxingAnalysis(birthYear: Int, birthMonth: Int, birthDay: Int, birthHour: Int) -> (String, [Int], String) {
let yearStems = ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"]
let yearBranches = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"]
let yearIndex = (birthYear - 4) % 60
let yearStem = yearStems[yearIndex / 12]
let yearBranch = yearBranches[yearIndex % 12]
let monthOffsets = [0, 0, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let monthIndex = monthOffsets[birthMonth] + yearIndex / 12
let monthStem = yearStems[monthIndex % 10]
let monthBranch = yearBranches[(yearIndex % 12 + monthOffsets[birthMonth]) % 12]
var baseDate = 693901
let daysInMonth = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
for y in 1900..
2 {
healthSuggestions += "金旺:需防止过劳,注意肺部健康。n"
}
if elementCounts[1] < 2 {
healthSuggestions += "火弱:适当食用辛辣食物,保持身体温暖。n"
}
if elementCounts[4] < 2 {
healthSuggestions += "水弱:多喝水,保持体内水分充足。n"
}
return (baZi, elementCounts, healthSuggestions)
}
// Main function to execute the program
let birthYear = 1981
let birthMonth = 8
let birthDay = 19
let birthHour = 14 // 未时(13:00-15:00)
let queryYear = "乙巳"
let queryMonth = 2
let queryDay = 12
let queryHour = 8 // 卯时(5:00-7:00)
let (originalHexagram, changedHexagram, movingLineRemainder) = meihuaYishu(year: queryYear, month: queryMonth, day: queryDay, hour: queryHour)
let (baZi, elementCounts, healthSuggestions) = wuxingAnalysis(birthYear: birthYear, birthMonth: birthMonth, birthDay: birthDay, birthHour: birthHour)
print("本卦: (originalHexagram), 变卦: (changedHexagram), 动爻位置: (movingLineRemainder)")
print("八字: (baZi)")
print("五行分布: ")
print("木: (elementCounts[0]) ")
print("火: (elementCounts[1]) ")
print("土: (elementCounts[2]) ")
print("金: (elementCounts[3]) ")
print("水: (elementCounts[4])n")
print(healthSuggestions)
-- 定义主函数
function main()
local birthYear = 1981
local birthMonth = 8
local birthDay = 19
local birthHour = 14 -- 未时(13:00-15:00)
local queryYear = "乙巳"
local queryMonth = 2
local queryDay = 12
local queryHour = 8 -- 卯时(5:00-7:00)
local originalHexagram, changedHexagram, movingLineRemainder = meihuaYishu(queryYear, queryMonth, queryDay, queryHour)
local baZi, elementCounts, healthSuggestions = wuxingAnalysis(birthYear, birthMonth, birthDay, birthHour)
print(string.format("本卦: %s, 变卦: %s, 动爻位置: %d", originalHexagram, changedHexagram, movingLineRemainder))
print(string.format("八字: %s", baZi))
print("五行分布:")
for element, count in pairs(elementCounts) do
print(string.format("%s: %d", element, count))
end
for _, suggestion in ipairs(healthSuggestions) do
print(suggestion)
end
end
-- 获取八卦编号
function getGuaNumber(number)
local guaMap = {
[1] = "乾", [2] = "兑", [3] = "离", [4] = "震", [5] = "巽",
[6] = "坎", [7] = "艮", [0] = "坤"
}
return guaMap[number] or ""
end
-- 易经梅花易数
function meihuaYishu(year, month, day, hour)
local earthBranches = {
['子'] = 1, ['丑'] = 2,
['寅'] = 3, ['卯'] = 4,
['辰'] = 5, ['巳'] = 6,
['午'] = 7, ['未'] = 8,
['申'] = 9, ['酉'] = 10,
['戌'] = 11, ['亥'] = 12,
}
-- 获取年份的地支数字
local lastChar = year:sub(-1)
local yearBranch = earthBranches[lastChar]
-- 计算上卦
local upperTrigramSum = yearBranch + month + day
local upperTrigramRemainder = upperTrigramSum % 8
-- 计算下卦
local lowerTrigramSum = upperTrigramSum + hour
local lowerTrigramRemainder = lowerTrigramSum % 8
-- 计算动爻
local movingLineRemainder = lowerTrigramSum % 6
-- 确定本卦和变卦
local originalHexagram = getGuaNumber(upperTrigramRemainder) .. getGuaNumber(lowerTrigramRemainder)
local changedHexagram = getChangedHexagram(originalHexagram, movingLineRemainder)
return originalHexagram, changedHexagram, movingLineRemainder
end
-- 获取变化后的卦象
function getChangedHexagram(hexagram, movingLine)
local hexagrams = {
["乾"] = {"乾", "兌"}, ["兑"] = {"兑", "離"},
["離"] = {"離", "震"}, ["震"] = {"震", "巽"},
["巽"] = {"巽", "坎"}, ["坎"] = {"坎", "艮"},
["艮"] = {"艮", "坤"}, ["坤"] = {"坤", "乾"}
}
local lines = {hexagram:match("(.)")}
if movingLine == 1 then
lines[1] = hexagrams[lines[1]][2]
elseif movingLine == 2 then
lines[2] = hexagrams[lines[2]][2]
end
return table.concat(lines)
end
-- 五行分析
function wuxingAnalysis(birthYear, birthMonth, birthDay, birthHour)
local yearStems = {"甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"}
local yearBranches = {"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"}
local yearIndex = (birthYear - 4) % 60
local yearStem = yearStems[math.floor(yearIndex / 12) + 1]
local yearBranch = yearBranches[yearIndex % 12 + 1]
-- 月干支
local monthOffsets = {0, 0, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
local monthIndex = monthOffsets[birthMonth] + math.floor(yearIndex / 12)
local monthStem = yearStems[monthIndex % 10 + 1]
local monthBranch = yearBranches[(yearIndex % 12 + monthOffsets[birthMonth]) % 12 + 1]
-- 日干支
local baseDate = 1900 * 365 + math.floor(1900 / 4) - math.floor(1900 / 100) + math.floor(1900 / 400) + 1900 * 12 + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31 + 18 -- 从1900年1月1日开始计算
local daysInMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
for y = 1900, birthYear - 1 do
baseDate = baseDate + 365 + leapYear(y)
end
for m = 1, birthMonth - 1 do
baseDate = baseDate + daysInMonth[m + 1] + leapYearDay(birthYear, m)
end
baseDate = baseDate + birthDay
local dayIndex = (baseDate + 1) % 60
local dayStem = yearStems[math.floor(dayIndex / 12) + 1]
local dayBranch = yearBranches[dayIndex % 12 + 1]
-- 时干支
local timeBranches = {"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"}
local timeBranchIndex = math.floor((birthHour - 1) / 2)
local timeBranch = timeBranches[timeBranchIndex + 1]
-- 八字
local baZi = string.format("%s%s %s%s %s%s %s", yearStem, yearBranch, monthStem, monthBranch, dayStem, dayBranch, timeBranch)
-- 五行分析
local elements = {
['甲'] = "木", ['乙'] = "木", ['丙'] = "火", ['丁'] = "火", ['戊'] = "土",
['己'] = "土", ['庚'] = "金", ['辛'] = "金", ['壬'] = "水", ['癸'] = "水"
}
local elementCounts = {["木"] = 0, ["火"] = 0, ["土"] = 0, ["金"] = 0, ["水"] = 0}
for char in baZi:gmatch(".") do
if elements[char] then
elementCounts[elements[char]] = elementCounts[elements[char]] + 1
end
end
-- 健康建议
local healthSuggestions = {}
if elementCounts["土"] < 2 then
table.insert(healthSuggestions, "土弱:需注意脾胃功能,饮食宜温补(如山药、小米),避免生冷。")
end
if elementCounts["木"] < 2 then
table.insert(healthSuggestions, "木弱:可增加绿色蔬菜摄入,适度运动疏肝。")
end
if elementCounts["金"] > 2 then
table.insert(healthSuggestions, "金旺:需防止过劳,注意肺部健康。")
end
if elementCounts["火"] < 2 then
table.insert(healthSuggestions, "火弱:适当食用辛辣食物,保持身体温暖。")
end
if elementCounts["水"] < 2 then
table.insert(healthSuggestions, "水弱:多喝水,保持体内水分充足。")
end
return baZi, elementCounts, healthSuggestions
end
-- 判断闰年
function leapYear(year)
return (year % 4 == 0 and (year % 100 ~= 0 or year % 400 == 0)) and 1 or 0
end
-- 判断闰年天数
function leapYearDay(year, month)
return (month == 2 and leapYear(year) == 1) and 1 or 0
end
-- 运行主函数
main()
Module Module1
Function GetGuaNumber(number As Integer) As String
Select Case number
Case 1
Return "乾"
Case 2
Return "兑"
Case 3
Return "离"
Case 4
Return "震"
Case 5
Return "巽"
Case 6
Return "坎"
Case 7
Return "艮"
Case 0
Return "坤"
Case Else
Return ""
End Select
End Function
Function MeihuaYishu(year As String, month As Integer, day As Integer, hour As Integer) As Tuple(Of String, String, Integer)
Dim earthBranches() As Integer = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}
Dim branchNames() As String = {"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"}
Dim lastChar As Char = year.Chars(year.Length - 1)
Dim yearBranch As Integer = 0
For i As Integer = 0 To branchNames.Length - 1
If branchNames(i) = lastChar.ToString() Then
yearBranch = earthBranches(i)
Exit For
End If
Next
Dim upperTrigramSum As Integer = yearBranch + month + day
Dim upperTrigramRemainder As Integer = upperTrigramSum Mod 8
Dim lowerTrigramSum As Integer = upperTrigramSum + hour
Dim lowerTrigramRemainder As Integer = lowerTrigramSum Mod 8
Dim movingLineRemainder As Integer = lowerTrigramSum Mod 6
Dim originalHexagram As String = $"{GetGuaNumber(upperTrigramRemainder)}{GetGuaNumber(lowerTrigramRemainder)}"
Dim changedHexagram As String = GetChangedHexagram(originalHexagram, movingLineRemainder)
Return New Tuple(Of String, String, Integer)(originalHexagram, changedHexagram, movingLineRemainder)
End Function
Function GetChangedHexagram(hexagram As String, movingLine As Integer) As String
Dim hexagrams() As Tuple(Of String, String) = {
Tuple.Create("乾", "兌"), Tuple.Create("兑", "離"), Tuple.Create("離", "震"), Tuple.Create("震", "巽"),
Tuple.Create("巽", "坎"), Tuple.Create("坎", "艮"), Tuple.Create("艮", "坤"), Tuple.Create("坤", "乾")
}
Dim gua1 As String = hexagram.Substring(0, 2)
Dim gua2 As String = hexagram.Substring(2, 2)
Dim changedHexagram As System.Text.StringBuilder = New System.Text.StringBuilder()
If movingLine = 1 Then
For Each pair In hexagrams
If pair.Item1 = gua1 Then
changedHexagram.Append(pair.Item2)
Exit For
End If
Next
ElseIf movingLine = 2 Then
For Each pair In hexagrams
If pair.Item1 = gua2 Then
changedHexagram.Append(pair.Item2)
Exit For
End If
Next
End If
changedHexagram.Append(gua2)
Return changedHexagram.ToString()
End Function
Function WuxingAnalysis(birthYear As Integer, birthMonth As Integer, birthDay As Integer, birthHour As Integer) As Tuple(Of String, List(Of Integer), String)
Dim yearStems() As String = {"甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"}
Dim yearBranches() As String = {"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"}
Dim yearIndex As Integer = (birthYear - 4) Mod 60
Dim yearStem As String = yearStems(yearIndex 12)
Dim yearBranch As String = yearBranches(yearIndex Mod 12)
Dim monthOffsets() As Integer = {0, 0, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Dim monthIndex As Integer = monthOffsets(birthMonth) + yearIndex 12
Dim monthStem As String = yearStems(monthIndex Mod 10)
Dim monthBranch As String = yearBranches((yearIndex Mod 12 + monthOffsets(birthMonth)) Mod 12)
Dim baseDate As Integer = 693901
Dim daysInMonth() As Integer = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
For y As Integer = 1900 To birthYear - 1
If (y Mod 4 = 0 AndAlso y Mod 100 <> 0) OrElse (y Mod 400 = 0) Then
baseDate += 366
Else
baseDate += 365
End If
Next
For m As Integer = 1 To birthMonth - 1
baseDate += daysInMonth(m)
If m = 2 AndAlso ((birthYear Mod 4 = 0 AndAlso birthYear Mod 100 <> 0) OrElse (birthYear Mod 400 = 0)) Then
baseDate += 1
End If
Next
baseDate += birthDay
Dim dayIndex As Integer = (baseDate + 1) Mod 60
Dim dayStem As String = yearStems(dayIndex 12)
Dim dayBranch As String = yearBranches(dayIndex Mod 12)
Dim timeBranches() As String = {"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"}
Dim timeBranchIndex As Integer = (birthHour - 1) 2
Dim timeBranch As String = timeBranches(timeBranchIndex)
Dim baZi As String = $"{yearStem}{yearBranch} {monthStem}{monthBranch} {dayStem}{dayBranch} {timeBranch}"
Dim elements() As String = {"甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"}
Dim elementTypes() As String = {"木", "木", "火", "火", "土", "土", "金", "金", "水", "水"}
Dim elementCounts As List(Of Integer) = New List(Of Integer) From {0, 0, 0, 0, 0}
For Each char In baZi.ToCharArray()
Dim charStr As String = char.ToString()
For j As Integer = 0 To elements.Length - 1
If charStr = elements(j) Then
Select Case elementTypes(j)
Case "木"
elementCounts(0) += 1
Case "火"
elementCounts(1) += 1
Case "土"
elementCounts(2) += 1
Case "金"
elementCounts(3) += 1
Case "水"
elementCounts(4) += 1
End Select
End If
Next
Next
Dim healthSuggestions As System.Text.StringBuilder = New System.Text.StringBuilder()
If elementCounts(2) < 2 Then
healthSuggestions.Append("土弱:需注意脾胃功能,饮食宜温补(如山药、小米),避免生冷。" & vbCrLf)
End If
If elementCounts(0) < 2 Then
healthSuggestions.Append("木弱:可增加绿色蔬菜摄入,适度运动疏肝。" & vbCrLf)
End If
If elementCounts(3) > 2 Then
healthSuggestions.Append("金旺:需防止过劳,注意肺部健康。" & vbCrLf)
End If
If elementCounts(1) < 2 Then
healthSuggestions.Append("火弱:适当食用辛辣食物,保持身体温暖。" & vbCrLf)
End If
If elementCounts(4) < 2 Then
healthSuggestions.Append("水弱:多喝水,保持体内水分充足。" & vbCrLf)
End If
Return New Tuple(Of String, List(Of Integer), String)(baZi, elementCounts, healthSuggestions.ToString())
End Function
Sub Main()
Dim birthYear As Integer = 1981
Dim birthMonth As Integer = 8
Dim birthDay As Integer = 19
Dim birthHour As Integer = 14 ' 未时(13:00-15:00)
Dim queryYear As String = "乙巳"
Dim queryMonth As Integer = 2
Dim queryDay As Integer = 12
Dim queryHour As Integer = 8 ' 卯时(5:00-7:00)
Dim resultMeihuaYishu As Tuple(Of String, String, Integer) = MeihuaYishu(queryYear, queryMonth, queryDay, queryHour)
Dim resultWuxingAnalysis As Tuple(Of String, List(Of Integer), String) = WuxingAnalysis(birthYear, birthMonth, birthDay, birthHour)
Console.WriteLine($"本卦: {resultMeihuaYishu.Item1}, 变卦: {resultMeihuaYishu.Item2}, 动爻位置: {resultMeihuaYishu.Item3}")
Console.WriteLine($"八字: {resultWuxingAnalysis.Item1}")
Console.Write("五行分布: ")
Console.Write($"木: {resultWuxingAnalysis.Item2(0)} ")
Console.Write($"火: {resultWuxingAnalysis.Item2(1)} ")
Console.Write($"土: {resultWuxingAnalysis.Item2(2)} ")
Console.Write($"金: {resultWuxingAnalysis.Item2(3)} ")
Console.Write($"水: {resultWuxingAnalysis.Item2(4)}" & vbCrLf)
Console.Write($"{resultWuxingAnalysis.Item3}")
End Sub
End Module
String getGuaNumber(int number) {
switch (number) {
case 1:
return "乾";
case 2:
return "兑";
case 3:
return "离";
case 4:
return "震";
case 5:
return "巽";
case 6:
return "坎";
case 7:
return "艮";
case 0:
return "坤";
default:
return "";
}
}
Triple meihuaYishu(String year, int month, int day, int hour) {
final earthBranches = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
final branchNames = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"];
final lastChar = year[year.length - 1];
int yearBranch = 0;
for (int i = 0; i < branchNames.length; i++) {
if (branchNames[i] == lastChar) {
yearBranch = earthBranches[i];
break;
}
}
final upperTrigramSum = yearBranch + month + day;
final upperTrigramRemainder = upperTrigramSum % 8;
final lowerTrigramSum = upperTrigramSum + hour;
final lowerTrigramRemainder = lowerTrigramSum % 8;
final movingLineRemainder = lowerTrigramSum % 6;
final originalHexagram = "${getGuaNumber(upperTrigramRemainder)}${getGuaNumber(lowerTrigramRemainder)}";
final changedHexagram = getChangedHexagram(originalHexagram, movingLineRemainder);
return Triple(originalHexagram, changedHexagram, movingLineRemainder);
}
String getChangedHexagram(String hexagram, int movingLine) {
final hexagrams = [
Pair("乾", "兌"), Pair("兑", "離"), Pair("離", "震"), Pair("震", "巽"),
Pair("巽", "坎"), Pair("坎", "艮"), Pair("艮", "坤"), Pair("坤", "乾"),
];
final gua1 = hexagram.substring(0, 2);
final gua2 = hexagram.substring(2, 4);
final changedHexagram = StringBuffer();
if (movingLine == 1) {
for (final pair in hexagrams) {
if (pair.first == gua1) {
changedHexagram.write(pair.second);
break;
}
}
} else if (movingLine == 2) {
for (final pair in hexagrams) {
if (pair.first == gua2) {
changedHexagram.write(pair.second);
break;
}
}
}
changedHexagram.write(gua2);
return changedHexagram.toString();
}
Triple, String> wuxingAnalysis(int birthYear, int birthMonth, int birthDay, int birthHour) {
final yearStems = ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"];
final yearBranches = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"];
final yearIndex = (birthYear - 4) % 60;
final yearStem = yearStems[yearIndex ~/ 12];
final yearBranch = yearBranches[yearIndex % 12];
final monthOffsets = [0, 0, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
final monthIndex = monthOffsets[birthMonth] + yearIndex ~/ 12;
final monthStem = yearStems[monthIndex % 10];
final monthBranch = yearBranches[(yearIndex % 12 + monthOffsets[birthMonth]) % 12];
int baseDate = 693901;
final daysInMonth = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
for (int y = 1900; y < birthYear; y++) {
if ((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0)) {
baseDate += 366;
} else {
baseDate += 365;
}
}
for (int m = 1; m < birthMonth; m++) {
baseDate += daysInMonth[m];
if (m == 2 && ((birthYear % 4 == 0 && birthYear % 100 != 0) || (birthYear % 400 == 0))) {
baseDate += 1;
}
}
baseDate += birthDay;
final dayIndex = (baseDate + 1) % 60;
final dayStem = yearStems[dayIndex ~/ 12];
final dayBranch = yearBranches[dayIndex % 12];
final timeBranches = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"];
final timeBranchIndex = (birthHour - 1) ~/ 2;
final timeBranch = timeBranches[timeBranchIndex];
final baZi = "$yearStem$yearBranch $monthStem$monthBranch $dayStem$dayBranch $timeBranch";
final elements = ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"];
final elementTypes = ["木", "木", "火", "火", "土", "土", "金", "金", "水", "水"];
final elementCounts = List.filled(5, 0);
for (final char in baZi.codeUnits.map((unit) => String.fromCharCode(unit))) {
final charStr = char;
for (int j = 0; j < elements.length; j++) {
if (charStr == elements[j]) {
switch (elementTypes[j]) {
case "木":
elementCounts[0]++;
break;
case "火":
elementCounts[1]++;
break;
case "土":
elementCounts[2]++;
break;
case "金":
elementCounts[3]++;
break;
case "水":
elementCounts[4]++;
break;
}
}
}
}
final healthSuggestions = StringBuffer();
if (elementCounts[2] < 2) {
healthSuggestions.write("土弱:需注意脾胃功能,饮食宜温补(如山药、小米),避免生冷。n");
}
if (elementCounts[0] < 2) {
healthSuggestions.write("木弱:可增加绿色蔬菜摄入,适度运动疏肝。n");
}
if (elementCounts[3] > 2) {
healthSuggestions.write("金旺:需防止过劳,注意肺部健康。n");
}
if (elementCounts[1] < 2) {
healthSuggestions.write("火弱:适当食用辛辣食物,保持身体温暖。n");
}
if (elementCounts[4] < 2) {
healthSuggestions.write("水弱:多喝水,保持体内水分充足。n");
}
return Triple(baZi, elementCounts, healthSuggestions.toString());
}
void main() {
final birthYear = 1981;
final birthMonth = 8;
final birthDay = 19;
final birthHour = 14; // 未时(13:00-15:00)
final queryYear = "乙巳";
final queryMonth = 2;
final queryDay = 12;
final queryHour = 8; // 卯时(5:00-7:00)
final resultMeihuaYishu = meihuaYishu(queryYear, queryMonth, queryDay, queryHour);
final resultWuxingAnalysis = wuxingAnalysis(birthYear, birthMonth, birthDay, birthHour);
print("本卦: ${resultMeihuaYishu.item1}, 变卦: ${resultMeihuaYishu.item2}, 动爻位置: ${resultMeihuaYishu.item3}");
print("八字: ${resultWuxingAnalysis.item1}");
print("五行分布: ");
print("木: ${resultWuxingAnalysis.item2[0]} ");
print("火: ${resultWuxingAnalysis.item2[1]} ");
print("土: ${resultWuxingAnalysis.item2[2]} ");
print("金: ${resultWuxingAnalysis.item2[3]} ");
print("水: ${resultWuxingAnalysis.item2[4]}n");
print("${resultWuxingAnalysis.item3}");
}
class Triple {
final T1 item1;
final T2 item2;
final T3 item3;
Triple(this.item1, this.item2, this.item3);
}
class Pair {
final T1 first;
final T2 second;
Pair(this.first, this.second);
}
fun getGuaNumber(number: Int): String {
return when (number) {
1 -> "乾"
2 -> "兑"
3 -> "离"
4 -> "震"
5 -> "巽"
6 -> "坎"
7 -> "艮"
0 -> "坤"
else -> ""
}
}
fun meihuaYishu(year: String, month: Int, day: Int, hour: Int): Triple {
val earthBranches = intArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
val branchNames = arrayOf("子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥")
val lastChar = year.last()
var yearBranch = 0
for ((i, name) in branchNames.withIndex()) {
if (name == lastChar.toString()) {
yearBranch = earthBranches[i]
break
}
}
val upperTrigramSum = yearBranch + month + day
val upperTrigramRemainder = upperTrigramSum % 8
val lowerTrigramSum = upperTrigramSum + hour
val lowerTrigramRemainder = lowerTrigramSum % 8
val movingLineRemainder = lowerTrigramSum % 6
val originalHexagram = "${getGuaNumber(upperTrigramRemainder)}${getGuaNumber(lowerTrigramRemainder)}"
val changedHexagram = getChangedHexagram(originalHexagram, movingLineRemainder)
return Triple(originalHexagram, changedHexagram, movingLineRemainder)
}
fun getChangedHexagram(hexagram: String, movingLine: Int): String {
val hexagrams = arrayOf(
Pair("乾", "兌"), Pair("兑", "離"), Pair("離", "震"), Pair("震", "巽"),
Pair("巽", "坎"), Pair("坎", "艮"), Pair("艮", "坤"), Pair("坤", "乾")
)
val gua1 = hexagram.substring(0, 2)
val gua2 = hexagram.substring(2, 4)
val changedHexagram = StringBuilder()
if (movingLine == 1) {
for (pair in hexagrams) {
if (pair.first == gua1) {
changedHexagram.append(pair.second)
break
}
}
} else if (movingLine == 2) {
for (pair in hexagrams) {
if (pair.first == gua2) {
changedHexagram.append(pair.second)
break
}
}
}
changedHexagram.append(gua2)
return changedHexagram.toString()
}
fun wuxingAnalysis(birthYear: Int, birthMonth: Int, birthDay: Int, birthHour: Int): Triple {
val yearStems = arrayOf("甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸")
val yearBranches = arrayOf("子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥")
val yearIndex = (birthYear - 4) % 60
val yearStem = yearStems[yearIndex / 12]
val yearBranch = yearBranches[yearIndex % 12]
val monthOffsets = intArrayOf(0, 0, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val monthIndex = monthOffsets[birthMonth] + yearIndex / 12
val monthStem = yearStems[monthIndex % 10]
val monthBranch = yearBranches[(yearIndex % 12 + monthOffsets[birthMonth]) % 12]
var baseDate = 693901
val daysInMonth = intArrayOf(0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
for (y in 1900 until birthYear) {
if ((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0)) {
baseDate += 366
} else {
baseDate += 365
}
}
for (m in 1 until birthMonth) {
baseDate += daysInMonth[m]
if (m == 2 && ((birthYear % 4 == 0 && birthYear % 100 != 0) || (birthYear % 400 == 0))) {
baseDate += 1
}
}
baseDate += birthDay
val dayIndex = (baseDate + 1) % 60
val dayStem = yearStems[dayIndex / 12]
val dayBranch = yearBranches[dayIndex % 12]
val timeBranches = arrayOf("子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥")
val timeBranchIndex = (birthHour - 1) / 2
val timeBranch = timeBranches[timeBranchIndex]
val baZi = "$yearStem$yearBranch $monthStem$monthBranch $dayStem$dayBranch $timeBranch"
val elements = arrayOf("甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸")
val elementTypes = arrayOf("木", "木", "火", "火", "土", "土", "金", "金", "水", "水")
val elementCounts = IntArray(5)
for (char in baZi) {
val charStr = char.toString()
for (j in elements.indices) {
if (charStr == elements[j]) {
when (elementTypes[j]) {
"木" -> elementCounts[0]++
"火" -> elementCounts[1]++
"土" -> elementCounts[2]++
"金" -> elementCounts[3]++
"水" -> elementCounts[4]++
}
}
}
}
val healthSuggestions = StringBuilder()
if (elementCounts[2] < 2) {
healthSuggestions.append("土弱:需注意脾胃功能,饮食宜温补(如山药、小米),避免生冷。n")
}
if (elementCounts[0] < 2) {
healthSuggestions.append("木弱:可增加绿色蔬菜摄入,适度运动疏肝。n")
}
if (elementCounts[3] > 2) {
healthSuggestions.append("金旺:需防止过劳,注意肺部健康。n")
}
if (elementCounts[1] < 2) {
healthSuggestions.append("火弱:适当食用辛辣食物,保持身体温暖。n")
}
if (elementCounts[4] < 2) {
healthSuggestions.append("水弱:多喝水,保持体内水分充足。n")
}
return Triple(baZi, elementCounts, healthSuggestions.toString())
}
fun main() {
val birthYear = 1981
val birthMonth = 8
val birthDay = 19
val birthHour = 14 // 未时(13:00-15:00)
val queryYear = "乙巳"
val queryMonth = 2
val queryDay = 12
val queryHour = 8 // 卯时(5:00-7:00)
val (originalHexagram, changedHexagram, movingLineRemainder) =
meihuaYishu(queryYear, queryMonth, queryDay, queryHour)
val (baZi, elementCounts, healthSuggestions) =
wuxingAnalysis(birthYear, birthMonth, birthDay, birthHour)
println("本卦: $originalHexagram, 变卦: $changedHexagram, 动爻位置: $movingLineRemainder")
println("八字: $baZi")
print("五行分布: ")
print("木: ${elementCounts[0]} ")
print("火: ${elementCounts[1]} ")
print("土: ${elementCounts[2]} ")
print("金: ${elementCounts[3]} ")
print("水: ${elementCounts[4]}n")
print("$healthSuggestions")
}
fn get_gua_number(number: i32) -> &'static str {
match number {
1 => "乾",
2 => "兑",
3 => "离",
4 => "震",
5 => "巽",
6 => "坎",
7 => "艮",
0 => "坤",
_ => "",
}
}
fn meihua_yishu(year: &str, month: i32, day: i32, hour: i32) -> (String, String, i32) {
let earth_branches = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
let branch_names = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"];
let last_char = year.chars().last().unwrap();
let mut year_branch = 0;
for (i, name) in branch_names.iter().enumerate() {
if *name == last_char.to_string() {
year_branch = earth_branches[i];
break;
}
}
let upper_trigram_sum = year_branch + month + day;
let upper_trigram_remainder = upper_trigram_sum % 8;
let lower_trigram_sum = upper_trigram_sum + hour;
let lower_trigram_remainder = lower_trigram_sum % 8;
let moving_line_remainder = lower_trigram_sum % 6;
let original_hexagram = format!(
"{}{}",
get_gua_number(upper_trigram_remainder),
get_gua_number(lower_trigram_remainder)
);
let changed_hexagram = get_changed_hexagram(&original_hexagram, moving_line_remainder);
(original_hexagram, changed_hexagram, moving_line_remainder)
}
fn get_changed_hexagram(hexagram: &str, moving_line: i32) -> String {
let hexagrams = [
("乾", "兌"), ("兑", "離"), ("離", "震"), ("震", "巽"),
("巽", "坎"), ("坎", "艮"), ("艮", "坤"), ("坤", "乾"),
];
let gua1 = &hexagram[..2];
let gua2 = &hexagram[2..];
let mut changed_hexagram = String::new();
if moving_line == 1 {
for pair in hexagrams.iter() {
if pair.0 == gua1 {
changed_hexagram.push_str(pair.1);
break;
}
}
} else if moving_line == 2 {
for pair in hexagrams.iter() {
if pair.0 == gua2 {
changed_hexagram.push_str(pair.1);
break;
}
}
}
changed_hexagram.push_str(gua2);
changed_hexagram
}
fn wuxing_analysis(birth_year: i32, birth_month: i32, birth_day: i32, birth_hour: i32) -> (String, [i32; 5], String) {
let year_stems = ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"];
let year_branches = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"];
let year_index = (birth_year - 4) % 60;
let year_stem = year_stems[(year_index / 12) as usize];
let year_branch = year_branches[(year_index % 12) as usize];
let month_offsets = [0, 0, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let month_index = month_offsets[birth_month as usize] + year_index / 12;
let month_stem = year_stems[(month_index % 10) as usize];
let month_branch = year_branches[((year_index % 12) + month_offsets[birth_month as usize]) % 12];
let mut base_date = 693901;
let days_in_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
for y in 1900..birth_year {
if (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0) {
base_date += 366;
} else {
base_date += 365;
}
}
for m in 1..birth_month {
base_date += days_in_month[m as usize];
if m == 2 && ((birth_year % 4 == 0 && birth_year % 100 != 0) || (birth_year % 400 == 0)) {
base_date += 1;
}
}
base_date += birth_day;
let day_index = (base_date + 1) % 60;
let day_stem = year_stems[(day_index / 12) as usize];
let day_branch = year_branches[(day_index % 12) as usize];
let time_branches = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"];
let time_branch_index = (birth_hour - 1) / 2;
let time_branch = time_branches[time_branch_index as usize];
let ba_zi = format!(
"{}{} {}{} {}{} {}",
year_stem, year_branch, month_stem, month_branch, day_stem, day_branch, time_branch
);
let elements = ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"];
let element_types = ["木", "木", "火", "火", "土", "土", "金", "金", "水", "水"];
let mut element_counts = [0; 5];
for char in ba_zi.chars() {
let char_str = char.to_string();
for j in 0..elements.len() {
if char_str == elements[j] {
match element_types[j] {
"木" => element_counts[0] += 1,
"火" => element_counts[1] += 1,
"土" => element_counts[2] += 1,
"金" => element_counts[3] += 1,
"水" => element_counts[4] += 1,
_ => {}
}
}
}
}
let mut health_suggestions = String::new();
if element_counts[2] < 2 {
health_suggestions.push_str("土弱:需注意脾胃功能,饮食宜温补(如山药、小米),避免生冷。n");
}
if element_counts[0] < 2 {
health_suggestions.push_str("木弱:可增加绿色蔬菜摄入,适度运动疏肝。n");
}
if element_counts[3] > 2 {
health_suggestions.push_str("金旺:需防止过劳,注意肺部健康。n");
}
if element_counts[1] < 2 {
health_suggestions.push_str("火弱:适当食用辛辣食物,保持身体温暖。n");
}
if element_counts[4] < 2 {
health_suggestions.push_str("水弱:多喝水,保持体内水分充足。n");
}
(ba_zi, element_counts, health_suggestions)
}
fn main() {
let birth_year = 1981;
let birth_month = 8;
let birth_day = 19;
let birth_hour = 14; // 未时(13:00-15:00)
let query_year = "乙巳";
let query_month = 2;
let query_day = 12;
let query_hour = 8; // 卯时(5:00-7:00)
let (original_hexagram, changed_hexagram, moving_line_remainder) =
meihua_yishu(query_year, query_month, query_day, query_hour);
let (ba_zi, element_counts, health_suggestions) =
wuxing_analysis(birth_year, birth_month, birth_day, birth_hour);
println!("本卦: {}, 变卦: {}, 动爻位置: {}", original_hexagram, changed_hexagram, moving_line_remainder);
println!("八字: {}", ba_zi);
print!("五行分布: ");
print!("木: {} ", element_counts[0]);
print!("火: {} ", element_counts[1]);
print!("土: {} ", element_counts[2]);
print!("金: {} ", element_counts[3]);
print!("水: {}n", element_counts[4]);
print!("{}", health_suggestions);
}
package main
import (
"fmt"
"strings"
)
func getGuaNumber(number int) string {
switch number {
case 1:
return "乾"
case 2:
return "兑"
case 3:
return "离"
case 4:
return "震"
case 5:
return "巽"
case 6:
return "坎"
case 7:
return "艮"
case 0:
return "坤"
default:
return ""
}
}
func meihuaYishu(year string, month, day, hour int) (originalHexagram, changedHexagram string, movingLineRemainder int) {
earthBranches := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}
branchNames := []string{"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"}
lastChar := year[len(year)-1:]
yearBranch := 0
for i, name := range branchNames {
if lastChar == name {
yearBranch = earthBranches[i]
break
}
}
upperTrigramSum := yearBranch + month + day
upperTrigramRemainder := upperTrigramSum % 8
lowerTrigramSum := upperTrigramSum + hour
lowerTrigramRemainder := lowerTrigramSum % 8
movingLineRemainder = lowerTrigramSum % 6
originalHexagram = getGuaNumber(upperTrigramRemainder) + getGuaNumber(lowerTrigramRemainder)
changedHexagram = getChangedHexagram(originalHexagram, movingLineRemainder)
return originalHexagram, changedHexagram, movingLineRemainder
}
func getChangedHexagram(hexagram string, movingLine int) string {
hexagrams := [][]string{
{"乾", "兌"}, {"兑", "離"}, {"離", "震"}, {"震", "巽"},
{"巽", "坎"}, {"坎", "艮"}, {"艮", "坤"}, {"坤", "乾"},
}
gua1 := hexagram[:2]
gua2 := hexagram[2:]
var changedHexagram string
if movingLine == 1 {
for _, pair := range hexagrams {
if pair[0] == gua1 {
changedHexagram = pair[1]
break
}
}
} else if movingLine == 2 {
for _, pair := range hexagrams {
if pair[0] == gua2 {
changedHexagram = pair[1]
break
}
}
}
changedHexagram += gua2
return changedHexagram
}
func wuxingAnalysis(birthYear, birthMonth, birthDay, birthHour int) (baZi string, elementCounts [5]int, healthSuggestions string) {
yearStems := []string{"甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"}
yearBranches := []string{"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"}
yearIndex := (birthYear - 4) % 60
yearStem := yearStems[yearIndex/12]
yearBranch := yearBranches[yearIndex%12]
monthOffsets := []int{0, 0, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
monthIndex := monthOffsets[birthMonth] + yearIndex/12
monthStem := yearStems[monthIndex%10]
monthBranch := yearBranches[(yearIndex%12+monthOffsets[birthMonth])%12]
baseDate := 693901
daysInMonth := []int{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
for y := 1900; y < birthYear; y++ {
if (y%4 == 0 && y%100 != 0) || (y%400 == 0) {
baseDate += 366
} else {
baseDate += 365
}
}
for m := 1; m < birthMonth; m++ {
baseDate += daysInMonth[m]
if m == 2 && ((birthYear%4 == 0 && birthYear%100 != 0) || (birthYear%400 == 0)) {
baseDate += 1
}
}
baseDate += birthDay
dayIndex := (baseDate + 1) % 60
dayStem := yearStems[dayIndex/12]
dayBranch := yearBranches[dayIndex%12]
timeBranches := []string{"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"}
timeBranchIndex := (birthHour - 1) / 2
timeBranch := timeBranches[timeBranchIndex]
baZi = fmt.Sprintf("%s%s %s%s %s%s %s", yearStem, yearBranch, monthStem, monthBranch, dayStem, dayBranch, timeBranch)
elements := []string{"甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"}
elementTypes := []string{"木", "木", "火", "火", "土", "土", "金", "金", "水", "水"}
for _, char := range baZi {
charStr := string(char)
for j, elem := range elements {
if charStr == elem {
switch elementTypes[j] {
case "木":
elementCounts[0]++
case "火":
elementCounts[1]++
case "土":
elementCounts[2]++
case "金":
elementCounts[3]++
case "水":
elementCounts[4]++
}
}
}
}
if elementCounts[2] < 2 {
healthSuggestions += "土弱:需注意脾胃功能,饮食宜温补(如山药、小米),避免生冷。n"
}
if elementCounts[0] < 2 {
healthSuggestions += "木弱:可增加绿色蔬菜摄入,适度运动疏肝。n"
}
if elementCounts[3] > 2 {
healthSuggestions += "金旺:需防止过劳,注意肺部健康。n"
}
if elementCounts[1] < 2 {
healthSuggestions += "火弱:适当食用辛辣食物,保持身体温暖。n"
}
if elementCounts[4] < 2 {
healthSuggestions += "水弱:多喝水,保持体内水分充足。n"
}
return baZi, elementCounts, healthSuggestions
}
func main() {
birthYear := 1981
birthMonth := 8
birthDay := 19
birthHour := 14 // 未时(13:00-15:00)
queryYear := "乙巳"
queryMonth := 2
queryDay := 12
queryHour := 8 // 卯时(5:00-7:00)
originalHexagram, changedHexagram, movingLineRemainder := meihuaYishu(queryYear, queryMonth, queryDay, queryHour)
baZi, elementCounts, healthSuggestions := wuxingAnalysis(birthYear, birthMonth, birthDay, birthHour)
fmt.Printf("本卦: %s, 变卦: %s, 动爻位置: %dn", originalHexagram, changedHexagram, movingLineRemainder)
fmt.Printf("八字: %sn", baZi)
fmt.Printf("五行分布: ")
fmt.Printf("木: %d ", elementCounts[0])
fmt.Printf("火: %d ", elementCounts[1])
fmt.Printf("土: %d ", elementCounts[2])
fmt.Printf("金: %d ", elementCounts[3])
fmt.Printf("水: %d n", elementCounts[4])
fmt.Print(healthSuggestions)
#include
#include
const char* get_gua_number(int number) {
switch (number) {
case 1: return "乾";
case 2: return "兑";
case 3: return "离";
case 4: return "震";
case 5: return "巽";
case 6: return "坎";
case 7: return "艮";
case 0: return "坤";
default: return "";
}
}
void meihua_yishu(const char* year, int month, int day, int hour, char* original_hexagram, char* changed_hexagram, int* moving_line_remainder) {
int earth_branches[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
const char* branch_names[] = {"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"};
int year_branch = 0;
for (int i = 0; i < 12; i++) {
if (strcmp(branch_names[i], &year[strlen(year) - 1]) == 0) {
year_branch = earth_branches[i];
break;
}
}
int upper_trigram_sum = year_branch + month + day;
int upper_trigram_remainder = upper_trigram_sum % 8;
int lower_trigram_sum = upper_trigram_sum + hour;
int lower_trigram_remainder = lower_trigram_sum % 8;
*moving_line_remainder = lower_trigram_sum % 6;
strcpy(original_hexagram, get_gua_number(upper_trigram_remainder));
strcat(original_hexagram, get_gua_number(lower_trigram_remainder));
get_changed_hexagram(original_hexagram, *moving_line_remainder, changed_hexagram);
}
void get_changed_hexagram(const char* hexagram, int moving_line, char* changed_hexagram) {
const char* hexagrams[][2] = {
{"乾", "兌"}, {"兑", "離"}, {"離", "震"}, {"震", "巽"},
{"巽", "坎"}, {"坎", "艮"}, {"艮", "坤"}, {"坤", "乾"}
};
char gua1[4], gua2[4];
strncpy(gua1, hexagram, 2); gua1[2] = '0';
strncpy(gua2, hexagram + 2, 2); gua2[2] = '0';
if (moving_line == 1) {
for (int i = 0; i < 8; i++) {
if (strcmp(hexagrams[i][0], gua1) == 0) {
strcpy(changed_hexagram, hexagrams[i][1]);
break;
}
}
} else if (moving_line == 2) {
for (int i = 0; i < 8; i++) {
if (strcmp(hexagrams[i][0], gua2) == 0) {
strcpy(changed_hexagram, hexagrams[i][1]);
break;
}
}
}
strcat(changed_hexagram, gua2);
}
void wuxing_analysis(int birth_year, int birth_month, int birth_day, int birth_hour, char* ba_zi, int* element_counts, char* health_suggestions) {
const char* year_stems[] = {"甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"};
const char* year_branches[] = {"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"};
int year_index = (birth_year - 4) % 60;
const char* year_stem = year_stems[year_index / 12];
const char* year_branch = year_branches[year_index % 12];
int month_offsets[] = {0, 0, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int month_index = month_offsets[birth_month] + year_index / 12;
const char* month_stem = year_stems[month_index % 10];
const char* month_branch = year_branches[(year_index % 12 + month_offsets[birth_month]) % 12];
int base_date = 693901;
int days_in_month[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
for (int y = 1900; y < birth_year; y++) {
if ((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0)) {
base_date += 366;
} else {
base_date += 365;
}
}
for (int m = 1; m < birth_month; m++) {
base_date += days_in_month[m];
if (m == 2 && ((birth_year % 4 == 0 && birth_year % 100 != 0) || (birth_year % 400 == 0))) {
base_date += 1;
}
}
base_date += birth_day;
int day_index = (base_date + 1) % 60;
const char* day_stem = year_stems[day_index / 12];
const char* day_branch = year_branches[day_index % 12];
const char* time_branches[] = {"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"};
int time_branch_index = (birth_hour - 1) / 2;
const char* time_branch = time_branches[time_branch_index];
sprintf(ba_zi, "%s%s %s%s %s%s %s", year_stem, year_branch, month_stem, month_branch, day_stem, day_branch, time_branch);
const char* elements[] = {"甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"};
const char* element_types[] = {"木", "木", "火", "火", "土", "土", "金", "金", "水", "水"};
memset(element_counts, 0, sizeof(int) * 5);
for (int i = 0; i < strlen(ba_zi); i++) {
char char_str[3];
snprintf(char_str, 3, "%c", ba_zi[i]);
for (int j = 0; j < 10; j++) {
if (strcmp(elements[j], char_str) == 0) {
if (strcmp(element_types[j], "木") == 0) element_counts[0]++;
else if (strcmp(element_types[j], "火") == 0) element_counts[1]++;
else if (strcmp(element_types[j], "土") == 0) element_counts[2]++;
else if (strcmp(element_types[j], "金") == 0) element_counts[3]++;
else if (strcmp(element_types[j], "水") == 0) element_counts[4]++;
}
}
}
health_suggestions[0] = '0';
if (element_counts[2] < 2) {
strcat(health_suggestions, "土弱:需注意脾胃功能,饮食宜温补(如山药、小米),避免生冷。n");
}
if (element_counts[0] < 2) {
strcat(health_suggestions, "木弱:可增加绿色蔬菜摄入,适度运动疏肝。n");
}
if (element_counts[3] > 2) {
strcat(health_suggestions, "金旺:需防止过劳,注意肺部健康。n");
}
if (element_counts[1] < 2) {
strcat(health_suggestions, "火弱:适当食用辛辣食物,保持身体温暖。n");
}
if (element_counts[4] < 2) {
strcat(health_suggestions, "水弱:多喝水,保持体内水分充足。n");
}
}
int main() {
int birth_year = 1981;
int birth_month = 8;
int birth_day = 19;
int birth_hour = 14; // 未时(13:00-15:00)
const char* query_year = "乙巳";
int query_month = 2;
int query_day = 12;
int query_hour = 8; // 卯时(5:00-7:00)
char original_hexagram[5];
char changed_hexagram[5];
int moving_line_remainder;
meihua_yishu(query_year, query_month, query_day, query_hour, original_hexagram, changed_hexagram, &moving_line_remainder);
char ba_zi[20];
int element_counts[5];
char health_suggestions[200];
wuxing_analysis(birth_year, birth_month, birth_day, birth_hour, ba_zi, element_counts, health_suggestions);
printf("本卦: %s, 变卦: %s, 动爻位置: %dn", original_hexagram, changed_hexagram, moving_line_remainder);
printf("八字: %sn", ba_zi);
printf("五行分布: ");
printf("木: %d ", element_counts[0]);
printf("火: %d ", element_counts[1]);
printf("土: %d ", element_counts[2]);
printf("金: %d ", element_counts[3]);
printf("水: %d n", element_counts[4]);
printf("%s", health_suggestions);
return 0;
}
#!/bin/bash
get_gua_number() {
local number=$1
case $number in
1) echo "乾" ;;
2) echo "兑" ;;
3) echo "离" ;;
4) echo "震" ;;
5) echo "巽" ;;
6) echo "坎" ;;
7) echo "艮" ;;
0) echo "坤" ;;
esac
}
meihua_yishu() {
local year=$1
local month=$2
local day=$3
local hour=$4
declare -A earth_branches=(
["子"]=1 ["丑"]=2 ["寅"]=3 ["卯"]=4
["辰"]=5 ["巳"]=6 ["午"]=7 ["未"]=8
["申"]=9 ["酉"]=10 ["戌"]=11 ["亥"]=12
)
local year_branch=${earth_branches[${year: -1}]:-0}
local upper_trigram_sum=$((year_branch + month + day))
local upper_trigram_remainder=$((upper_trigram_sum % 8))
local lower_trigram_sum=$((upper_trigram_sum + hour))
local lower_trigram_remainder=$((lower_trigram_sum % 8))
local moving_line_remainder=$((lower_trigram_sum % 6))
local original_hexagram=$(get_gua_number $upper_trigram_remainder)$(get_gua_number $lower_trigram_remainder)
local changed_hexagram=$(get_changed_hexagram "$original_hexagram" $moving_line_remainder)
echo "$original_hexagram" "$changed_hexagram" "$moving_line_remainder"
}
get_changed_hexagram() {
local hexagram=$1
local moving_line=$2
declare -A hexagrams=(
["乾"]="乾 兌" ["兑"]="兑 離"
["離"]="離 震" ["震"]="震 巽"
["巽"]="巽 坎" ["坎"]="坎 艮"
["艮"]="艮 坤" ["坤"]="坤 乾"
)
IFS=' ' read -r -a result <<< "$hexagram"
if [ "$moving_line" -eq 1 ]; then
result[0]=${hexagrams[$result][1]}
elif [ "$moving_line" -eq 2 ]; then
result[1]=${hexagrams[$result][1]}
fi
echo "${result[@]}"
}
wuxing_analysis() {
local birth_year=$1
local birth_month=$2
local birth_day=$3
local birth_hour=$4
local year_stems=("甲" "乙" "丙" "丁" "戊" "己" "庚" "辛" "壬" "癸")
local year_branches=("子" "丑" "寅" "卯" "辰" "巳" "午" "未" "申" "酉" "戌" "亥")
local year_index=$(( (birth_year - 4) % 60 ))
local year_stem=${year_stems[$((year_index / 12))]}
local year_branch=${year_branches[$((year_index % 12))]}
local month_offsets=(0 0 11 12 1 2 3 4 5 6 7 8 9 10)
local month_index=$(( month_offsets[birth_month] + year_index / 12 ))
local month_stem=${year_stems[$((month_index % 10))]}
local month_branch=${year_branches[$(((year_index % 12 + month_offsets[birth_month]) % 12))]}
local base_date=693901
local days_in_month=(0 31 28 31 30 31 30 31 31 30 31 30 31)
for (( y = 1900; y < birth_year; y++ )); do
if (( (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0) )); then
base_date=$((base_date + 366))
else
base_date=$((base_date + 365))
fi
done
for (( m = 1; m < birth_month; m++ )); do
base_date=$((base_date + days_in_month[m]))
if (( m == 2 )) && (( (birth_year % 4 == 0 && birth_year % 100 != 0) || (birth_year % 400 == 0) )); then
base_date=$((base_date + 1))
fi
done
base_date=$((base_date + birth_day))
local day_index=$(( (base_date + 1) % 60 ))
local day_stem=${year_stems[$((day_index / 12))]}
local day_branch=${year_branches[$((day_index % 12))]}
local time_branches=("子" "丑" "寅" "卯" "辰" "巳" "午" "未" "申" "酉" "戌" "亥")
local time_branch_index=$(( (birth_hour - 1) / 2 ))
local time_branch=${time_branches[$time_branch_index]}
local ba_zi="$year_stem$year_branch $month_stem$month_branch $day_stem$day_branch $time_branch"
declare -A elements=(
["甲"]="木" ["乙"]="木" ["丙"]="火" ["丁"]="火"
["戊"]="土" ["己"]="土" ["庚"]="金" ["辛"]="金"
["壬"]="水" ["癸"]="水"
)
declare -A element_counts=(
["木"]=0 ["火"]=0 ["土"]=0 ["金"]=0 ["水"]=0
)
for (( i=0; i<${#ba_zi}; i++ )); do
char="${ba_zi:$i:1}"
if [[ -n "${elements[$char]}" ]]; then
element_counts[${elements[$char]}]=$((element_counts[${elements[$char]}] + 1))
fi
done
local health_suggestions=""
if (( element_counts["土"] < 2 )); then
health_suggestions+="土弱:需注意脾胃功能,饮食宜温补(如山药、小米),避免生冷。n"
fi
if (( element_counts["木"] < 2 )); then
health_suggestions+="木弱:可增加绿色蔬菜摄入,适度运动疏肝。n"
fi
if (( element_counts["金"] > 2 )); then
health_suggestions+="金旺:需防止过劳,注意肺部健康。n"
fi
if (( element_counts["火"] < 2 )); then
health_suggestions+="火弱:适当食用辛辣食物,保持身体温暖。n"
fi
if (( element_counts["水"] < 2 )); then
health_suggestions+="水弱:多喝水,保持体内水分充足。n"
fi
echo "$ba_zi"
for key in "${!element_counts[@]}"; do
echo "$key: ${element_counts[$key]}"
done
echo -e "$health_suggestions"
}
# 示例调用
birth_year=1981
birth_month=8
birth_day=19
birth_hour=14 # 未时(13:00-15:00)
query_year="乙巳"
query_month=2
query_day=12
query_hour=8 # 卯时(5:00-7:00)
read original_hexagram changed_hexagram moving_line_remainder < <(meihua_yishu "$query_year" "$query_month" "$query_day" "$query_hour")
ba_zi=$(wuxing_analysis "$birth_year" "$birth_month" "$birth_day" "$birth_hour")
echo "本卦: $original_hexagram, 变卦: $changed_hexagram, 动爻位置: $moving_line_remainder"
echo "八字: $ba_zi"
"乾", 2 => "兑", 3 => "离", 4 => "震",
5 => "巽", 6 => "坎", 7 => "艮", 0 => "坤"
];
return $guaMap[$number];
}
function meihuaYishu($year, $month, $day, $hour) {
// 地支数字映射
$earthBranches = [
"子" => 1, "丑" => 2, "寅" => 3, "卯" => 4,
"辰" => 5, "巳" => 6, "午" => 7, "未" => 8,
"申" => 9, "酉" => 10, "戌" => 11, "亥" => 12
];
// 获取年份的地支数字
$yearBranch = isset($earthBranches[substr($year, -1)]) ? $earthBranches[substr($year, -1)] : 0;
// 计算上卦
$upperTrigramSum = $yearBranch + $month + $day;
$upperTrigramRemainder = $upperTrigramSum % 8;
// 计算下卦
$lowerTrigramSum = $upperTrigramSum + $hour;
$lowerTrigramRemainder = $lowerTrigramSum % 8;
// 计算动爻
$movingLineRemainder = $lowerTrigramSum % 6;
// 确定本卦和变卦
$originalHexagram = getGuaNumber($upperTrigramRemainder) . getGuaNumber($lowerTrigramRemainder);
$changedHexagram = getChangedHexagram($originalHexagram, $movingLineRemainder);
return [$originalHexagram, $changedHexagram, $movingLineRemainder];
}
function getChangedHexagram($hexagram, $movingLine) {
$hexagrams = [
"乾" => ["乾", "兌"], "兑" => ["兑", "離"],
"離" => ["離", "震"], "震" => ["震", "巽"],
"巽" => ["巽", "坎"], "坎" => ["坎", "艮"],
"艮" => ["艮", "坤"], "坤" => ["坤", "乾"]
];
$result = str_split($hexagram);
if ($movingLine === 1) {
$result[0] = $hexagrams[$result[0]][1];
} elseif ($movingLine === 2) {
$result[1] = $hexagrams[$result[1]][1];
}
return implode('', $result);
}
function wuxingAnalysis($birthYear, $birthMonth, $birthDay, $birthHour) {
// 年干支
$yearStems = ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"];
$yearBranches = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"];
$yearIndex = ($birthYear - 4) % 60;
$yearStem = $yearStems[floor($yearIndex / 12)];
$yearBranch = $yearBranches[$yearIndex % 12];
// 月干支
$monthOffsets = [0, 0, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$monthIndex = $monthOffsets[$birthMonth] + floor($yearIndex / 12);
$monthStem = $yearStems[$monthIndex % 10];
$monthBranch = $yearBranches[($yearIndex % 12 + $monthOffsets[$birthMonth]) % 12];
// 日干支
$baseDate = 1900 * 365 + floor(1900 / 4) - floor(1900 / 100) + floor(1900 / 400) + 1900 * 12 + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31 + 18; // 从1900年1月1日开始计算
$daysInMonth = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
for ($y = 1900; $y < $birthYear; $y++) {
$baseDate += 365 + (($y % 4 === 0 && $y % 100 !== 0) || ($y % 400 === 0) ? 1 : 0);
}
for ($m = 1; $m < $birthMonth; $m++) {
$baseDate += $daysInMonth[$m] + (($m === 2) && (($birthYear % 4 === 0 && $birthYear % 100 !== 0) || ($birthYear % 400 === 0)) ? 1 : 0);
}
$baseDate += $birthDay;
$dayIndex = ($baseDate + 1) % 60;
$dayStem = $yearStems[floor($dayIndex / 12)];
$dayBranch = $yearBranches[$dayIndex % 12];
// 时干支
$timeBranches = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"];
$timeBranchIndex = floor(($birthHour - 1) / 2);
$timeBranch = $timeBranches[$timeBranchIndex];
// 八字
$baZi = "$yearStem$yearBranch $monthStem$monthBranch $dayStem$dayBranch $timeBranch";
// 五行分析
$elements = [
'甲' => '木', '乙' => '木', '丙' => '火', '丁' => '火',
'戊' => '土', '己' => '土', '庚' => '金', '辛' => '金',
'壬' => '水', '癸' => '水'
];
$elementCounts = ['木' => 0, '火' => 0, '土' => 0, '金' => 0, '水' => 0];
foreach (str_split($baZi) as $char) {
if (isset($elements[$char])) {
$elementCounts[$elements[$char]]++;
}
}
// 健康建议
$healthSuggestions = '';
if ($elementCounts['土'] < 2) {
$healthSuggestions .= "土弱:需注意脾胃功能,饮食宜温补(如山药、小米),避免生冷。n";
}
if ($elementCounts['木'] < 2) {
$healthSuggestions .= "木弱:可增加绿色蔬菜摄入,适度运动疏肝。n";
}
if ($elementCounts['金'] > 2) {
$healthSuggestions .= "金旺:需防止过劳,注意肺部健康。n";
}
if ($elementCounts['火'] < 2) {
$healthSuggestions .= "火弱:适当食用辛辣食物,保持身体温暖。n";
}
if ($elementCounts['水'] < 2) {
$healthSuggestions .= "水弱:多喝水,保持体内水分充足。n";
}
return [$baZi, $elementCounts, $healthSuggestions];
}
// 示例调用
$birthYear = 1981;
$birthMonth = 8;
$birthDay = 19;
$birthHour = 14; // 未时(13:00-15:00)
$queryYear = "乙巳";
$queryMonth = 2;
$queryDay = 12;
$queryHour = 8; // 卯时(5:00-7:00)
list($originalHexagram, $changedHexagram, $movingLineRemainder) = meihuaYishu($queryYear, $queryMonth, $queryDay, $queryHour);
list($baZi, $elementCounts, $healthSuggestions) = wuxingAnalysis($birthYear, $birthMonth, $birthDay, $birthHour);
echo "本卦: $originalHexagram, 变卦: $changedHexagram, 动爻位置: $movingLineRemaindern";
echo "八字: $baZin";
echo "五行分布: ";
foreach ($elementCounts as $element => $count) {
echo "$element: $count ";
}
echo "n";
echo $healthSuggestions;
?>
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
int birthYear = 1981;
int birthMonth = 8;
int birthDay = 19;
int birthHour = 14; // 未时(13:00-15:00)
string queryYear = "乙巳";
int queryMonth = 2;
int queryDay = 12;
int queryHour = 8; // 卯时(5:00-7:00)
var meihuaResult = MeihuaYishu(queryYear, queryMonth, queryDay, queryHour);
string originalHexagram = meihuaResult.Item1;
string changedHexagram = meihuaResult.Item2;
int movingLineRemainder = meihuaResult.Item3;
var wuxingAnalysisResult = WuxingAnalysis(birthYear, birthMonth, birthDay, birthHour);
string baZi = wuxingAnalysisResult.Item1;
Dictionary elementCounts = wuxingAnalysisResult.Item2;
string healthSuggestions = wuxingAnalysisResult.Item3;
Console.WriteLine($"本卦: {originalHexagram}, 变卦: {changedHexagram}, 动爻位置: {movingLineRemainder}");
Console.WriteLine($"八字: {baZi}");
Console.Write("五行分布: ");
foreach (var pair in elementCounts)
{
Console.Write($"{pair.Key}: {pair.Value} ");
}
Console.WriteLine();
Console.WriteLine(healthSuggestions);
}
static string GetGuaNumber(int number)
{
Dictionary guaMap = new Dictionary
{
{1, "乾"}, {2, "兑"}, {3, "离"}, {4, "震"},
{5, "巽"}, {6, "坎"}, {7, "艮"}, {0, "坤"}
};
return guaMap[number];
}
static Tuple MeihuaYishu(string year, int month, int day, int hour)
{
// 地支数字映射
Dictionary earthBranches = new Dictionary
{
{"子", 1}, {"丑", 2}, {"寅", 3}, {"卯", 4},
{"辰", 5}, {"巳", 6}, {"午", 7}, {"未", 8},
{"申", 9}, {"酉", 10}, {"戌", 11}, {"亥", 12}
};
// 获取年份的地支数字
int yearBranch = earthBranches.ContainsKey(year.Substring(year.Length - 1)) ? earthBranches[year.Substring(year.Length - 1)] : 0;
// 计算上卦
int upperTrigramSum = yearBranch + month + day;
int upperTrigramRemainder = upperTrigramSum % 8;
// 计算下卦
int lowerTrigramSum = upperTrigramSum + hour;
int lowerTrigramRemainder = lowerTrigramSum % 8;
// 计算动爻
int movingLineRemainder = lowerTrigramSum % 6;
// 确定本卦和变卦
string originalHexagram = GetGuaNumber(upperTrigramRemainder) + GetGuaNumber(lowerTrigramRemainder);
string changedHexagram = GetChangedHexagram(originalHexagram, movingLineRemainder);
return Tuple.Create(originalHexagram, changedHexagram, movingLineRemainder);
}
static string GetChangedHexagram(string hexagram, int movingLine)
{
Dictionary> hexagrams = new Dictionary>
{
{"乾", new List { "乾", "兌" } }, {"兑", new List { "兑", "離" } },
{"離", new List { "離", "震" } }, {"震", new List { "震", "巽" } },
{"巽", new List { "巽", "坎" } }, {"坎", new List { "坎", "艮" } },
{"艮", new List { "艮", "坤" } }, {"坤", new List { "坤", "乾" } }
};
char[] result = hexagram.ToCharArray();
if (movingLine == 1)
{
result[0] = hexagrams[result[0].ToString()][1][0];
}
else if (movingLine == 2)
{
result[1] = hexagrams[result[1].ToString()][1][0];
}
return new string(result);
}
static Tuple, string> WuxingAnalysis(int birthYear, int birthMonth, int birthDay, int birthHour)
{
// 年干支
string[] yearStems = { "甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸" };
string[] yearBranches = { "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥" };
int yearIndex = (birthYear - 4) % 60;
string yearStem = yearStems[yearIndex / 12];
string yearBranch = yearBranches[yearIndex % 12];
// 月干支
int[] monthOffsets = { 0, 0, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int monthIndex = monthOffsets[birthMonth] + (yearIndex / 12);
string monthStem = yearStems[monthIndex % 10];
string monthBranch = yearBranches[(yearIndex % 12 + monthOffsets[birthMonth]) % 12];
// 日干支
int baseDate = 1900 * 365 + (1900 / 4) - (1900 / 100) + (1900 / 400) + 1900 * 12 + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31 + 18; // 从1900年1月1日开始计算
int[] daysInMonth = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
for (int y = 1900; y < birthYear; y++)
{
baseDate += 365 + ((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0) ? 1 : 0);
}
for (int m = 1; m < birthMonth; m++)
{
baseDate += daysInMonth[m] + ((m == 2) && ((birthYear % 4 == 0 && birthYear % 100 != 0) || (birthYear % 400 == 0)) ? 1 : 0);
}
baseDate += birthDay;
int dayIndex = (baseDate + 1) % 60;
string dayStem = yearStems[dayIndex / 12];
string dayBranch = yearBranches[dayIndex % 12];
// 时干支
string[] timeBranches = { "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥" };
int timeBranchIndex = (birthHour - 1) / 2;
string timeBranch = timeBranches[timeBranchIndex];
// 八字
string baZi = $"{yearStem}{yearBranch} {monthStem}{monthBranch} {dayStem}{dayBranch} {timeBranch}";
// 五行分析
Dictionary elements = new Dictionary
{
{'甲', "木"}, {'乙', "木"}, {'丙', "火"}, {'丁', "火"},
{'戊', "土"}, {'己', "土"}, {'庚', "金"}, {'辛', "金"},
{'壬', "水"}, {'癸', "水"}
};
Dictionary elementCounts = new Dictionary
{
{"木", 0}, {"火", 0}, {"土", 0}, {"金", 0}, {"水", 0}
};
foreach (char c in baZi)
{
if (elements.ContainsKey(c))
{
elementCounts[elements[c]]++;
}
}
// 健康建议
string healthSuggestions = "";
if (elementCounts["土"] < 2)
{
healthSuggestions += "土弱:需注意脾胃功能,饮食宜温补(如山药、小米),避免生冷。n";
}
if (elementCounts["木"] < 2)
{
healthSuggestions += "木弱:可增加绿色蔬菜摄入,适度运动疏肝。n";
}
if (elementCounts["金"] > 2)
{
healthSuggestions += "金旺:需防止过劳,注意肺部健康。n";
}
if (elementCounts["火"] < 2)
{
healthSuggestions += "火弱:适当食用辛辣食物,保持身体温暖。n";
}
if (elementCounts["水"] < 2)
{
healthSuggestions += "水弱:多喝水,保持体内水分充足。n";
}
return Tuple.Create(baZi, elementCounts, healthSuggestions);
}
function getGuaNumber(number: number): string {
const guaMap: { [key: number]: string } = {1: "乾", 2: "兑", 3: "离", 4: "震", 5: "巽", 6: "坎", 7: "艮", 0: "坤"};
return guaMap[number];
}
function meihuaYishu(year: string, month: number, day: number, hour: number): [string, string, number] {
// 地支数字映射
const earthBranches: { [key: string]: number } = {"子": 1, "丑": 2, "寅": 3, "卯": 4, "辰": 5, "巳": 6,
"午": 7, "未": 8, "申": 9, "酉": 10, "戌": 11, "亥": 12};
// 获取年份的地支数字
const yearBranch = earthBranches[year.slice(-1)] || 0;
// 计算上卦
const upperTrigramSum = yearBranch + month + day;
const upperTrigramRemainder = upperTrigramSum % 8;
// 计算下卦
const lowerTrigramSum = upperTrigramSum + hour;
const lowerTrigramRemainder = lowerTrigramSum % 8;
// 计算动爻
const movingLineRemainder = lowerTrigramSum % 6;
// 确定本卦和变卦
const originalHexagram = getGuaNumber(upperTrigramRemainder) + getGuaNumber(lowerTrigramRemainder);
const changedHexagram = getChangedHexagram(originalHexagram, movingLineRemainder);
return [originalHexagram, changedHexagram, movingLineRemainder];
}
function getChangedHexagram(hexagram: string, movingLine: number): string {
const hexagrams: { [key: string]: [string, string] } = {
"乾": ["乾", "兌"], "兑": ["兑", "離"],
"離": ["離", "震"], "震": ["震", "巽"],
"巽": ["巽", "坎"], "坎": ["坎", "艮"],
"艮": ["艮", "坤"], "坤": ["坤", "乾"]
};
let result = hexagram.split('');
if (movingLine === 1) {
result[0] = hexagrams[result[0]][1];
} else if (movingLine === 2) {
result[1] = hexagrams[result[1]][1];
}
return result.join('');
}
type ElementCounts = { [key: string]: number };
function wuxingAnalysis(birthYear: number, birthMonth: number, birthDay: number, birthHour: number): [string, ElementCounts, string] {
// 年干支
const yearStems = ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"];
const yearBranches = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"];
const yearIndex = (birthYear - 4) % 60;
const yearStem = yearStems[Math.floor(yearIndex / 12)];
const yearBranch = yearBranches[yearIndex % 12];
// 月干支
const monthOffsets = [0, 0, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const monthIndex = monthOffsets[birthMonth] + Math.floor(yearIndex / 12);
const monthStem = yearStems[monthIndex % 10];
const monthBranch = yearBranches[(yearIndex % 12 + monthOffsets[birthMonth]) % 12];
// 日干支
let baseDate = 1900 * 365 + Math.floor(1900 / 4) - Math.floor(1900 / 100) + Math.floor(1900 / 400) + 1900 * 12 + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31 + 18; // 从1900年1月1日开始计算
const daysInMonth = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
for (let y = 1900; y < birthYear; y++) {
baseDate += 365 + ((y % 4 === 0 && y % 100 !== 0) || (y % 400 === 0));
}
for (let m = 1; m < birthMonth; m++) {
baseDate += daysInMonth[m] + ((m === 2) && ((birthYear % 4 === 0 && birthYear % 100 !== 0) || (birthYear % 400 === 0)));
}
baseDate += birthDay;
const dayIndex = (baseDate + 1) % 60;
const dayStem = yearStems[Math.floor(dayIndex / 12)];
const dayBranch = yearBranches[dayIndex % 12];
// 时干支
const timeBranches = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"];
const timeBranchIndex = Math.floor((birthHour - 1) / 2);
const timeBranch = timeBranches[timeBranchIndex];
// 八字
const baZi = `${yearStem}${yearBranch} ${monthStem}${monthBranch} ${dayStem}${dayBranch} ${timeBranch}`;
// 五行分析
const elements: { [key: string]: string } = {'甲': '木', '乙': '木', '丙': '火', '丁': '火', '戊': '土', '己': '土',
'庚': '金', '辛': '金', '壬': '水', '癸': '水'};
const elementCounts: ElementCounts = {'木': 0, '火': 0, '土': 0, '金': 0, '水': 0};
for (const char of baZi) {
if (elements[char]) {
elementCounts[elements[char]]++;
}
}
// 健康建议
let healthSuggestions = '';
if (elementCounts['土'] < 2) {
healthSuggestions += "土弱:需注意脾胃功能,饮食宜温补(如山药、小米),避免生冷。n";
}
if (elementCounts['木'] < 2) {
healthSuggestions += "木弱:可增加绿色蔬菜摄入,适度运动疏肝。n";
}
if (elementCounts['金'] > 2) {
healthSuggestions += "金旺:需防止过劳,注意肺部健康。n";
}
if (elementCounts['火'] < 2) {
healthSuggestions += "火弱:适当食用辛辣食物,保持身体温暖。n";
}
if (elementCounts['水'] < 2) {
healthSuggestions += "水弱:多喝水,保持体内水分充足。n";
}
return [baZi, elementCounts, healthSuggestions];
}
// 示例调用
const birthYear = 1981;
const birthMonth = 8;
const birthDay = 19;
const birthHour = 14; // 未时(13:00-15:00)
const queryYear = "乙巳";
const queryMonth = 2;
const queryDay = 12;
const queryHour = 8; // 卯时(5:00-7:00)
const [originalHexagram, changedHexagram, movingLineRemainder] = meihuaYishu(queryYear, queryMonth, queryDay, queryHour);
const [baZi, elementCounts, healthSuggestions] = wuxingAnalysis(birthYear, birthMonth, birthDay, birthHour);
console.log(`本卦: ${originalHexagram}, 变卦: ${changedHexagram}, 动爻位置: ${movingLineRemainder}`);
console.log(`八字: ${baZi}`);
console.log("五行分布:", elementCounts);
console.log(healthSuggestions);
function getGuaNumber(number) {
const guaMap = {1: "乾", 2: "兑", 3: "离", 4: "震", 5: "巽", 6: "坎", 7: "艮", 0: "坤"};
return guaMap[number];
}
function meihuaYishu(year, month, day, hour) {
// 地支数字映射
const earthBranches = {"子": 1, "丑": 2, "寅": 3, "卯": 4, "辰": 5, "巳": 6,
"午": 7, "未": 8, "申": 9, "酉": 10, "戌": 11, "亥": 12};
// 获取年份的地支数字
const yearBranch = earthBranches[year.slice(-1)] || 0;
// 计算上卦
const upperTrigramSum = yearBranch + month + day;
const upperTrigramRemainder = upperTrigramSum % 8;
// 计算下卦
const lowerTrigramSum = upperTrigramSum + hour;
const lowerTrigramRemainder = lowerTrigramSum % 8;
// 计算动爻
const movingLineRemainder = lowerTrigramSum % 6;
// 确定本卦和变卦
const originalHexagram = getGuaNumber(upperTrigramRemainder) + getGuaNumber(lowerTrigramRemainder);
const changedHexagram = getChangedHexagram(originalHexagram, movingLineRemainder);
return [originalHexagram, changedHexagram, movingLineRemainder];
}
function getChangedHexagram(hexagram, movingLine) {
const hexagrams = {
"乾": ["乾", "兌"], "兑": ["兑", "離"],
"離": ["離", "震"], "震": ["震", "巽"],
"巽": ["巽", "坎"], "坎": ["坎", "艮"],
"艮": ["艮", "坤"], "坤": ["坤", "乾"]
};
let result = hexagram.split('');
if (movingLine === 1) {
result[0] = hexagrams[result[0]][1];
} else if (movingLine === 2) {
result[1] = hexagrams[result[1]][1];
}
return result.join('');
}
function wuxingAnalysis(birthYear, birthMonth, birthDay, birthHour) {
// 年干支
const yearStems = ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"];
const yearBranches = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"];
const yearIndex = (birthYear - 4) % 60;
const yearStem = yearStems[Math.floor(yearIndex / 12)];
const yearBranch = yearBranches[yearIndex % 12];
// 月干支
const monthOffsets = [0, 0, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const monthIndex = monthOffsets[birthMonth] + Math.floor(yearIndex / 12);
const monthStem = yearStems[monthIndex % 10];
const monthBranch = yearBranches[(yearIndex % 12 + monthOffsets[birthMonth]) % 12];
// 日干支
let baseDate = 1900 * 365 + Math.floor(1900 / 4) - Math.floor(1900 / 100) + Math.floor(1900 / 400) + 1900 * 12 + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31 + 18; // 从1900年1月1日开始计算
const daysInMonth = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
for (let y = 1900; y < birthYear; y++) {
baseDate += 365 + ((y % 4 === 0 && y % 100 !== 0) || (y % 400 === 0));
}
for (let m = 1; m < birthMonth; m++) {
baseDate += daysInMonth[m] + ((m === 2) && ((birthYear % 4 === 0 && birthYear % 100 !== 0) || (birthYear % 400 === 0)));
}
baseDate += birthDay;
const dayIndex = (baseDate + 1) % 60;
const dayStem = yearStems[Math.floor(dayIndex / 12)];
const dayBranch = yearBranches[dayIndex % 12];
// 时干支
const timeBranches = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"];
const timeBranchIndex = Math.floor((birthHour - 1) / 2);
const timeBranch = timeBranches[timeBranchIndex];
// 八字
const baZi = `${yearStem}${yearBranch} ${monthStem}${monthBranch} ${dayStem}${dayBranch} ${timeBranch}`;
// 五行分析
const elements = {'甲': '木', '乙': '木', '丙': '火', '丁': '火', '戊': '土', '己': '土',
'庚': '金', '辛': '金', '壬': '水', '癸': '水'};
const elementCounts = {'木': 0, '火': 0, '土': 0, '金': 0, '水': 0};
for (const char of baZi) {
if (elements[char]) {
elementCounts[elements[char]]++;
}
}
// 健康建议
let healthSuggestions = '';
if (elementCounts['土'] < 2) {
healthSuggestions += "土弱:需注意脾胃功能,饮食宜温补(如山药、小米),避免生冷。n";
}
if (elementCounts['木'] < 2) {
healthSuggestions += "木弱:可增加绿色蔬菜摄入,适度运动疏肝。n";
}
if (elementCounts['金'] > 2) {
healthSuggestions += "金旺:需防止过劳,注意肺部健康。n";
}
if (elementCounts['火'] < 2) {
healthSuggestions += "火弱:适当食用辛辣食物,保持身体温暖。n";
}
if (elementCounts['水'] < 2) {
healthSuggestions += "水弱:多喝水,保持体内水分充足。n";
}
return [baZi, elementCounts, healthSuggestions];
}
// 示例调用
const birthYear = 1981;
const birthMonth = 8;
const birthDay = 19;
const birthHour = 14; // 未时(13:00-15:00)
const queryYear = "乙巳";
const queryMonth = 2;
const queryDay = 12;
const queryHour = 8; // 卯时(5:00-7:00)
const [originalHexagram, changedHexagram, movingLineRemainder] = meihuaYishu(queryYear, queryMonth, queryDay, queryHour);
const [baZi, elementCounts, healthSuggestions] = wuxingAnalysis(birthYear, birthMonth, birthDay, birthHour);
console.log(`本卦: ${originalHexagram}, 变卦: ${changedHexagram}, 动爻位置: ${movingLineRemainder}`);
console.log(`八字: ${baZi}`);
console.log("五行分布:", elementCounts);
console.log(healthSuggestions);
#include
#include
#include
评论 (0)