CodeCombat 数组迭代与极值查找

手动实现 `FindNearest` 和 `FindFarthest`(21-23关)

第 21 关

沙蛇 (Sand-Snakes)

战术思路分析:手动查找最近

英雄的 `findNearest` 技能在这片峡谷中被干扰了!你需要自己编写算法,遍历所有硬币并找出**距离最小**的那一个。

Min Search 算法(最小查找)

1. **初始化:** `nearestDistance = 9999` (设置一个比任何实际距离都大的起始值)。
2. **遍历与比较:** 循环遍历每个硬币,如果当前硬币的 `distance` **小于** `nearestDistance`,则更新 `nearest` 和 `nearestDistance`。

IF Dist < MinDist:
  MinDist = Dist
  Nearest = Coin

Python 程序解法

1
while True:
外层无限循环
2
coins = hero.findItems()
获取硬币列表
3
coinIndex = 0
初始化索引
4
nearest = None
初始化最近物品为 None
5
nearestDistance = 9999
初始化最小距离为极大值 (9999)
6
# 搜索所有的硬币,找到离你最近的那一颗。
7
while coinIndex < len(coins):
遍历列表
8
coin = coins[coinIndex]
获取当前硬币
9
coinIndex += 1
索引步进
10
distance = hero.distanceTo(coin)
计算距离
11
# 如果硬币与你的距离小于“最近距离(nearestDistance)”
12
if distance < nearestDistance:
进行距离比较
13
# 将 nearest 设置为 coin
14
nearest = coin
更新最近物品
15
# 将 nearestDistance 设置为 distance
16
nearestDistance = distance
更新最小距离
17
18
# 如果找到离你最近的硬币,移动到硬币的位置。
19
if nearest:
如果找到了最近的硬币
20
hero.moveXY(nearest.pos.x, nearest.pos.y)
移动到硬币的位置
第 22 关

奇数沙尘暴 (Odd Sandstorm)

战术思路分析:跳跃步进

列表中的朋友和敌人信息是**交替出现**的(偶数索引是敌人,奇数索引是朋友)。英雄只需要攻击敌人。

关键:索引 `+= 2`

让索引从 `0` 开始,每次循环增加 `2` (`enemyIndex += 2`),就能跳过朋友,只攻击敌人。

Start = 0
Index += 2

0 → 2 → 4

Python 程序解法

1
everybody = ['Yetu', 'Tabitha', 'Rasha', 'Max', 'Yazul', 'Todd']
数组包含朋友和兽人
2
enemyIndex = 0
初始化索引
3
4
while enemyIndex < len(everybody):
遍历列表
5
# 使用方括号从数组中得到兽人的名字
6
enemy = everybody[enemyIndex]
获取当前索引处的敌人
7
# 使用存有兽人名字的变量攻击
8
hero.attack(enemy)
攻击敌人
9
# 每次递增 2 来跳过朋友。
10
enemyIndex += 2
索引步进 **2**
11
12
hero.moveXY(36, 53)
移动到绿洲
第 23 关

疯狂的 Maxer (Mad Maxer)

战术思路分析:找出最远

靠近的敌人是诱饵,真正有威胁的是最远的敌人。你需要实现 **Max Search** 算法,找出 **距离最远** 的敌人。

Max Search 算法(最大查找)

1. **初始化:** `farthest = None`,`maxDistance = 0` (一个极小值)。
2. **遍历与比较:** 如果当前目标的 `distance` **大于** `maxDistance`,则更新 `farthest` 和 `maxDistance`。

IF Dist > MaxDist:
  MaxDist = Dist
  Farthest = Target

Python 程序解法

1
while True:
外层无限循环
2
farthest = None
初始化最远敌人
3
maxDistance = 0
初始化最大距离为 0
4
enemyIndex = 0
5
enemies = hero.findEnemies()
获取敌人列表
6
# 查看全部敌人,找出最远的那个。
7
while enemyIndex < len(enemies):
遍历敌人列表
8
target = enemies[enemyIndex]
获取当前敌人
9
enemyIndex += 1
索引步进
10
distance = hero.distanceTo(target)
计算距离
11
# 这个敌人是不是比我们看到的最远敌人还要远?
12
if distance > maxDistance:
进行距离比较
13
maxDistance = distance
更新 maxDistance
14
farthest = target
更新 farthest
15
16
if farthest:
如果找到了最远敌人
17
# 干掉最远的敌人!
18
while farthest.health > 0:
持续攻击直到死亡
19
hero.attack(farthest)
攻击