Codewars(알고리즘)/8Kyu

[Codewars] [8kyu] To square(root) or not to square(root)

Dannian 2020. 10. 31. 01:51
반응형
 

Codewars: Achieve mastery through challenge

Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highest potential.

www.codewars.com

루트로 나눠지는 값들은 제곱근, 그 외는 제곱을 해서 배열로 반환하는 문제입니다.

 

1. Swift

1-1. 본인의 풀이

저의 경우 input의 각 element의 제곱근을 구한 값을 Int로 변환 후 그 값들을 다시 제곱 한 값이 원래 값(element)과 같으면 제곱근, 아니라면 element 값을 제곱한 값을 반환할 배열(returnArr)에 각각 저장하면 된다고 생각을 하였습니다.

 

먼저 Apple의 Document에서 squareRoot() 문서를 일단 먼저 보면 좋을 것 같았습니다. 

 

Apple Developer Documentation

 

developer.apple.com

Int type에서는 squareRoot()를 이용할 수 없기 때문에 Int -> Double로 변환을 하고, squareRoot()를 실행한 결과값을 Int로 다시 변환하여 변수(sqv)에 저장을 합니다.

 

변수(sqv)를 제곱한 값이 원래 값(element)와 동일하면 변수(sqv)를 반환할 배열(returnArr)에 추가합니다.

 

원래 값(element)와 동일하지 않으면 원래 값(element)를 제곱한 값을 반환할 배열(returnArr)에 추가합니다.

import Foundation

func squareOrSquareRoot(_ input: [Int]) -> [Int] {
  var returnArr : [Int] = [] // 결과 반환 Array
  input.forEach { element in // 입력 값의 각 element
    let sqv = Int(Double(element).squareRoot()) // Int -> Double -> squareRoot() -> Int
    if sqv * sqv == element { // 제곱근을 제곱한 값이 element와 동일한 경우
      returnArr.append(sqv) // 반환 Array에 제곱근을 추가
    }else{ // 그 외
      returnArr.append(element * element) // 원본 입력값을 제곱
    }
  }
  return returnArr
}

 

1-2. Best Solution

 

Codewars: Achieve mastery through challenge

Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highest potential.

www.codewars.com

All Solution에서 Best Practices를 가장 많이 받은 cjnevin유저의 풀이입니다.

import Foundation

func squareOrSquareRoot(_ input: [Int]) -> [Int] {
    return input.map { i in
        let r = sqrt(Double(i))
        // truncatingRemainder는 dividingBy의 값으로 나눈 나머지 값을 반환합니다.
        // 단, %연산자와 다른 점은 부동소숫점 타입도 나머지 연산이 가능하다는 점입니다.
        // 여기서는 1로 나머지 연산을 진행하고, 결과값이 0이라면 제곱근,
        // 아니라면 원본 값을 제곱을 한 값을 반환합니다.
        return r.truncatingRemainder(dividingBy: 1).isZero ? Int(r) : i * i
    }
}

 

접근 방식은 제가 위에서 설명한 것과 동일하지만, 더 깔끔하고 기본 제공 함수를 적절하게 활용한 방식입니다.

 

sqrt는 squareRoot()와 동일한 기능을 하는 함수입니다.

 

다만 Stack overflow의 몇몇 답변들을 참고하다보니 squareRoot()를 이용하는 것이 sqrt함수를 호출 하는 것 보다 빠르다고 합니다.(아래 참고 URL)

 

Easiest way to find Square Root in Swift?

I have been trying to figure out how to programmatically find a square root of a number in Swift. I am looking for the simplest possible way to accomplish with as little code needed. I now this is

stackoverflow.com

이 외에도 다른 자료들을 찾아보다보면 몇몇 답변에서 해당 내용이 존재하지만, 아직 제가 직접 테스트를 해본 적이 없기 때문에 확실한 것은 아직 모르겠습니다.

 

-차후 다른 언어의 풀이도 추가될 예정입니다.-

반응형