프로그래머스 - 덧칠하기
·
Algorithm/programmers
import Foundationfunc solution(_ n:Int, _ m:Int, _ section:[Int]) -> Int { var list = section var count = 0 while !list.isEmpty { let removed = list.removeFirst() while !list.isEmpty && list.first! - removed
프로그래머스 - 등수 매기기
·
Algorithm/programmers
import Foundationfunc solution(_ score:[[Int]]) -> [Int] { var list:[Double] = score.map{ Double($0[0]+$0[1])/Double(2) } var sorted:[Double] = list.sorted(by: >) return list.map { sorted.firstIndex(of: $0)! + 1 }}
프로그래머스 - 가장 많이 받은 선물
·
Algorithm/programmers
import Foundationfunc solution(_ friends:[String], _ gifts:[String]) -> Int { var friendInfo: [String:Int] = [:] for (index, name) in friends.enumerated() { friendInfo[name] = index } var giftState: [[Int]] = .init(repeating: .init(repeating: 0, count: friends.count), count: friends.count) var giftCount: [Int] = .init(repeating: 0, count: friends.count) for g..
프로그래머스 - 치킨 쿠폰
·
Algorithm/programmers
치킨 쿠폰 문제에서 주의할 점은 쿠폰 10개로 치킨을 시켜먹어도 쿠폰 1개를 주는 것입니다  import Foundationfunc solution(_ chicken:Int) -> Int { var ch = chicken var cnt = 0 while ch >= 10 { cnt += ch/10 ch = (ch/10) + (ch%10) } return cnt}
Swift - 백준 1927 최소 힙
·
Algorithm/Baekjoon
swift에서는 최소 힙에 관한 라이브러리가 없기 때문에 직접 구현해야 합니다 push 하는법push 하는 법은 다음과 같습니다현재 힙의 크기가 0보다 크고 현재 값이 부모 노드보다 작을 때까지 while 문을 반복합니다.while 문에서 반복되는 동안 현재 값의 노드와 부모 노드와 값을 바꾸고 부모 노드로 현재 위치(인덱스)를 이동시킵니다.while 문을 반복하다보면 현재 들어온 값은 자신보다 큰 부모 노드가 나올때까지 부모 노드와 계속 swap합니다.func push(_ x: Int) { heap.append(x) var n = heap.count-1 while n > 0 && x  pop 하는법pop 은 push 에 비해 코드는 길지만 원리는 비슷합니다.만약 현재 힙이..
프로그래머스 - 중복된 숫자 개수 filter, reduce
·
Algorithm/programmers
filter는 익숙한 문법입니다. '걸러내다' 라는 의미를 갖고 있으며 조건에 맞는 원하는 값을 걸러내는데 사용되며 아래처럼 사용됩니다.func solution(_ array:[Int], _ n:Int) -> Int { return array.filter { $0 == n }.count} reduce로 숫자 더하기let numbers = [1, 2, 3, 4, 5]이 배열의 모든 숫자를 더하고 싶다면 `reduce`를 이렇게 사용할 수 있습니다.let sum = numbers.reduce(0) { (결과, 숫자) in return 결과 + 숫자}- 0은 초기값 입니다.- `{ (결과, 숫자) in 결과 + 숫자 }`는 각 숫자를 어떻게 더할지를 설명하는 규칙 입니다.[1, 2, 3, 4, 5]..
ytw_developer
'Algorithm' 카테고리의 글 목록 (9 Page)