You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求满足约束的正负双整数缩放归一化算法(Swift实现)

实现Swift函数scale

需要实现如下Swift函数:

func scale(x: Int, y: Int) -> Double { 
    // 在此处实现算法
    return 0.5
}

算法约束

  • 返回值范围为0到1
  • 当x与y相等时返回0.5
  • 当x比y"大"*时返回大于0.5的值
  • 当y比x"大"*时返回小于0.5的值
  • 返回值具有相对性,例如scale(x: -5, y: 4) < scale(x: -5, y: 0) == true
    • -1比-2"大"

Swift Playground测试套件

import Foundation
import XCTest

func XCTAssertBetween(_ value: Double, _ range: ClosedRange<Double>, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
    XCTAssertGreaterThanOrEqual(value, range.lowerBound, "Value is less than lower bound", file: file, line: line)
    XCTAssertLessThanOrEqual(value, range.upperBound, "Value is more than upper bound", file: file, line: line)
}

class ScaleTests: XCTestCase {
    func testZZ() {
        XCTAssertEqual(scale(x: 0, y: 0), 0.5)
    }
    
    func testPP() {
        XCTAssertEqual(scale(x: 1, y: 1), 0.5)
    }
    
    func testPZ() {
        XCTAssertBetween(scale(x: 1, y: 0), 0.51...1)
    }
    
    func testZP() {
        XCTAssertBetween(scale(x: 0, y: 1), 0...0.49)
    }
    
    func testNN() {
        XCTAssertEqual(scale(x: -1, y: -1), 0.5)
    }
    
    func testZN() {
        XCTAssertBetween(scale(x: 0, y: -1), 0.51...1)
    }
    
    func testNZ() {
        XCTAssertBetween(scale(x: -1, y: 0), 0...0.49)
    }
}
  
ScaleTests.defaultTestSuite.run()

内容的提问来源于stack exchange,提问作者emehex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 06:00:31