반응형
Codewars: Achieve mastery through coding challenge
Codewars is a coding practice site for all programmers where you can learn various programming languages. Join the community and improve your skills in many languages!
www.codewars.com
이번에는 f(x) 식이 주어지고, 해당 값에 따른 포물선 곡선의 각 point별 길이를 구하여 전체 포물선 유사값을 도출하는 문제입니다.
중학교 때 배운 a^2 + b^2 = c^2을 응용했습니다..
1. Swift
1-1. 본인의 풀이
func lenCurve(_ n: Int) -> Double {
// your code
var arr : [Double] = []
for i in 0 ... n {
arr.append(Double(i) / Double(n))
}
var length : Double = 0
for (index, value) in arr.enumerated() {
if index >= arr.count - 1 {
break
} else {
// a^2 + b^2 = c^2
let secondX = arr[index + 1]
let firstY = yValue(value)
let secondY = yValue(secondX)
let cLength = lineLen(value, y1: firstY, x2: secondX, y2: secondY)
length += cLength
}
}
return length
}
private func yValue(_ x: Double) -> Double {
return x * x
}
private func lineLen(_ x1: Double, y1: Double, x2: Double, y2: Double) -> Double {
let a = pow(abs(x2 - x1), 2)
let b = pow(abs(y2 - y1), 2)
return sqrt(a + b)
}
아래는 위와 같지만, for문 한 번으로 줄인 방식
func lenCurve(_ n: Int) -> Double {
// your code
var arr : [Double] = []
var length : Double = 0
for i in 0 ..< n {
let x1 = Double(i) / Double(n)
let x2 = Double(i + 1) / Double(n)
let y1 = yValue(x1)
let y2 = yValue(x2)
length += lineLen(x1, y1: y1, x2: x2, y2: y2)
}
return length
}
private func yValue(_ x: Double) -> Double {
return x * x
}
private func lineLen(_ x1: Double, y1: Double, x2: Double, y2: Double) -> Double {
let a = pow(abs(x2 - x1), 2)
let b = pow(abs(y2 - y1), 2)
return sqrt(a + b)
}
이번 문제는 사실상 영어 독해 문제였네요...
Solution 상에도 특별히 clever나 best practice를 압도적으로 받은 것이 없어서 이번엔 넘어가겠습니다.
반응형
'Codewars(알고리즘) > 6Kyu' 카테고리의 다른 글
[Codewars] [6Kyu] Tank Truck (0) | 2023.06.15 |
---|---|
[Codewars] [6Kyu] Projectile Motion (0) | 2023.06.15 |
[Codewars] [6Kyu] Persistent Bugger. (0) | 2022.01.26 |
[Codewars] [6Kyu] Give me a Diamond (0) | 2022.01.26 |
[Codewars] [6Kyu] Moduli number system (0) | 2022.01.26 |