ExcelHome技术论坛

 找回密码
 免费注册

QQ登录

只需一步,快速开始

快捷登录

搜索
EH技术汇-专业的职场技能充电站 妙哉!函数段子手趣味讲函数 Excel服务器-会Excel,做管理系统 效率神器,一键搞定繁琐工作
HR薪酬管理数字化实战 Excel 2021函数公式学习大典 Excel数据透视表实战秘技 打造核心竞争力的职场宝典
让更多数据处理,一键完成 数据工作者的案头书 免费直播课集锦 ExcelHome出品 - VBA代码宝免费下载
用ChatGPT与VBA一键搞定Excel WPS表格从入门到精通 Excel VBA经典代码实践指南
查看: 1070|回复: 3

代码注释-帮忙看下这段代码-九宫数

[复制链接]

TA的精华主题

TA的得分主题

发表于 2007-5-24 21:01 | 显示全部楼层 |阅读模式
本帖已被收录到知识树中,索引项:其他结构和算法

想用循环穷举写个简单的九宫数术求解代码,即数字1-9分布成正方形,横竖斜的和都是15 。但因太菜最终没成功,别人给写了个,可是有点看不懂,水平有限不要见笑。劳烦帮忙注释下!

Sub 1-9九宫数算法()

Const XX = 3
Const YY = 3
Dim matrix(XX, YY) As Integer
Dim i As Long
Dim x As Long
Dim y As Long
Dim tx As Long
Dim ty As Long
Dim index As Long

index = 1
x = XX - 1
y = (YY + 1) / 2 - 1

For i = 0 To XX * YY
matrix(i / XX, i Mod YY) = 0
Next i

For i = 1 To XX * YY
matrix(x, y) = index
tx = (x + 1) Mod XX
ty = (y + 1) Mod YY
If matrix(tx, ty) <> 0 Then
If x = 0 Then
x = XX
Else
x = x - 1
End If
Else
x = tx
y = ty
End If
index = index + 1
Next i

Dim str1 As String
For x = 0 To XX - 1
str1 = ""
For y = 0 To YY - 1
str1 = str1 + Str(matrix(x, y)) + " "
Next y

Debug.Print str1
Next x

End Sub

TA的精华主题

TA的得分主题

 楼主| 发表于 2007-5-24 22:35 | 显示全部楼层

这是我Q群的一个朋友,平时很少上线,所以就到这里来找人帮忙了,这种方法叫规划求解。逻辑性很强的

TA的精华主题

TA的得分主题

发表于 2007-5-25 14:16 | 显示全部楼层

N年前的习作,效率不高,但好理解:

'易知九宫图中间为5,关于中心对称位置之和为10,分析如下:

'       a        b        c


'       d        5      10-d


'       10-c    10-b    10-a

'if a is an odd,c is an odd ,then 10-a is an odd,10-c is odd,so b,d,10-d,10-b are all odds(paradox)
 
'if a is an odd,c is an even ,then 10-a is an odd,10-c is even,so b,d,10-d,10-b are all evens(paradox)

'if a is an even,c is an odd ,then 10-a is an even,10-c is odd,so b,d,10-d,10-b are all evens(paradox)

'if a is an even,c is an even ,then 10-a is an even,10-c is even,so b,d,10-d,10-b are all odds(maybe)

'so a ,c must be  evens;    b,d must be odds


Dim nine As New Collection
Private Sub Form_Load()
Dim a As Integer, b As Integer, c As Integer, d As Integer, i As Integer
For a = 2 To 8 Step 2
For b = 1 To 9 Step 2
For c = 2 To 8 Step 2
For d = 1 To 9 Step 2
If a + b + c = 15 And a + d - c = 5 And a + c <> 10 And b + d <> 10 And b <> 5 And d <> 5 Then nine.Add StrConv(a & b & c & vbCrLf & d & "5" & (10 - d) & vbCrLf & (10 - c) & (10 - b) & (10 - a), vbWide) '全角显示
Next: Next: Next: Next
For i = 1 To nine.Count
MsgBox nine(i), 64, "九宫图之" & i
Next
End Sub

TA的精华主题

TA的得分主题

发表于 2007-5-24 21:53 | 显示全部楼层

建议找原作者解释解释

里面的规律性太强,特别是1是固定的,可能有固定的算法

您需要登录后才可以回帖 登录 | 免费注册

本版积分规则

手机版|关于我们|联系我们|ExcelHome

GMT+8, 2024-12-5 02:47 , Processed in 0.040078 second(s), 8 queries , Gzip On, MemCache On.

Powered by Discuz! X3.4

© 1999-2023 Wooffice Inc.

沪公网安备 31011702000001号 沪ICP备11019229号-2

本论坛言论纯属发表者个人意见,任何违反国家相关法律的言论,本站将协助国家相关部门追究发言者责任!     本站特聘法律顾问:李志群律师

快速回复 返回顶部 返回列表