Go-基础实战Rewrite

求平方根

知识点:递归
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
package main

import (
"fmt"
)

func sqrtRecursive(x, guess, prevGuess, epsilon float64) float64 {
if diff := guess*guess - x; diff < epsilon && -diff < epsilon {
return guess
}

newGuess := (guess + x/guess) / 2
if newGuess == prevGuess {
return guess
}

return sqrtRecursive(x, newGuess, guess, epsilon)
}

func sqrt(x float64) float64 {
return sqrtRecursive(x, 1.0, 0.0, 1e-9)
}

func main() {
x := 25.0
result := sqrt(x)
fmt.Printf("%.2f 的平方根为 %.6f\n", x, result)
}

Go计算器

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
package queue

type Queue struct {
elements []interface{} //0永远为Top/Front
}

func (q *Queue) Push(item interface{}) {
q.elements = append(q.elements, item)
}

func (q *Queue) Pop() {
if !q.Empty() {
q.elements = q.elements[1:] //delete top
}
}

func (q *Queue) Front() interface{} {
if q.Empty() {
return nil //队列空返回nil
}
item := q.elements[0]
return item
}

func (q *Queue) Empty() bool {
return q.Size() == 0
}

func (q *Queue) Size() int {
return len(q.elements)
}

func (q *Queue) Clear() {
q.elements = make([]interface{}, 0)
}

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
package stack

type Stack struct {
//切片储存栈元素,i=len(elements)为top
elements []interface{}
}

func (s *Stack) Push(item interface{}) {
s.elements = append(s.elements, item)
}

func (s *Stack) Pop() {
if !s.Empty() {
lastIdx := len(s.elements) - 1
s.elements = s.elements[:lastIdx]
}
}

func (s *Stack) Top() interface{} {
if s.Empty() {
return nil
}
return s.elements[len(s.elements)-1]
}

func (s *Stack) Empty() bool {
return s.Size() == 0
}

func (s *Stack) Size() int {
return len(s.elements)
}

func (s *Stack) Clear() {
s.elements = make([]interface{}, 0)
}

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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package main

import (
"Redrock-lesson1/lv4-CounterProMax/queue"
"Redrock-lesson1/lv4-CounterProMax/stack"
"fmt"
"strconv"
"unicode"
)

var priority = map[rune]int{
'*': 2,
'/': 2,
'+': 1,
'-': 1,
}

func InToPost(in string, s *stack.Stack, q *queue.Queue) { // 中缀表达式转后缀表达式
s.Clear()
q.Clear()
for i := 0; i < len(in); i++ {
ch := rune(in[i])
switch {
case unicode.IsDigit(ch): // 如果是数字
endIdx := i
for j := i; j < len(in) && (in[j] == '.' || (in[j] >= '0' && in[j] <= '9')); j++ { // 扫描数字范围
endIdx = j // 标记endIndex
}
num := in[i : endIdx+1] // 储存数字
i = endIdx // 更新下标
n, err := strconv.ParseFloat(num, 64) // 字符串转浮点数
if err != nil {
}
q.Push(n) //将数字插入队列
case ch == '(': // 如果是左括号,则将左括号压入栈
s.Push(ch)
case ch == ')': // 如果是右括号,则弹出左括号前的所有栈元素
check := s.Top().(rune)
for check != '(' && !s.Empty() { // 弹出左括号前的所有栈元素
//fmt.Printf("---------ru = %c------------\n", ru)
q.Push(check) // 将运算符插入后缀表达式
s.Pop()
check = s.Top().(rune)
}
s.Pop() // 弹出左括号
case ch == '*' || ch == '/' || ch == '+' || ch == '-':
for !s.Empty() && priority[s.Top().(rune)] >= priority[ch] { // 当栈不为空且栈顶运算符优先级 >= 当前运算符优先级
ru := s.Top().(rune)
q.Push(ru)
s.Pop()
}
s.Push(ch) // 将当前运算符压入栈
}
}
for !s.Empty() { // 向队列插入剩余运算符
q.Push(s.Top())
s.Pop()
}
}

