DEV Community

Too Leng
Too Leng

Posted on

【ChaoCode】 Swift 基礎篇 10:Range 運算子作業

0…3 和 0..<3 的差別是什麼?

0…3 包含 3,0..<3 不包含 3。
任意兩個相同類型的值 a 和 b,要讓 a..<b 可以建立為一個 Range,需要滿足哪些條件?
需滿足一下兩個條件:

  1. 它們的類型必須是「可以被比較大小的」,因為 range 是照大小排序。
  2. a 小於或等於 b 所有類型的 Range 都一定有屬性 .lowerBound 嗎? 不,如果是只有結束位置的部分 Range 就沒有 lowerBound 的屬性。 例如 …4 或 ..<4。
import Foundation

// 【ChaoCode】 Swift 基礎篇 10:Range 運算子實作作業
//
// 1. 保羅在學校活動的時間是 7:00~13:00 點,艾莉在學校活動的時間是 12:30~17:00 點,溫蒂在學校活動的時間是 10:00~16:00 點,他們有辦法在學校碰面嗎?如果可以的話是幾點到幾點?
// ⚠️ 嘗試用下面提供的 formatter 讓你的數字一律印出兩位數,比方 1 應該印出 01。請用這種一律有兩位數的顯示方式來印出時間。例如 1 點 5 分應該是 01 點 05 分。
let 保羅時間 = 700..<1300
let 艾莉時間 = 1230..<1700
let 溫蒂時間 = 1000..<1600

let 共通時間 = 保羅時間.clamped(to: 艾莉時間).clamped(to: 溫蒂時間)

if (共通時間.first == 共通時間.last) {
    print("不能碰面")
} else {
    typealias 時間 = (hour: Int, min: Int)
    let 開始時間: 時間 = (共通時間.lowerBound / 100, 共通時間.lowerBound % 100)
    let 結束時間: 時間 = (共通時間.upperBound / 100, 共通時間.upperBound % 100)

    let formatter = NumberFormatter()
    formatter.minimumIntegerDigits = 2
    let 開始時間字串 = formatter.string(for: 開始時間.hour)! + " : " + formatter.string(for: 開始時間.min)!
    let 結束時間字串 = formatter.string(for: 結束時間.hour)! + " : " + formatter.string(for: 結束時間.min)!

    print("他們可以在 \(開始時間字串) ~ \(結束時間字串) 之間碰面")
}


print("---------------------")



// 2. 請設計一個隨機抽獎活動,每次執行時會從 1 到 1000 隨機抽一個數字。如果這個數字在 100 ~ 200 的範圍中(不含 200)則中 200 元;如果這個數字尾數是 8 或 6 則中 500 元;如果這個數字剛好是 888 或 666 則中 10,000 元。



func 抽獎活動(自選隨機數字: Int? = nil)
{
    var 隨機數字: Int = (1...1000).randomElement()! // ⚠️ 請勿改變數名稱,只修改 ? 的部分,? 必須是隨機產生的數字。
    隨機數字 = 自選隨機數字 ?? 隨機數字 // ⚠️ 請勿刪掉這行,測試用

    print("您抽中的數字是:\(隨機數字)", terminator: ",")

    let 尾數 = 隨機數字 % 10

    if (隨機數字 == 666 || 隨機數字 == 888) {
        print("🎉 恭喜你中了 10,000 元!")
    } else if (尾數 == 6 || 尾數 == 8) {
        print("🎉 恭喜你中了 500 元!")
    } else if ((100..<200).contains(隨機數字)) {
        print("🎉 恭喜你中了 200 元!")
    } else {
        print("很可惜,這次沒有中獎。")
    }
}

抽獎活動(自選隨機數字: 1)
抽獎活動(自選隨機數字: 100)
抽獎活動(自選隨機數字: 116)
抽獎活動(自選隨機數字: 239)
抽獎活動(自選隨機數字: 200)
抽獎活動(自選隨機數字: 344)
抽獎活動(自選隨機數字: 246)
抽獎活動(自選隨機數字: 666)
抽獎活動(自選隨機數字: 888)
抽獎活動(自選隨機數字: 777)
抽獎活動(自選隨機數字: 150)
抽獎活動()


Enter fullscreen mode Exit fullscreen mode

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs