GithubHelp home page GithubHelp logo

codility-swift's People

Contributors

heydoy avatar

Watchers

 avatar

codility-swift's Issues

First Unique

import Foundation
import Glibc

// you can write to stdout for debugging purposes, e.g.
// print("this is a debug message")

public func solution(_ A : inout [Int]) -> Int {
    // write your code in Swift 4.2.1 (Linux)
    // dicitonary 를 만들어서 저장하자 
    var dict: [Int: Int] = [:]
    for item in A {
        if let value = dict[item] {
            dict[item] = value + 1
        } else { 
            dict[item] = 1
        }
    }
    for number in A {
        if dict[number] == 1 {
            return number
        }
    }
    return -1
}

image

https://app.codility.com/demo/results/trainingMNV2AJ-WEP/

String Symmetry Point

extension String {
    subscript(idx: Int) -> String? {
        guard (0..<count).contains(idx) else {
            return nil
        }
        let target = index(startIndex, offsetBy: idx)
        return String(self[target])
    }
    
    subscript(_ range: CountableRange<Int>) -> String {
        let start = index(startIndex, offsetBy: max(0, range.lowerBound))
        let end = index(startIndex, offsetBy: min(self.count, range.upperBound))
        return String(self[start..<end])
    }
    
    subscript(_ range: CountablePartialRangeFrom<Int>) -> String {
        let start = index(startIndex, offsetBy: max(0, range.lowerBound))
        return String(self[start...])
    }
}

public func solution(_ S : inout String) -> Int {
    // write your code in Swift 4.2.1 (Linux)
    if S.count % 2 == 0 { return -1 }
    
    var mid = S.count / 2
    var start = 0
    var end = S.count - 1
    

    while start < mid {
        if S[start] != S[end] {
            return -1
        }
        start += 1
        end -= 1
    }

    return mid
}

스코어 57
첨자를 문자열 익스텐션으로 만들고 단순 비교로 for문을 돌렸더니 대용량 데이터에서 타임아웃 에러가 났다.

image

https://app.codility.com/demo/results/training5GFM46-FXK/

Parking Bill

import Foundation
import Glibc

// you can write to stdout for debugging purposes, e.g.
// print("this is a debug message")

public func solution(_ E : inout String, _ L : inout String) -> Int {
    func calculateToMin(_ time: String) -> Int {
        // compactMap이어야 옵셔널 처리를 안해줄 수 있음
        let value = time.components(separatedBy: ":").compactMap { Int($0) }
        return value[0] * 60 + value[1]
    }

    // 입장료 + 첫 한시간까지
    var cost = 2 + 3
    // 퇴장에서 입장시간과 첫 한시간 빼기
    let duration = calculateToMin(L) - calculateToMin(E) - 60

    // 올림 
    if duration > 0 {
        cost += Int(ceil((Double(duration) / 60.0))) * 4
    }
    return cost
}

image

https://app.codility.com/demo/results/trainingFKSNZP-CSV/

Disappearing Pairs

import Foundation
import Glibc

// you can write to stdout for debugging purposes, e.g.
// print("this is a debug message")

public func solution(_ S : inout String) -> String {
    // write your code in Swift 4.2.1 (Linux)
    var result = ""
    for item in S {
        if result.last == item {
            _ = result.popLast()
        } else {
            result.append(item)
        }
    }
    return result
}

배열은 removeLast()popLast()를 이용해 제거할 수 있다. 둘은 동일하게 동작하지만 pop의 경우 배열이 비었을 때 사용하면 nil을 반환한다. 문자열은 캐릭터의 배열 형태이므로 appendpopLast 메서드를 사용할 수 있다.
위 문제는 스택 특징을 이용해 풀었기 때문에 pop 메서드를 이용했다. 이전 문자와 현재 문자가 동일할 경우 이전문자를 없앤다.

image

https://app.codility.com/demo/results/trainingJTNWXG-Q5N/

Tree Height

import Foundation
import Glibc
import extratypes // this library contains declarations of types from the task

// you can write to stdout for debugging purposes, e.g.
// print("this is a debug message")

private func getHeight(_ T: Tree?) -> Int {
    if let T = T {
        if T.l ==  nil && T.r == nil {
            return 0
        }
        else if T.l == nil {
            return 1 + getHeight(T.r)
        }
        else if T.r == nil {
            return 1 + getHeight(T.l)
        }
        else {
            return 1 + max(getHeight(T.l), getHeight(T.r))
        }
    } else { return 0 }
}


public func solution(_ T : Tree?) -> Int {
    // write your code in Swift 4.2.1 (Linux)
    return getHeight(T)
}

재귀함수로 해결

image

https://app.codility.com/demo/results/trainingVASVHA-2SZ/

Array Inversion Count

import Foundation
import Glibc

// you can write to stdout for debugging purposes, e.g.
// print("this is a debug message")

public func solution(_ A : inout [Int]) -> Int {
    // write your code in Swift 4.2.1 (Linux)
    let count = A.count
    var inversion = 0
    for i in 0..<count {
        let first = A[i] 
        for j in i..<count {
            if first > A[j] {
                inversion += 1
            }
        }
        if inversion >= 1000000000 {
            return -1
        }
    }
    return inversion
}

https://app.codility.com/demo/results/trainingW3N324-Z2U/

image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.