func PostCount(q *queue.Queue) float64 {
var s stack.Stack
var n1, n2, ans float64
for !q.Empty() { // 扫描队列元素
topElement := q.Front()
q.Pop()
switch v := topElement.(type) {
case float64: // 如果是数字
s.Push(v)
case rune: // 如果是操作符
n2 = s.Top().(float64)
s.Pop()
n1 = s.Top().(float64)
s.Pop() // 弹出两个元素
switch v { // 运算
case '+':
ans = n1 + n2
case '-':
ans = n1 - n2
case '*':
ans = n1 * n2
case '/':
ans = n1 / n2
}
s.Push(ans) // 将结果压回栈内
}
}
result := s.Top().(float64) // 栈顶元素为结果
s.Clear()
return result
}

func main() {
fmt.Printf("桓因使用Go语言计算器!\n请输入一个合法的算数表达式,例如:(3.14+2.71)*2/5\n输入exit退出程序")
var input string
for {
fmt.Printf("\n请输入:")
fmt.Scanln(&input)
if input == "exit" {
break
}
var q queue.Queue
var s stack.Stack
InToPost(input, &s, &q) // 中缀表达式转后缀表达式
/*for !q.Empty() {
value, ok := q.Front().(rune)
value2, ok2 := q.Front().(float64)
if ok {
fmt.Printf("%c ", value)
} else if ok2 {
fmt.Printf("%f ", value2)
}
q.Pop()
}*/
fmt.Printf("结果是%f\n", PostCount(&q)) // 后缀表达式求值
}
fmt.Printf("感谢使用!再见!\n")
}


DFS


回合制游戏

接口
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
package main

import "fmt"

// ==================== 核心接口定义 ====================

// Fighter 战斗角色接口
type Fighter interface {
Name() string
Health() int
TakeDamage(damage int)
IsAlive() bool
}

// Action 战斗行为接口
type Action interface {
Execute(actor, target Fighter)
Description() string
}

// ActionSelector 行动选择器接口
type ActionSelector interface {
SelectAction() Action
SelectTarget(opponents []Fighter) Fighter
}

// ==================== 角色结构体 ====================

// BaseCharacter 基础角色结构
type BaseCharacter struct {
name string
health int
}

func (c *BaseCharacter) Name() string {
return c.name
}

func (c *BaseCharacter) Health() int {
return c.health
}

func (c *BaseCharacter) TakeDamage(damage int) {
c.health -= damage
if c.health < 0 {
c.health = 0
}
}

func (c *BaseCharacter) IsAlive() bool {
return c.health > 0
}

// ==================== 具体角色实现 ====================

// Warrior 战士角色
type Warrior struct {
BaseCharacter
attack int
}

func NewWarrior(name string, health, attack int) *Warrior {
return &Warrior{
BaseCharacter: BaseCharacter{name: name, health: health},
attack: attack,
}
}

// Mage 法师角色
type Mage struct {
BaseCharacter
spellPower int
}

func NewMage(name string, health, spellPower int) *Mage {
return &Mage{
BaseCharacter: BaseCharacter{name: name, health: health},
spellPower: spellPower,
}
}

// ==================== 战斗行为实现 ====================

// AttackAction 普通攻击行为
type AttackAction struct {
damage int
}

func (a AttackAction) Execute(actor, target Fighter) {
target.TakeDamage(a.damage)
}

func (a AttackAction) Description() string {
return fmt.Sprintf("attacks for %d damage", a.damage)
}

// SpellAction 法术攻击行为
type SpellAction struct {
damage int
spellName string
}

func (s SpellAction) Execute(actor, target Fighter) {
target.TakeDamage(s.damage)
}

func (s SpellAction) Description() string {
return fmt.Sprintf("casts %s for %d damage", s.spellName, s.damage)
}

// HealAction 治疗行为
type HealAction struct {
amount int
}

func (h HealAction) Execute(actor, target Fighter) {
// 治疗目标(但不超过最大生命值)
target.(*BaseCharacter).health += h.amount
}

func (h HealAction) Description() string {
return fmt.Sprintf("heals for %d health", h.amount)
}

// ==================== 行动选择器实现 ====================

// WarriorActionSelector 战士行动选择器
type WarriorActionSelector struct {
warrior *Warrior
}

func (w WarriorActionSelector) SelectAction() Action {
// 战士总是选择攻击
return AttackAction{damage: w.warrior.attack}
}

func (w WarriorActionSelector) SelectTarget(opponents []Fighter) Fighter {
// 战士总是选择第一个存活的对手
for _, opp := range opponents {
if opp.IsAlive() {
return opp
}
}
return nil
}

// MageActionSelector 法师行动选择器
type MageActionSelector struct {
mage *Mage
}

