求满足约束的正负双整数缩放归一化算法(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
相关产品推荐
相关产品推荐

