> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/ios/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/ios/swift-playgrounds/learn-to-code-2/pages/variables/round-up-the-switches.md).

# 計算開關數量

Round Up the Switches

這個關卡要我們先收集在第一個平台上的寶石，然後再到第二個平台上去打開相同數量的開關。

![](https://1830103165-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M5-JmwCZMKh_d7RfBaN%2F-M5RhwZGj6Iy2L2ayFae%2F-M5RkRyiyyoWvGdnWbCf%2Fround%20up%20the%20switches.PNG?alt=media\&token=1b339614-b504-4c79-84a6-c7ade5965688)

{% tabs %}
{% tab title="main" %}

```swift
// 變數初始化
var gems = 0
var switches = 0

// 策略：如果
// 1. 還沒收到寶石，或者是
// 2. 有收到寶石但開關數量比寶石少，
// 就繼續走
while gems == 0 || (gems > 0 && switches < gems) {
    walkAlongLeft {
        if isOnGem { 
            collectGem() 
            gems += 1
        }
        if isOnClosedSwitch {
            toggleSwitch()
            switches += 1
        }
    }
}
```

{% endtab %}

{% tab title="navigation" %}

```swift
// ⭐️ 貼著左邊走的策略，
//    將來可以寫入 Actor 的 extension 中。
func walkAlongLeft(handle:()->Void) {
    if !isBlockedLeft {
        turnLeft()
        moveForward()
        handle()
    } else if !isBlocked {
        moveForward()
        handle()
    } else {
        turnRight()
    }
}
```

{% endtab %}
{% endtabs %}