func (m MageActionSelector) SelectAction() Action {
// 法师随机选择行动
actions := []Action{
SpellAction{damage: m.mage.spellPower, spellName: "Fireball"},
HealAction{amount: 20},
}
return actions[0] // 简化:总是选择第一个
}

func (m MageActionSelector) SelectTarget(opponents []Fighter) Fighter {
// 法师总是选择第一个存活的对手
for _, opp := range opponents {
if opp.IsAlive() {
return opp
}
}
return nil
}

// ==================== 战斗系统 ====================

// BattleSystem 战斗系统
type BattleSystem struct{}

func (bs BattleSystem) PerformTurn(actor Fighter, selector ActionSelector, opponents []Fighter) {
if !actor.IsAlive() {
return
}

// 选择行动和目标
action := selector.SelectAction()
target := selector.SelectTarget(opponents)

if target == nil {
return
}

// 执行行动
fmt.Printf("%s %s at %s! ", actor.Name(), action.Description(), target.Name())
action.Execute(actor, target)

// 显示结果
fmt.Printf("(%s health: %d)\n", target.Name(), target.Health())
}

// ==================== 主函数 ====================
func main() {
// 创建角色
warrior := NewWarrior("Arthur", 100, 15)
mage := NewMage("Merlin", 80, 25)

// 创建行动选择器
warriorSelector := WarriorActionSelector{warrior: warrior}
mageSelector := MageActionSelector{mage: mage}

// 创建战斗系统
battleSystem := BattleSystem{}

fmt.Println("===== Battle Start =====")

// 战士回合
battleSystem.PerformTurn(warrior, warriorSelector, []Fighter{mage})

// 法师回合
battleSystem.PerformTurn(mage, mageSelector, []Fighter{warrior})

// 战士回合
battleSystem.PerformTurn(warrior, warriorSelector, []Fighter{mage})

// 法师回合
battleSystem.PerformTurn(mage, mageSelector, []Fighter{warrior})

fmt.Println("===== Battle End =====")
fmt.Printf("%s health: %d\n", warrior.Name(), warrior.Health())
fmt.Printf("%s health: %d\n", mage.Name(), mage.Health())
}

哈希表

知识点:map、指针、结构体、range、数据结构
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package main

import (
"fmt"
)

type HashMap struct {
key string
value string
hashCode int
next *HashMap
}

var table [16](*HashMap)

func initTable() {
for i := range table{
table[i] = &HashMap{"","",i,nil}
}
}

func getInstance() [16](*HashMap){
if(table[0] == nil){
initTable()
}
return table
}

func genHashCode(k string) int{
if len(k) == 0{
return 0
}
var hashCode int = 0
var lastIndex int = len(k) - 1
for i := range k {
if i == lastIndex {
hashCode += int(k[i])
break
}
hashCode += (hashCode + int(k[i]))*31
}
return hashCode
}

func indexTable(hashCode int) int{
return hashCode%16
}

func indexNode(hashCode int) int {
return hashCode>>4
}

func put(k string, v string) string {
var hashCode = genHashCode(k)
var thisNode = HashMap{k,v,hashCode,nil}

var tableIndex = indexTable(hashCode)
var nodeIndex = indexNode(hashCode)

var headPtr [16](*HashMap) = getInstance()
var headNode = headPtr[tableIndex]

if (*headNode).key == "" {
*headNode = thisNode
return ""
}

var lastNode *HashMap = headNode
var nextNode *HashMap = (*headNode).next

for nextNode != nil && (indexNode((*nextNode).hashCode) < nodeIndex){
lastNode = nextNode
nextNode = (*nextNode).next
}
if (*lastNode).hashCode == thisNode.hashCode {
var oldValue string = lastNode.value
lastNode.value = thisNode.value
return oldValue
}
if lastNode.hashCode < thisNode.hashCode {
lastNode.next = &thisNode
}
if nextNode != nil {
thisNode.next = nextNode
}
return ""
}

func get(k string) string {
var hashCode = genHashCode(k)
var tableIndex = indexTable(hashCode)

var headPtr [16](*HashMap) = getInstance()
var node *HashMap = headPtr[tableIndex]

if (*node).key == k{
return (*node).value
}

for (*node).next != nil {
if k == (*node).key {
return (*node).value
}
node = (*node).next
}
return ""
}

//examples
func main() {
getInstance()
put("a","a_put")
put("b","b_put")
fmt.Println(get("a"))
fmt.Println(get("b"))
put("p","p_put")
fmt.Println(get("p"))
}