├── .gitignore ├── BasicConcepts ├── BinarySearch │ ├── BinarySearch_Coden.swift │ ├── BinarySearch_Geon.swift │ ├── BinarySearch_Soll.swift │ ├── BinarySearch_Tacocat.swift │ └── BinarySearch_수박.swift ├── CountingCellsInABlob │ ├── CountingCellsInABlob_Coden.swift │ └── CountingCellsInABlob_수박.swift ├── Factorial │ ├── Factorial_Coden.swift │ ├── Factorial_Ellen.swift │ ├── Factorial_Geon.swift │ ├── Factorial_Soll.swift │ ├── Factorial_Tacocat.swift │ └── Factorial_수박.swift ├── Fibonacci │ ├── Fibonacci_Coden.swift │ ├── Fibonacci_Ellen.swift │ ├── Fibonacci_Geon.swift │ ├── Fibonacci_Soll.swift │ ├── Fibonacci_Tacocat.swift │ └── Fibonacci_수박.swift ├── LinkedList │ ├── LinkedList_Coden.swift │ ├── LinkedList_Ellen.swift │ ├── LinkedList_Geon.swift │ ├── LinkedList_Soll.swift │ ├── LinkedList_Tacocat.swift │ └── LinkedList_수박.swift ├── Maze │ ├── MazaBFS_수박.swift │ ├── MazeBFS_Coden.swift │ ├── MazeBFS_Soll.swift │ ├── MazeDFS_Coden.swift │ └── MazeDFS_수박.swift ├── NQueensProblem │ ├── NQueensProblem_Coden.swift │ └── NQueensProblem_수박.swift ├── Queue │ ├── Queue_Coden.swift │ ├── Queue_Geon.swift │ ├── Queue_Soll.swift │ ├── Queue_Tacocat.swift │ └── Queue_수박.swift ├── SequentialSearch │ ├── SequentialSearch_Coden.swift │ ├── SequentialSearch_Geon.swift │ ├── SequentialSearch_Soll.swift │ ├── SequentialSearch_Tacocat.swift │ └── SequentialSearch_수박.swift └── Stack │ ├── Stack_Coden.swift │ ├── Stack_Ellen.swift │ ├── Stack_Geon.swift │ ├── Stack_Soll.swift │ ├── Stack_Tacocat.swift │ └── Stack_수박.swift ├── Boj_Charlotte ├── 1000_charlotte.swift ├── 1001_charlotte.swift ├── 1008_charlotte.swift ├── 10171_charlotte.swift ├── 10172_charlotte.swift ├── 10430_charlotte.swift ├── 10718_charlotte.swift ├── 10869_charlotte.swift ├── 10998_charlotte.swift └── 2557_charlotte.swift ├── Boj_Coden ├── 1000_Coden.swift ├── 1001_Coden.swift ├── 1008_Coden.swift ├── 1012_Coden.swift ├── 10171_Coden.swift ├── 10172_Coden.swift ├── 10430_Coden.swift ├── 10718_Coden.swift ├── 10816_Coden.swift ├── 10828_Coden.swift ├── 10869_Coden.swift ├── 10998_Coden.swift ├── 11866_Coden.swift ├── 1303_Coden.swift ├── 15649_Coden.swift ├── 1759_Coden.swift ├── 18258_Coden.swift ├── 2178_Coden.swift ├── 2557_Coden.swift ├── 2588_Coden.swift ├── 2667_Coden.swift ├── 4949_Coden.swift ├── 7576_Coden.swift ├── 9019_Coden.swift ├── 9663_Coden.cpp └── 9663_Coden.swift ├── Boj_Geon ├── 1000_Geon.swift ├── 1001_Geon.swift ├── 1008_Geon.swift ├── 10171_Geon.swift ├── 10172_Geon.swift ├── 10430_Geon.swift ├── 10718_Geon.swift ├── 10828_Geon.swift ├── 10869_Geon.swift ├── 10998_Geon.swift ├── 11866_Geon.swift ├── 2557_Geon.swift ├── 2588_Geon.swift └── 4949_Geon.swift ├── Boj_Soll ├── 1000_Soll.swift ├── 1001_Soll.swift ├── 1008_Soll.swift ├── 10171_Soll.swift ├── 10172_Soll.swift ├── 10430_Soll.swift ├── 10718_Soll.swift ├── 10816_Soll.swift ├── 10828_Soll.swift ├── 10869_Soll.swift ├── 10998_Soll.swift ├── 11866_Soll.swift ├── 18258_Soll.swift ├── 2557_Soll.swift ├── 2588_Soll.swift ├── 4949_Soll.swift └── 9663_Soll.swift ├── Boj_Soobak ├── 1000_수박.swift ├── 1001_수박.swift ├── 1008_수박.swift ├── 1012_수박.swift ├── 10171_수박.swift ├── 10172_수박.swift ├── 10430_수박.swift ├── 10718_수박.swift ├── 10816_수박.swift ├── 10828_수박.swift ├── 10869_수박.swift ├── 10998_수박.swift ├── 11866_수박.swift ├── 1303_수박.swift ├── 1759_수박.swift ├── 18258_수박.swift ├── 2178_수박.swift ├── 2557_수박.swift ├── 2558_수박.swift ├── 2667_수박.swift ├── 4949_수박.swift ├── 7576_수박.swift ├── 9019_수박.swift └── 9663_수박.swift ├── Boj_Tacocat ├── 1000_Tacocat.swift ├── 1001_Tacocat.swift ├── 1008_Tacocat.swift ├── 10172_Tacocat.swift ├── 10430_Tacocat.swift ├── 10717_Tacocat.swift ├── 10718_Tacocat.swift ├── 10828_Tacocat.swift ├── 10869_Tacocat.swift ├── 10998_Tacocat.swift ├── 11866_Tacocat.swift ├── 2557_Tacocat.swift ├── 2588_Tacocat.swift └── 4949_Tacocat.swift ├── Boj_ellen ├── 1000_Ellen.swift ├── 1001_Ellen.swift ├── 1008_Ellen.swift ├── 10171_Ellen.swift ├── 10172_Ellen.swift ├── 10430_Ellen.swift ├── 10718_Ellen.swift ├── 10828_Ellen.swift ├── 10869_Ellen.swift ├── 10998_Ellen.swift ├── 1158_Ellen.swift ├── 18258_Ellen.swift ├── 2557_Ellen.swift ├── 2588_Ellen.swift └── 4949_Ellen.swift ├── Programmers_Coden ├── 모의고사_Coden.swift ├── 수박수박수박수박수박수?_Coden.swift └── 타겟 넘버_Coden.swift ├── Programmers_Soobak ├── 모의고사_수박.swift ├── 수박수박수?_수박.swift └── 타겟넘버_수박.swift └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.toptal.com/developers/gitignore/api/macos,xcode,swift 3 | # Edit at https://www.toptal.com/developers/gitignore?templates=macos,xcode,swift 4 | 5 | ### macOS ### 6 | # General 7 | .DS_Store 8 | .AppleDouble 9 | .LSOverride 10 | 11 | # Icon must end with two \r 12 | Icon 13 | 14 | 15 | # Thumbnails 16 | ._* 17 | 18 | # Files that might appear in the root of a volume 19 | .DocumentRevisions-V100 20 | .fseventsd 21 | .Spotlight-V100 22 | .TemporaryItems 23 | .Trashes 24 | .VolumeIcon.icns 25 | .com.apple.timemachine.donotpresent 26 | 27 | # Directories potentially created on remote AFP share 28 | .AppleDB 29 | .AppleDesktop 30 | Network Trash Folder 31 | Temporary Items 32 | .apdisk 33 | 34 | ### Swift ### 35 | # Xcode 36 | # 37 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 38 | 39 | ## User settings 40 | xcuserdata/ 41 | 42 | ## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) 43 | *.xcscmblueprint 44 | *.xccheckout 45 | 46 | ## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) 47 | build/ 48 | DerivedData/ 49 | *.moved-aside 50 | *.pbxuser 51 | !default.pbxuser 52 | *.mode1v3 53 | !default.mode1v3 54 | *.mode2v3 55 | !default.mode2v3 56 | *.perspectivev3 57 | !default.perspectivev3 58 | 59 | ## Obj-C/Swift specific 60 | *.hmap 61 | 62 | ## App packaging 63 | *.ipa 64 | *.dSYM.zip 65 | *.dSYM 66 | 67 | ## Playgrounds 68 | timeline.xctimeline 69 | playground.xcworkspace 70 | 71 | # Swift Package Manager 72 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. 73 | # Packages/ 74 | # Package.pins 75 | # Package.resolved 76 | # *.xcodeproj 77 | # Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata 78 | # hence it is not needed unless you have added a package configuration file to your project 79 | # .swiftpm 80 | 81 | .build/ 82 | 83 | # CocoaPods 84 | # We recommend against adding the Pods directory to your .gitignore. However 85 | # you should judge for yourself, the pros and cons are mentioned at: 86 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 87 | # Pods/ 88 | # Add this line if you want to avoid checking in source code from the Xcode workspace 89 | # *.xcworkspace 90 | 91 | # Carthage 92 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 93 | # Carthage/Checkouts 94 | 95 | Carthage/Build/ 96 | 97 | # Accio dependency management 98 | Dependencies/ 99 | .accio/ 100 | 101 | # fastlane 102 | # It is recommended to not store the screenshots in the git repo. 103 | # Instead, use fastlane to re-generate the screenshots whenever they are needed. 104 | # For more information about the recommended setup visit: 105 | # https://docs.fastlane.tools/best-practices/source-control/#source-control 106 | 107 | fastlane/report.xml 108 | fastlane/Preview.html 109 | fastlane/screenshots/**/*.png 110 | fastlane/test_output 111 | 112 | # Code Injection 113 | # After new code Injection tools there's a generated folder /iOSInjectionProject 114 | # https://github.com/johnno1962/injectionforxcode 115 | 116 | iOSInjectionProject/ 117 | 118 | ### Xcode ### 119 | # Xcode 120 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 121 | 122 | 123 | 124 | 125 | ## Gcc Patch 126 | /*.gcno 127 | 128 | ### Xcode Patch ### 129 | *.xcodeproj/* 130 | !*.xcodeproj/project.pbxproj 131 | !*.xcodeproj/xcshareddata/ 132 | !*.xcworkspace/contents.xcworkspacedata 133 | **/xcshareddata/WorkspaceSettings.xcsettings 134 | 135 | # End of https://www.toptal.com/developers/gitignore/api/macos,xcode,swift 136 | 137 | # Excluding files that are not related to algorithm problem solving. 138 | **/main.swift 139 | **/*.xcodeproj 140 | -------------------------------------------------------------------------------- /BasicConcepts/BinarySearch/BinarySearch_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // BinarySearch_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2021/12/21. 6 | // 7 | 8 | /* 9 | 이진탐색 구현 10 | 이진탐색은 '정렬된 컬렉션'에서 원하는 값을 찾는 알고리즘이다. 11 | 시간복잡도는 일반적으로 O(log n)이다. 12 | */ 13 | 14 | //MARK: - Iterative version 15 | func binarySearch(for value: Element, in storage: Container) -> Container.Index? where Container: Collection, Container.Element == Element, Element: Comparable, Container.Index == Int { 16 | var leftIndex = 0 17 | var rightIndex = storage.count - 1 18 | 19 | while leftIndex <= rightIndex { 20 | let centerIndex = (leftIndex + rightIndex) / 2 21 | 22 | if storage[centerIndex] == value { 23 | return centerIndex 24 | } else if storage[centerIndex] > value { 25 | rightIndex = centerIndex - 1 26 | } else { 27 | leftIndex = centerIndex + 1 28 | } 29 | } 30 | 31 | return nil 32 | } 33 | 34 | //MARK: - Recursive version 35 | func recursiveBinSearch(for value: Element, in storage: Container, startIndex: Container.Index, endIndex: Container.Index) -> Container.Index? where Container: Collection, Container.Element == Element, Element: Comparable, Container.Index == Int { 36 | let centerIndex = (startIndex + endIndex) / 2 37 | 38 | if startIndex > endIndex { //base case 1 - 찾지 못한 경우 39 | return nil 40 | } else if storage[centerIndex] == value { //base case 2 - 원하는 값을 찾은 경우 41 | return centerIndex 42 | } else if storage[centerIndex] > value { //recursive case 1 - 앞의 절반을 다시 찾아봐야 하는 경우 43 | return recursiveBinSearch(for: value, in: storage, startIndex: startIndex, endIndex: centerIndex - 1) 44 | } else { //recursive case 2 - 뒤의 절반을 다시 찾아봐야 하는 경우 45 | return recursiveBinSearch(for: value, in: storage, startIndex: centerIndex + 1, endIndex: endIndex) 46 | } 47 | } 48 | 49 | -------------------------------------------------------------------------------- /BasicConcepts/BinarySearch/BinarySearch_Geon.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SequentialSearch_Geon .swift 3 | // Excution 4 | // 5 | // Created by 김준건 on 2021/12/24. 6 | // 7 | 8 | func search(into container: [T], target: T, startIndex: Int, endIndex: Int) -> Int? { 9 | let middle = (startIndex + endIndex) / 2 10 | 11 | if startIndex > endIndex { 12 | return nil 13 | } else if container[middle] == target { 14 | return middle 15 | } else if container[middle] < target { 16 | return search(into: container, target: target, startIndex: middle + 1, endIndex: endIndex) 17 | } else { 18 | return search(into: container, target: target, startIndex: startIndex, endIndex: middle) 19 | } 20 | 21 | } 22 | 23 | func search(into container: [T], target: T) -> Int? { 24 | var startIndex = 0 25 | var endIndex = container.count - 1 26 | 27 | while startIndex < endIndex { 28 | let middle = (startIndex + endIndex) / 2 29 | 30 | if container[middle] == target { 31 | return middle 32 | } else if container[middle] < target { 33 | startIndex = middle + 1 34 | } else { 35 | endIndex = middle 36 | } 37 | } 38 | return nil 39 | } 40 | -------------------------------------------------------------------------------- /BasicConcepts/BinarySearch/BinarySearch_Soll.swift: -------------------------------------------------------------------------------- 1 | // 2 | // BinarySearch_Soll.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by Dasoll Park on 2021/12/23. 6 | // 7 | 8 | import Foundation 9 | 10 | func binarySearch(data: [Int], target: Int) -> Int { 11 | var begin = 0 12 | var end = data.count - 1 13 | var middle: Int 14 | 15 | while true { 16 | middle = (begin + end) / 2 17 | if begin > end { 18 | return -1 19 | } 20 | if data[middle] == target { 21 | return middle 22 | } else if data[middle] < target { 23 | begin = middle + 1 24 | } else { 25 | end = middle - 1 26 | } 27 | } 28 | } 29 | 30 | func binarySearch(data: [Int], target: Int, begin: Int, end: Int) -> Int { 31 | if begin > end { 32 | return -1 33 | } else { 34 | let middle = (begin + end) / 2 35 | if target == data[middle] { 36 | return middle 37 | } else if target < data[middle] { 38 | return binarySearch(data: data, target: target, begin: begin, end: middle - 1) 39 | } else { 40 | return binarySearch(data: data, target: target, begin: middle + 1, end: end) 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /BasicConcepts/BinarySearch/BinarySearch_Tacocat.swift: -------------------------------------------------------------------------------- 1 | // 2 | // BinarySearch_Tacocat.swift 3 | // AlgorithmStudy_Exercise 4 | // 5 | // Created by Do Yi Lee on 2021/12/24. 6 | // 7 | 8 | import Foundation 9 | 10 | var data: [Int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 11 | 12 | func binarySearch(start: Int, end: Int, target: Int) -> Int { 13 | if start > end { 14 | return -1 15 | } else { 16 | let number = (start + end) / 2 17 | 18 | if data[number] == target { 19 | return number 20 | } else if data[number] < target { 21 | return binarySearch(start: number, end: end, target: target) 22 | } else { 23 | return binarySearch(start: start, end: number, target: target) 24 | } 25 | } 26 | } 27 | 28 | let test = binarySearch(start: 0, end: 8, target: 4) 29 | print(test) 30 | -------------------------------------------------------------------------------- /BasicConcepts/BinarySearch/BinarySearch_수박.swift: -------------------------------------------------------------------------------- 1 | // 2 | // BinarySearch_수박.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by kjs on 2021/12/23. 6 | // 7 | 8 | enum SearchError: Error { 9 | case elementIsNotExist 10 | } 11 | 12 | func binarySearchOnIteration( 13 | element: Element, 14 | within array: [Element] 15 | ) -> Result<(index: Int, element: Element), Error> { 16 | var startIndex = 0 17 | var endIndex = array.count - 1 18 | var midIndex: Int { 19 | (startIndex + endIndex) / 2 20 | } 21 | 22 | while startIndex <= endIndex { 23 | let currentIndex = midIndex 24 | let currentTarget = array[currentIndex] 25 | 26 | if currentTarget == element { 27 | return .success((index: currentIndex, element: currentTarget)) 28 | } else if currentTarget < element { 29 | startIndex = currentIndex + 1 30 | } else if currentTarget > element { 31 | endIndex = currentIndex - 1 32 | } 33 | } 34 | 35 | return .failure(SearchError.elementIsNotExist) 36 | } 37 | 38 | func binarySearchOnRecursion( 39 | element: Element, 40 | from startIndex: Int, 41 | to endIndex: Int, 42 | within array: [Element] 43 | ) -> Result<(index: Int, element: Element), Error> { 44 | guard startIndex <= endIndex && startIndex < array.count else { 45 | return .failure(SearchError.elementIsNotExist) 46 | } 47 | 48 | let currentIndex = (startIndex + endIndex) / 2 49 | let currentTarget = array[currentIndex] 50 | 51 | if currentTarget == element { 52 | return .success((index: currentIndex, element: currentTarget)) 53 | } else if currentTarget < element { 54 | return binarySearchOnRecursion( 55 | element: element, 56 | from: currentIndex + 1, 57 | to: endIndex, 58 | within: array 59 | ) 60 | } else if currentTarget > element { 61 | return binarySearchOnRecursion( 62 | element: element, 63 | from: startIndex, 64 | to: endIndex - 1, 65 | within: array 66 | ) 67 | } 68 | 69 | return .failure(SearchError.elementIsNotExist) 70 | } 71 | -------------------------------------------------------------------------------- /BasicConcepts/CountingCellsInABlob/CountingCellsInABlob_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // CountingCellsInABlob_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2022/01/03. 6 | // 7 | 8 | /* 9 | 주어진 픽셀 그림에서 blob이 몇개인지 카운팅 하는 문제 10 | blob들 중 가장 큰 blob의 셀 개수를 알려달라 할 수도 있고 모든 blob에 대해 셀의 총 개수를 배열로 만들어 반환하라 할 수도 있다. 11 | 12 | Counting Cells in a Blob 문제는 DFS/BFS로 풀이 가능하다. 13 | 여기서는 DFS를 이용한 풀이를 작성해보려 한다. 14 | */ 15 | 16 | //입력 17 | let backgroundPixel = 0 18 | let imagePixel = 1 19 | var photo = [ 20 | [1, 0, 0, 0, 0, 0, 0, 1], 21 | [0, 1, 1, 0, 0, 1, 0, 0], 22 | [1, 1, 0, 0, 1, 0, 1, 0], 23 | [0, 0, 0, 0, 0, 1, 0, 0], 24 | [0, 1, 0, 1, 0, 1, 0, 0], 25 | [0, 1, 0, 1, 0, 1, 0, 0], 26 | [1, 0, 0, 0, 1, 0, 0, 1], 27 | [0, 1, 1, 0, 0, 1, 1, 1] 28 | ] 29 | 30 | //풀이 31 | let checkedPixel = 2 32 | var countingResult = [Int]() 33 | 34 | func countCells(x column: Int, y row: Int) -> Int { 35 | if row < 0 || row > 7 || column < 0 || column > 7 { //base case 1 - 범위 벗어남 36 | return 0 37 | } else if photo[row][column] != imagePixel { //base case 2 - 이미지 픽셀이 아닌 부분에 도착 38 | return 0 39 | } else { //recursive case - 이미지 픽셀에 도착 40 | photo[row][column] = checkedPixel 41 | return 1 42 | + countCells(x: column, y: row - 1) 43 | + countCells(x: column + 1, y: row - 1) 44 | + countCells(x: column + 1, y: row) 45 | + countCells(x: column + 1, y: row + 1) 46 | + countCells(x: column, y: row + 1) 47 | + countCells(x: column - 1, y: row + 1) 48 | + countCells(x: column - 1, y: row) 49 | + countCells(x: column - 1, y: row - 1) 50 | } //12시 방향부터 시계방향으로 탐색 51 | } 52 | 53 | 54 | for row in photo.indices { 55 | for column in photo[row].indices { 56 | let result = countCells(x: column, y: row) 57 | if result > 0 { 58 | countingResult.append(result) 59 | } 60 | } 61 | } 62 | 63 | print(countingResult) 64 | -------------------------------------------------------------------------------- /BasicConcepts/CountingCellsInABlob/CountingCellsInABlob_수박.swift: -------------------------------------------------------------------------------- 1 | // 2 | // CountingCellsInABlob_수박.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by kjs on 2022/01/04. 6 | // 7 | 8 | struct Node: CustomStringConvertible { 9 | let isFilled: Bool 10 | var isVisited = false 11 | 12 | var description: String { 13 | if isFilled { 14 | return "O" 15 | } else if isVisited { 16 | return "X" 17 | } else { 18 | return " " 19 | } 20 | } 21 | } 22 | 23 | var color: Node { 24 | return Node(isFilled: true) 25 | } 26 | 27 | var empty: Node { 28 | return Node(isFilled: false) 29 | } 30 | var blobs: [[Node]] { 31 | [ // 8*8 32 | [color, empty, empty, empty, empty, empty, empty, color], 33 | [empty, color, color, empty, empty, color, empty, empty], 34 | [color, color, empty, empty, color, empty, color, empty], 35 | [empty, empty, empty, empty, empty, color, empty, empty], 36 | [empty, color, empty, color, empty, color, empty, empty], 37 | [empty, color, empty, color, empty, color, empty, empty], 38 | [color, empty, empty, empty, color, empty, empty, color], 39 | [empty, color, color, empty, empty, color, color, color] 40 | ] 41 | } 42 | 43 | var currentBlobs = blobs 44 | 45 | func countingCellsEiBlob(y: Int, x: Int) -> Int { 46 | guard y < currentBlobs.count, x < currentBlobs.count else { return .zero } 47 | guard x >= 0, y >= 0 else { return .zero } 48 | 49 | if currentBlobs[y][x].isVisited { return .zero } 50 | 51 | currentBlobs[y][x].isVisited = true 52 | 53 | if currentBlobs[y][x].isFilled { 54 | 55 | let directions = [ 56 | (y: y-1, x: x-1), 57 | (y: y-1, x: x), 58 | (y: y-1, x: x+1), 59 | (y: y, x: x-1), 60 | (y: y, x: x+1), 61 | (y: y+1, x: x-1), 62 | (y: y+1, x: x), 63 | (y: y+1, x: x+1), 64 | ] 65 | 66 | return 1 + directions.reduce(0, { (partialResult, point) in 67 | return partialResult + countingCellsEiBlob(y: point.y, x: point.x) 68 | }) 69 | 70 | } else{ 71 | return .zero 72 | } 73 | } 74 | 75 | /* 76 | for y in 0...7 { 77 | for x in 0...7 { 78 | currentBlobs = blobs 79 | let count = countingCellsEiBlob(y: y, x: x) 80 | if count > 0 { 81 | print("y: \(y), x: \(x), count: \(count)") 82 | } 83 | } 84 | } 85 | 86 | currentBlobs.forEach { nodes in 87 | print(nodes) 88 | } 89 | */ 90 | -------------------------------------------------------------------------------- /BasicConcepts/Factorial/Factorial_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Factorial_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2021/12/17. 6 | // 7 | 8 | //팩토리얼은 특정 숫자값 n에 대해 n부터 1까지의 곱을 의미한다. 9 | //0!은 1로 약속되어있다. 따라서 n >= 0 10 | 11 | //MARK: - Recursion 12 | func factorial(n: Int) -> Int { 13 | if n <= 0 { 14 | return 1 15 | } 16 | return n * factorial(n: n-1) 17 | } 18 | 19 | //MARK: - Iterative 20 | func IterativeFact(n: Int) -> Int { 21 | return (1...n).reduce(1, *) 22 | } 23 | 24 | -------------------------------------------------------------------------------- /BasicConcepts/Factorial/Factorial_Ellen.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Factorial_Ellen.swift 3 | // BasicConcepts_Ellen 4 | // 5 | // Created by Ellen on 2021/12/17. 6 | // 7 | 8 | import Foundation 9 | 10 | func factorial(_ number: Int) -> Int { 11 | if number == 0 { 12 | return 1 13 | } else { 14 | return number * factorial(number - 1) 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /BasicConcepts/Factorial/Factorial_Geon.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Factorial_Geon.swift 3 | // Execution 4 | // 5 | // Created by 김준건 on 2021/12/17. 6 | // 7 | 8 | import Foundation 9 | 10 | func factorial(input n: Int) -> Int { 11 | if n == .zero { 12 | return 1 13 | } else { 14 | return n * factorial(input: n-1) 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /BasicConcepts/Factorial/Factorial_Soll.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Factorial_Soll.swift 3 | // Factorial 4 | // 5 | // Created by Dasoll Park on 2021/12/17. 6 | // 7 | 8 | func factorial(_ n: Int) -> Int { 9 | if n <= 0 { 10 | return 1 11 | } else { 12 | return n * factorial(n-1) 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /BasicConcepts/Factorial/Factorial_Tacocat.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Factorial_Tacocat.swift 3 | // AlgorithmStudy_Exercise 4 | // 5 | // Created by Do Yi Lee on 2021/12/16. 6 | // 7 | 8 | import Foundation 9 | 10 | func factorial(_ number: Int) -> Int { 11 | if number == 0 { 12 | return 1 13 | } else { 14 | return number * factorial(number - 1) 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /BasicConcepts/Factorial/Factorial_수박.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Factorial_수박.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by kjs on 2021/12/16. 6 | // 7 | 8 | func factorial(_ number: UInt) -> UInt { 9 | if number <= 1 { 10 | return 1 11 | } else { 12 | return number * factorial(number-1) 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /BasicConcepts/Fibonacci/Fibonacci_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Fibonacci_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2021/12/17. 6 | // 7 | 8 | //피보나치는 1, 1, 2, 3, 5, 8 .. 순서로 나아가는 수열이다. 9 | //i번째 값은 i-1 과 i-2 값의 합으로 나타난다. 10 | //첫번째값과 두번째 값은 1이며 구하고자 하는 값을 n번째라고 가정하자. (n > 0) 11 | 12 | //MARK: - Recursion 13 | func fibonacci(n: Int) -> Int { 14 | if n <= 2 { 15 | return 1 16 | } 17 | return fibonacci(n: n-1) + fibonacci(n: n-2) 18 | } 19 | 20 | //MARK: - Memoization(Top-Down) 21 | let input = 100 //사용자가 원하는 n번째 값 입력 22 | var fibMemo = [Int]() 23 | for _ in 0...input { 24 | fibMemo.append(0) 25 | } 26 | func MemoizationFib(n: Int) -> Int { 27 | if n <= 2 { 28 | return 1 29 | } else if fibMemo[n] != 0 { 30 | return fibMemo[n] 31 | } else { 32 | fibMemo[n] = MemoizationFib(n: n-1) + MemoizationFib(n: n-2) 33 | return fibMemo[n] 34 | } 35 | } 36 | 37 | //MARK: - DP(Bottom-Up) 38 | let input2 = 100 //사용자가 원하는 n번째 값 입력 39 | var fibMemoization = [Int]() 40 | for _ in 0...input2 { 41 | fibMemoization.append(0) 42 | } 43 | fibMemoization[1] = 1 44 | fibMemoization[2] = 1 45 | func DPFib(n: Int) -> Int { 46 | for index in 3...n { 47 | fibMemoization[index] = fibMemoization[index-1] + fibMemoization[index-2] 48 | } 49 | return fibMemoization[n] 50 | } 51 | -------------------------------------------------------------------------------- /BasicConcepts/Fibonacci/Fibonacci_Ellen.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Fibonacci_Ellen.swift 3 | // BasicConcepts_Ellen 4 | // 5 | // Created by Ellen on 2021/12/17. 6 | // 7 | 8 | import Foundation 9 | 10 | func fibonacci(_ number: Int) -> Int { 11 | if number == 0 { 12 | return 0 13 | } else if number == 1 { 14 | return 1 15 | } else { 16 | return fibonacci(number-1) + fibonacci(number-2) 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /BasicConcepts/Fibonacci/Fibonacci_Geon.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Fibonacci.swift 3 | // Execution 4 | // 5 | // Created by 김준건 on 2021/12/17. 6 | // 7 | 8 | import Foundation 9 | 10 | func fibonacci(input n: Int) -> Int { 11 | if n <= 1 { 12 | return n 13 | } else { 14 | return fibonacci(input: n-1) + fibonacci(input: n-2) 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /BasicConcepts/Fibonacci/Fibonacci_Soll.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Fibonacci_Soll.swift 3 | // Fibonacci 4 | // 5 | // Created by Dasoll Park on 2021/12/17. 6 | // 7 | 8 | func fibonacci(_ n: Int) -> Int { 9 | if n < 2 { 10 | return n 11 | } else { 12 | return fibonacci(n-1) + fibonacci(n-2) 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /BasicConcepts/Fibonacci/Fibonacci_Tacocat.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Fibonacci_Tacocat.swift 3 | // AlgorithmStudy_Exercise 4 | // 5 | // Created by Do Yi Lee on 2021/12/16. 6 | // 7 | 8 | import Foundation 9 | 10 | func fibonacci(_ number: Int) -> Int { 11 | if number == 0 { 12 | return 0 13 | } else if number == 1 { 14 | return 1 + fibonacci(number - 1) 15 | } else { 16 | return fibonacci(number - 1) + fibonacci(number - 2) 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /BasicConcepts/Fibonacci/Fibonacci_수박.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Fibonacci_수박.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by kjs on 2021/12/16. 6 | // 7 | 8 | func fibonacci(_ number: UInt) -> UInt { 9 | if number <= 1 { 10 | return 1 11 | } else { 12 | return fibonacci(number-2) + fibonacci(number-1) 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /BasicConcepts/LinkedList/LinkedList_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // LinkedList_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2021/12/06. 6 | // 7 | 8 | struct LinkedList { 9 | //캡슐화를 위해 Node를 내부에 선언 10 | private class Node { 11 | let data: T 12 | var next: Node? 13 | 14 | init(data: T) { 15 | self.data = data 16 | } 17 | } 18 | 19 | private var head: Node? 20 | private let firstIndex = 0 21 | 22 | //O(n) 23 | var size: Int { 24 | var count = Int.zero 25 | var node = head 26 | while node != nil { //while let 바인딩도 써볼 수 있을 것 같다. 27 | count += 1 28 | node = node?.next 29 | } 30 | return count 31 | } 32 | var isEmpty: Bool { 33 | return head == nil 34 | } 35 | 36 | mutating func insertIntoFront(with data: T) { 37 | let node = Node(data: data) 38 | node.next = head?.next 39 | head = node 40 | } 41 | //O(n) 42 | mutating func insert(into index: Int, with data: T) -> T? { 43 | if index < firstIndex || index > size { //Invalid Index 44 | return nil 45 | } 46 | if index == firstIndex { 47 | insertIntoFront(with: data) 48 | return data 49 | } 50 | 51 | var remainingDistance = index 52 | var previousNode: Node? = nil 53 | var nextNode = head 54 | while remainingDistance != .zero { 55 | previousNode = nextNode 56 | nextNode = nextNode?.next 57 | remainingDistance -= 1 58 | } 59 | let newNode = Node(data: data) 60 | newNode.next = nextNode 61 | previousNode?.next = newNode 62 | 63 | return data 64 | } 65 | mutating func insertIntoRear(with data: T) { 66 | _ = insert(into: size, with: data) 67 | } 68 | //최악의 경우 O(n) 69 | func search(for data: T) -> Int? { 70 | var presentNode = head 71 | var index = firstIndex 72 | while presentNode != nil { 73 | if presentNode?.data == data { 74 | return index 75 | } 76 | presentNode = presentNode?.next 77 | index += 1 78 | } 79 | return nil 80 | } 81 | mutating func deleteFront() -> T? { 82 | let data = head?.data 83 | head = head?.next 84 | return data 85 | } 86 | mutating func delete(at index: Int) -> T? { 87 | if index < firstIndex || index >= size { //Invalid Index 88 | return nil 89 | } 90 | if index == firstIndex { 91 | return deleteFront() 92 | } 93 | var previousNode: Node? = nil 94 | var targetNode = head 95 | var countToDestination = firstIndex 96 | while countToDestination != index { 97 | previousNode = targetNode 98 | targetNode = targetNode?.next 99 | countToDestination += 1 100 | } 101 | let data = targetNode?.data 102 | previousNode?.next = targetNode?.next 103 | 104 | return data 105 | } 106 | mutating func delete(about data: T) -> T? { 107 | guard let index = search(for: data) else { 108 | return nil 109 | } 110 | let data = delete(at: index) 111 | return data 112 | } 113 | mutating func deleteRear() -> T? { 114 | let lastIndex = size - 1 115 | return delete(at: lastIndex) 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /BasicConcepts/LinkedList/LinkedList_Ellen.swift: -------------------------------------------------------------------------------- 1 | // 2 | // LinkedList_Ellen.swift 3 | // Boj_Ellen 4 | // 5 | // Created by Ellen on 2021/12/17. 6 | // 7 | 8 | import Foundation 9 | 10 | final class Node { 11 | var value: T 12 | var next: Node? 13 | var previous: Node? 14 | 15 | init(value: T, previous: Node?, next: Node?) { 16 | self.value = value 17 | self.previous = previous 18 | self.next = next 19 | } 20 | } 21 | 22 | class LinkedList { 23 | var head: Node? 24 | weak var tail: Node? 25 | 26 | var empty: Bool { 27 | if head == nil { 28 | return true 29 | } else { 30 | return false 31 | } 32 | } 33 | 34 | func add(_ value: T) { 35 | if head == nil { 36 | head = Node(value: value, previous: nil, next: nil) 37 | tail = head 38 | } else { 39 | tail?.next = Node(value: value, previous: tail, next: nil) 40 | } 41 | } 42 | 43 | func addFirst(_ value: T) { 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /BasicConcepts/LinkedList/LinkedList_Geon.swift: -------------------------------------------------------------------------------- 1 | // 2 | // LinkedList_Geon.swift 3 | // Execution 4 | // 5 | // Created by 김준건 on 2021/12/14. 6 | // 7 | 8 | import Foundation 9 | 10 | class Node { 11 | var data: T 12 | var next: Node? 13 | 14 | init(data: T, next: Node?) { 15 | self.data = data 16 | self.next = next 17 | } 18 | 19 | } 20 | 21 | final class LinkedList { 22 | var head: Node? 23 | var tail: Node? 24 | var isEmpty: Bool { 25 | return head == nil 26 | } 27 | 28 | func append(data: T) { 29 | let newNode = Node(data: data, next: nil) 30 | if isEmpty { 31 | head = newNode 32 | tail = head 33 | } else { 34 | tail?.next = newNode 35 | tail = newNode 36 | } 37 | } 38 | 39 | func removeFirst() -> Node? { 40 | defer { 41 | head = head?.next 42 | if isEmpty { 43 | tail = nil 44 | } 45 | } 46 | return head 47 | } 48 | 49 | func removeAll() { 50 | head = nil 51 | tail = nil 52 | } 53 | 54 | func peekFirst() -> Node? { 55 | return head 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /BasicConcepts/LinkedList/LinkedList_Soll.swift: -------------------------------------------------------------------------------- 1 | // 2 | // LinkedList_Soll.swift 3 | // BasicConcepts 4 | // 5 | // Created by Dasoll Park on 2021/12/16. 6 | // 7 | 8 | final class Node { 9 | let item: T 10 | var next: Node? 11 | 12 | init(item: T, next: Node?) { 13 | self.item = item 14 | self.next = next 15 | } 16 | } 17 | 18 | final class LinkedList { 19 | private var head: Node? 20 | 21 | var isEmpty: Bool { 22 | head == nil 23 | } 24 | 25 | func insert(_ item: T) { 26 | if head == nil { 27 | head = Node(item: item, next: nil) 28 | return 29 | } 30 | var current = head 31 | while current?.next != nil { 32 | current = current?.next 33 | } 34 | current?.next = Node(item: item, next: nil) 35 | } 36 | 37 | func showItems() { 38 | var current = head 39 | while current != nil { 40 | print(current?.item ?? "", terminator: " ") 41 | current = current?.next 42 | } 43 | } 44 | 45 | func obtainLastItem() -> T? { 46 | if head == nil { 47 | return nil 48 | } 49 | var current = head 50 | while current?.next != nil { 51 | current = current?.next 52 | } 53 | return current?.item 54 | } 55 | 56 | func delete(item: T) { 57 | if head?.item == item { 58 | head = head?.next 59 | } 60 | 61 | var previous: Node? 62 | var current = head 63 | 64 | while current != nil && current?.item != item { 65 | previous = current 66 | current = current?.next 67 | } 68 | 69 | previous?.next = current?.next 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /BasicConcepts/LinkedList/LinkedList_Tacocat.swift: -------------------------------------------------------------------------------- 1 | // 2 | // LinkedList.swift 3 | // AlgorithmStudy_Exercise 4 | // 5 | // Created by Do Yi Lee on 2021/12/10. 6 | // 7 | 8 | import Foundation 9 | 10 | struct LinkedList { 11 | private var head: Node? 12 | private var tail: Node? 13 | } 14 | 15 | extension LinkedList { 16 | func isEmpty() -> Bool { 17 | return head == nil 18 | } 19 | 20 | mutating func append(_ value: Value) { 21 | if isEmpty() { 22 | head = Node(value: value) 23 | tail = head 24 | return 25 | } 26 | 27 | tail?.next = Node(value: value) 28 | tail = tail?.next 29 | } 30 | 31 | mutating func remove() -> Value? { 32 | defer { head = head?.next } 33 | return head?.value 34 | } 35 | 36 | mutating func removeAll() { 37 | head = nil 38 | tail = nil 39 | } 40 | 41 | func glance() -> Value? { 42 | return head?.value 43 | } 44 | } 45 | 46 | class Node { 47 | var value: Value 48 | var next: Node? = nil 49 | 50 | init(value: Value) { 51 | self.value = value 52 | } 53 | 54 | init(value: Value, next: Node?) { 55 | self.value = value 56 | self.next = next 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /BasicConcepts/LinkedList/LinkedList_수박.swift: -------------------------------------------------------------------------------- 1 | // 2 | // LinkedList_수박.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by kjs on 2021/12/08. 6 | // 7 | 8 | import Foundation 9 | 10 | class Node { 11 | private(set) var value: AnyType 12 | weak var prev: Node? 13 | var next: Node? 14 | 15 | init(value: AnyType, next: Node? = nil) { 16 | self.value = value 17 | } 18 | 19 | func updateValue(by value: AnyType) { 20 | self.value = value 21 | } 22 | } 23 | 24 | struct LinkedList { 25 | private(set) var head: Node? 26 | private(set) weak var tail: Node? 27 | 28 | var isEmpty: Bool { 29 | return head == nil 30 | } 31 | 32 | mutating func append(_ value: AnyType) { 33 | let newNode = Node(value: value) 34 | 35 | if isEmpty { 36 | head = newNode 37 | head?.next = newNode 38 | } else { 39 | tail?.next = newNode 40 | newNode.prev = tail 41 | } 42 | 43 | tail = newNode 44 | } 45 | 46 | var target: Node? { 47 | return head?.next 48 | } 49 | 50 | mutating func remove(target: Node?) { 51 | var targetToDelete = head 52 | 53 | while target !== targetToDelete { 54 | targetToDelete = targetToDelete?.next 55 | } 56 | 57 | if let previousNode = targetToDelete?.prev { 58 | previousNode.next = targetToDelete?.next 59 | previousNode.next?.prev = previousNode 60 | } else { 61 | head = targetToDelete?.next 62 | } 63 | } 64 | 65 | mutating func removeLast() { 66 | tail = tail?.prev 67 | tail?.next = nil 68 | } 69 | 70 | init() { } 71 | 72 | init(headValue: AnyType) { 73 | self.append(headValue) 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /BasicConcepts/Maze/MazaBFS_수박.swift: -------------------------------------------------------------------------------- 1 | // 2 | // MazaBFS_수박.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by kjs on 2022/02/15. 6 | // 7 | 8 | struct Node: CustomStringConvertible { 9 | var order = 0 10 | var isVisitied = false 11 | var isBlocked: Bool 12 | 13 | var description: String { 14 | if isBlocked { 15 | return "-" 16 | } else if isVisitied == false { 17 | return "X" 18 | } else { 19 | return order.description 20 | } 21 | } 22 | } 23 | 24 | var path: Node { 25 | Node(isBlocked: false) 26 | } 27 | 28 | var wall: Node { 29 | Node(isBlocked: true) 30 | } 31 | 32 | var map: [[Node]] = [ 33 | [path, path, path, path, wall, path, path], 34 | [path, wall, wall, path, wall, path, wall], 35 | [path, path, wall, path, path, path, path], 36 | [wall, path, wall, wall, wall, wall, wall], 37 | [path, path, path, path, wall, path, path], 38 | [wall, path, wall, wall, wall, wall, path], 39 | [path, path, path, path, path, path, path] 40 | ] 41 | 42 | var queue = Queue<(y: Int, x: Int)>() 43 | queue.enqueue((y: .zero, x: .zero)) 44 | 45 | while queue.isEmpty == false { 46 | guard let (y, x) = queue.dequeue() else { break } 47 | map[y][x].isVisitied = true 48 | 49 | if y == map.count-1, x == map[y].count-1 { 50 | break 51 | } 52 | 53 | let directions = [ 54 | (y: y+1, x: x), 55 | (y: y-1, x: x), 56 | (y: y, x: x+1), 57 | (y: y, x: x-1) 58 | ] 59 | 60 | directions 61 | .filter { (y: Int, x: Int) in 62 | y < map.count && 63 | x < map[0].count && 64 | y >= 0 && 65 | x >= 0 && 66 | map[y][x].isBlocked == false && 67 | map[y][x].isVisitied == false 68 | } 69 | .forEach { (nextY: Int, nextX: Int) in 70 | map[nextY][nextX].order = map[y][x].order + 1 71 | queue.enqueue((nextY, nextX)) 72 | } 73 | } 74 | 75 | map.forEach { row in 76 | print(row) 77 | } 78 | 79 | 80 | 81 | 82 | struct Queue { 83 | private var linkedList = LinkedList() 84 | 85 | var head: AnyType? { 86 | linkedList.head?.value 87 | } 88 | 89 | var tail: AnyType? { 90 | linkedList.tail?.value 91 | } 92 | 93 | var isEmpty: Bool { 94 | linkedList.head == nil 95 | } 96 | 97 | mutating func enqueue(_ value: AnyType) { 98 | linkedList.append(value) 99 | } 100 | 101 | mutating func dequeue() -> AnyType? { 102 | return linkedList.removeFirst() 103 | } 104 | } 105 | 106 | // MARK: - components 107 | extension Queue { 108 | private class Node { 109 | private(set) var value: AnyType 110 | weak var prev: Node? 111 | var next: Node? 112 | 113 | init(value: AnyType, next: Node? = nil) { 114 | self.value = value 115 | } 116 | 117 | func updateValue(by value: AnyType) { 118 | self.value = value 119 | } 120 | } 121 | 122 | private struct LinkedList { 123 | private(set) var head: Node? 124 | private(set) weak var tail: Node? 125 | 126 | var isEmpty: Bool { 127 | return head == nil 128 | } 129 | 130 | mutating func append(_ value: AnyType) { 131 | let newNode = Node(value: value) 132 | 133 | if isEmpty { 134 | head = newNode 135 | } else { 136 | tail?.next = newNode 137 | newNode.prev = tail 138 | } 139 | 140 | tail = newNode 141 | } 142 | 143 | mutating func removeFirst() -> AnyType? { 144 | defer { 145 | head = head?.next 146 | } 147 | 148 | return head?.value 149 | } 150 | 151 | init() { } 152 | 153 | init(headValue: AnyType) { 154 | self.append(headValue) 155 | } 156 | } 157 | } 158 | 159 | -------------------------------------------------------------------------------- /BasicConcepts/Maze/MazeBFS_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Maze2_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2022/02/14. 6 | // 7 | 8 | /* 9 | 미로 문제를 BFS로 풀이해보자. 10 | */ 11 | 12 | var maze = [ 13 | [0, 0, 0, 0, 1, 0, 0], 14 | [0, 1, 1, 0, 1, 0, 1], 15 | [0, 0, 1, 0, 0, 0, 0], 16 | [1, 0, 1, 1, 1, 1, 1], 17 | [0, 0, 0, 0, 1, 0, 0], 18 | [1, 0, 1, 1, 1, 1, 0], 19 | [0, 0, 0, 0, 0, 0, 0] 20 | ].map { $0.map { $0.description } } 21 | 22 | //더블 스택을 이용한 큐 구현 23 | struct Queue { 24 | private var enqueueStack = [Element]() 25 | private var dequeueStack = [Element]() 26 | 27 | var isEmpty: Bool { 28 | return enqueueStack.isEmpty && dequeueStack.isEmpty 29 | } 30 | 31 | mutating func enqueue(_ element: Element) { 32 | enqueueStack.append(element) 33 | } 34 | 35 | mutating func dequeue() -> Element? { 36 | if dequeueStack.isEmpty { 37 | dequeueStack = enqueueStack.reversed() 38 | enqueueStack.removeAll() 39 | } 40 | 41 | return dequeueStack.popLast() 42 | } 43 | 44 | mutating func removeAll() { 45 | enqueueStack.removeAll() 46 | dequeueStack.removeAll() 47 | } 48 | } 49 | 50 | //좌표값을 나타내기 위한 자료구조 51 | struct Coord { 52 | let x: Int 53 | let y: Int 54 | } 55 | 56 | //풀이 57 | func printMaze() { 58 | print( 59 | maze 60 | .map { $0.joined(separator: "\t") } 61 | .joined(separator: "\n") 62 | ) 63 | print() 64 | } 65 | 66 | //해당 지점으로 이동 가능한지 체크하는 함수 67 | func isMovable(to coord: Coord) -> Bool { 68 | if coord.x < 0 || coord.x >= 7 || 69 | coord.y < 0 || coord.y >= 7 || 70 | maze[coord.y][coord.x] != "0" { 71 | return false 72 | } else { 73 | return true 74 | } 75 | } 76 | 77 | //BFS를 이용하여 출구를 찾는 함수 78 | func findExit() { 79 | var queue = Queue() 80 | let startingPoint = Coord(x: 0, y: 0) 81 | maze[startingPoint.y][startingPoint.x] = "-1" //방문 표시 82 | queue.enqueue(startingPoint) 83 | 84 | while let currentPoint = queue.dequeue() { //queue.isEmpty를 이용해도 됨 85 | let currentX = currentPoint.x 86 | let currentY = currentPoint.y 87 | let adjacentPoints = [ 88 | Coord(x: currentX, y: currentY - 1), 89 | Coord(x: currentX + 1, y: currentY), 90 | Coord(x: currentX, y: currentY + 1), 91 | Coord(x: currentX - 1, y: currentY) 92 | ] 93 | 94 | for nextPoint in adjacentPoints { 95 | if isMovable(to: nextPoint) { 96 | maze[nextPoint.y][nextPoint.x] = (Int(maze[currentY][currentX])! - 1).description //방문 표시 97 | queue.enqueue(nextPoint) 98 | } 99 | 100 | if nextPoint.x == 6 && nextPoint.y == 6 { //해당 다음 지점이 출구라면 101 | queue.removeAll() 102 | break 103 | } 104 | } 105 | } 106 | } 107 | 108 | //경로를 역추적하여 출구까지 가는 화살표를 그려줄 함수 109 | func tracePathBack(from coord: Coord) { 110 | if coord.x == 0 && coord.y == 0 { //base case - 출발지점 도착 시 111 | return 112 | } else { // recursive case - 더 추적해야 하는 경우 113 | let currentDistance = Int(maze[coord.y][coord.x])! 114 | let nextDistance = currentDistance + 1 115 | let adjacentPoints = [ 116 | Coord(x: coord.x, y: coord.y - 1), 117 | Coord(x: coord.x + 1, y: coord.y), 118 | Coord(x: coord.x, y: coord.y + 1), 119 | Coord(x: coord.x - 1, y: coord.y) 120 | ] 121 | 122 | for (direction, nextPoint) in adjacentPoints.enumerated() 123 | where nextPoint.x >= 0 && nextPoint.x <= 6 && 124 | nextPoint.y >= 0 && nextPoint.y <= 6 && 125 | Int(maze[nextPoint.y][nextPoint.x])! == nextDistance { 126 | tracePathBack(from: nextPoint) 127 | 128 | if direction == 0 { 129 | maze[nextPoint.y][nextPoint.x] = "↓" 130 | } else if direction == 1 { 131 | maze[nextPoint.y][nextPoint.x] = "←" 132 | } else if direction == 2 { 133 | maze[nextPoint.y][nextPoint.x] = "↑" 134 | } else { 135 | maze[nextPoint.y][nextPoint.x] = "→" 136 | } 137 | 138 | break 139 | } 140 | } 141 | } 142 | 143 | printMaze() 144 | findExit() 145 | tracePathBack(from: Coord(x: 6, y: 6)) 146 | maze[6][6] = "x" 147 | printMaze() 148 | 149 | -------------------------------------------------------------------------------- /BasicConcepts/Maze/MazeBFS_Soll.swift: -------------------------------------------------------------------------------- 1 | // 2 | // MazeBFS_Soll.swift 3 | // YagomStudy5th 4 | // 5 | // Created by Dasoll Park on 2022/02/19. 6 | // 7 | 8 | import Foundation 9 | 10 | struct Storage { 11 | private var queue: [T] = [] 12 | 13 | var count: Int { 14 | queue.count 15 | } 16 | 17 | var isEmpty: Bool { 18 | queue.isEmpty 19 | } 20 | 21 | mutating func enqueue(_ element: T) { 22 | queue.append(element) 23 | } 24 | 25 | mutating func dequeue() -> T? { 26 | queue.removeFirst() 27 | } 28 | } 29 | 30 | struct Position { 31 | var x: Int 32 | var y: Int 33 | } 34 | 35 | final class Maze { 36 | var maze: [[Int]] = [ 37 | [0, 0, 0, 0, 1, 0, 0], 38 | [0, 1, 1, 0, 1, 0, 1], 39 | [0, 0, 1, 0, 0, 0, 0], 40 | [1, 0, 1, 1, 1, 1, 1], 41 | [0, 0, 0, 0, 1, 0, 0], 42 | [1, 0, 1, 1, 1, 1, 0], 43 | [0, 0 ,0, 0, 0, 0, 0] 44 | ] 45 | var current = Position(x: 0, y: 0) 46 | var storage: Storage = Storage() 47 | var isFound = false 48 | let sizeOfMaze = 7 49 | 50 | func start() { 51 | storage.enqueue(current) 52 | maze[0][0] = -1 53 | 54 | // && isFound == false 조건문을 통해 queue에 항목이 남아있어도 빠져나올수있도록 해준다. 55 | while storage.isEmpty == false && isFound == false { 56 | 57 | guard let currentPosition = storage.dequeue() else { return } 58 | 59 | for direction in 0..<4 { 60 | if movable(currentPosition, direction) { 61 | 62 | guard let nextPosition = move(currentPosition, direction) else { return } 63 | 64 | maze[nextPosition.x][nextPosition.y] = maze[currentPosition.x][currentPosition.y] - 1 65 | 66 | // 목적지를 찾은 경우 for문은 빠져나가도 while 문은 더 돈다 67 | if nextPosition.x == sizeOfMaze - 1 && nextPosition.y == sizeOfMaze - 1 { 68 | print("Found the path") 69 | isFound = true 70 | // storae removeAll()은 O(n)이다. 71 | break 72 | } 73 | storage.enqueue(nextPosition) 74 | } 75 | } 76 | } 77 | maze.forEach { print($0) } 78 | } 79 | 80 | func movable(_ current: Position, _ direction: Int) -> Bool { 81 | var isValidCell = false 82 | 83 | switch direction { 84 | case 0: 85 | if current.x - 1 >= 0 { 86 | isValidCell = maze[current.x - 1][current.y] == 0 87 | } 88 | case 1: 89 | if current.y + 1 <= sizeOfMaze - 1 { 90 | isValidCell = maze[current.x][current.y + 1] == 0 91 | } 92 | case 2: 93 | if current.x + 1 <= sizeOfMaze - 1 { 94 | isValidCell = maze[current.x + 1][current.y] == 0 95 | } 96 | 97 | case 3: 98 | if current.y - 1 >= 0 { 99 | isValidCell = maze[current.x][current.y - 1] == 0 100 | } 101 | default: 102 | return isValidCell 103 | } 104 | return isValidCell 105 | } 106 | 107 | func move(_ current: Position, _ direction: Int) -> Position? { 108 | switch direction { 109 | case 0: 110 | return Position(x: current.x - 1, y: current.y) 111 | case 1: 112 | return Position(x: current.x, y: current.y + 1) 113 | case 2: 114 | return Position(x: current.x + 1, y: current.y) 115 | case 3: 116 | return Position(x: current.x, y: current.y - 1) 117 | default: 118 | return nil 119 | } 120 | } 121 | } 122 | 123 | let maze = Maze() 124 | maze.start() 125 | -------------------------------------------------------------------------------- /BasicConcepts/Maze/MazeDFS_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Maze_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2021/12/24. 6 | // 7 | 8 | /* 9 | 미로 찾기 문제는 DFS/BFS로 풀 수 있는 문제이다. 10 | 여기서는 Recursion을 이용한 DFS로 풀어보려고 한다. 11 | */ 12 | 13 | let passage = "0" 14 | let wall = "1" 15 | var maze = [ 16 | [0, 0, 0, 0, 0, 0, 0, 1], 17 | [0, 1, 1, 0, 1, 1, 0, 1], 18 | [0, 0, 0, 1, 0, 0, 0, 1], 19 | [0, 1, 0, 0, 1, 1, 0, 0], 20 | [0, 1, 1, 1, 0, 0, 1, 1], 21 | [0, 1, 0, 0, 0, 1, 0, 1], 22 | [0, 0, 0, 1, 0, 0, 0, 1], 23 | [0, 1, 1, 1, 0, 1, 0, 0] 24 | ].map { $0.map { String($0) } } 25 | 26 | //풀이 27 | //길 표시를 위한 값들을 먼저 정의 28 | let blockedPassage = "X" 29 | let destination = "#" 30 | enum Direction: String, CustomStringConvertible { 31 | case up = "↑" 32 | case down = "↓" 33 | case left = "←" 34 | case right = "→" 35 | 36 | var description: String { 37 | return self.rawValue 38 | } 39 | } 40 | 41 | @discardableResult 42 | func findPath(x column: Int, y row: Int) -> Bool { 43 | if row < 0 || row > 7 || column < 0 || column > 7 { //base case 1 - 범위 벗어남 44 | return false 45 | } else if maze[row][column] != passage { //base case 2 - 해당 위치로 이동했는데 통로가 아닌 경우 46 | return false 47 | } else if row == 7 && column == 7 { //base case 3 - 목적지 도착 48 | maze[row][column] = destination 49 | return true 50 | } else { //recursive case - 이동한 위치가 통로인 경우 51 | maze[row][column] = Direction.up.description 52 | if findPath(x: column, y: row - 1) { return true } 53 | 54 | maze[row][column] = Direction.right.description 55 | if findPath(x: column + 1, y: row) { return true } 56 | 57 | maze[row][column] = Direction.down.description 58 | if findPath(x: column, y: row + 1) { return true } 59 | 60 | maze[row][column] = Direction.left.description 61 | if findPath(x: column - 1, y: row) { return true } 62 | 63 | //각각의 방향을 다 돌아봤는데도 출구로 가는 길이 없다면 현재 위치는 갈 수 없는 길 64 | maze[row][column] = blockedPassage 65 | return false 66 | } 67 | } 68 | 69 | func printMaze() { 70 | print(maze.map { $0.joined(separator: " ") }.joined(separator: "\n")) 71 | print() 72 | } 73 | 74 | printMaze() 75 | findPath(x: 0, y: 0) 76 | printMaze() 77 | -------------------------------------------------------------------------------- /BasicConcepts/Maze/MazeDFS_수박.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Maze_수박.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by kjs on 2022/01/03. 6 | // 7 | 8 | struct Node: CustomStringConvertible { 9 | private var everVisitied = false 10 | private var everBlocked = false 11 | 12 | let isWall: Bool 13 | let isPath: Bool 14 | 15 | var description: String { 16 | if isWall { 17 | return "W" 18 | } else if everBlocked { 19 | return "B" 20 | } else if everVisitied { 21 | return "O" 22 | } else { 23 | return "X" 24 | } 25 | } 26 | 27 | var isVisited: Bool { 28 | get { 29 | everVisitied 30 | } 31 | set { 32 | everVisitied = newValue 33 | } 34 | } 35 | 36 | var isBlocked: Bool { 37 | get { 38 | everBlocked 39 | } 40 | set { 41 | everBlocked = newValue 42 | } 43 | } 44 | 45 | init(isWall: Bool) { 46 | self.isWall = isWall 47 | self.isPath = !isWall 48 | } 49 | } 50 | 51 | var wall: Node { 52 | Node(isWall: true) 53 | } 54 | var path: Node { 55 | Node(isWall: false) 56 | } 57 | 58 | var maze = [ 59 | [path, path, path, path, path, path, path, wall], 60 | [path, wall, wall, path, wall, wall, path, wall], 61 | [path, wall, path, wall, path, path, path, wall], 62 | [path, wall, path, path, wall, wall, path, path], 63 | [path, wall, wall, wall, path, path, wall, wall], 64 | [path, wall, path, path, path, wall, path, wall], 65 | [path, path, path, wall, path, path, path, wall], 66 | [path, wall, wall, wall, path, wall, path, path] 67 | ] 68 | 69 | let startPoint = maze[0][0] 70 | let endPoint = maze[maze.count-1][maze.count-1] 71 | 72 | func findMazePath(y: Int, x: Int) -> Bool { 73 | //base case with checking index 74 | guard y < maze.count, x < maze.count else { return false } 75 | guard y >= 0 , x >= 0 else { return false } 76 | //base case with checking state 77 | if maze[y][x].isWall { return false } 78 | if maze[y][x].isVisited { return false } 79 | 80 | maze[y][x].isVisited = true 81 | 82 | //goal 83 | if y == maze.count - 1 && x == maze.count - 1 { 84 | return true 85 | } 86 | 87 | let directions = [ 88 | (y: y+1, x: x), 89 | (y: y-1, x: x), 90 | (y: y, x: x+1), 91 | (y: y, x: x-1) 92 | ] 93 | var isPassed = false 94 | 95 | directions.forEach { point in 96 | if findMazePath(y: point.y, x: point.x) { 97 | isPassed = true 98 | } 99 | } 100 | 101 | if isPassed { 102 | return true 103 | } else { 104 | maze[y][x].isBlocked = true 105 | return false 106 | } 107 | } 108 | 109 | /* 110 | print(findMazePath(y: 0, x: 0) ? "There is a way!" : "You died") 111 | maze.forEach({ nodes in 112 | print(nodes) 113 | }) 114 | 115 | */ 116 | -------------------------------------------------------------------------------- /BasicConcepts/NQueensProblem/NQueensProblem_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // NQueensProblem_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2022/01/12. 6 | // 7 | 8 | /* 9 | N-Queens Problem은 대표적인 백트래킹/dfs 문제이다. 10 | 말을 하나씩 놓아보면서 상태공간트리 깊은 level로 들어가도록 풀이하면 된다. 11 | 유망(promising)하지 않은 노드는 탐색하지 않아도 되며 찾고자 하는 정답인 leaf 노드를 하나 이상 찾으면 된다. 12 | 13 | 여기서는 사용자 입력 size에 따른 size * size 크기의 N-Queens Problem을 풀어보려고 한다. 14 | 해는 하나만 찾아 볼 것이다. 15 | */ 16 | 17 | //입력 18 | print("체스판의 가로 세로 길이를 입력하십시오: ", terminator: "") 19 | let size = Int(readLine()!)! 20 | 21 | //각 말들은 row당 하나씩 두는 것으로 하며 각각의 row에서 어느 column에 둔 것인지 1차원 배열로 추적하기로 한다. 22 | let notYetPlaced = -1 23 | var chessboard = [Int]() 24 | for _ in 0...size { //체스판은 1 ~ size 인덱스를 사용 할 것이다. 25 | chessboard.append(notYetPlaced) 26 | } 27 | 28 | func isValidLocation(in row: Int) -> Bool { //말을 row행에 놓았을 때 해당 column 위치에 놓는 것이 유효한지 검증 29 | if row == 0 { return true } //0번 행은 존재하지 않으나 root노드이고 시작점이므로 언제나 유효하다고 봐야 함 30 | for prevRow in 1.. Bool { //row 행에 말을 막 놓은 상태 40 | if !isValidLocation(in: row) { //base case 1 - row행의 column위치에 말을 놓는 것이 부적합한 경우 41 | return false 42 | } else if row == size { //base case 2 - 모든 말이 잘 놓인 경우 43 | return true 44 | } else { //recursive case - row 행에 놓은 말은 괜찮지만 아직 말을 더 놓아봐야 하는 경우 45 | for column in 1...size { 46 | chessboard[row + 1] = column 47 | if deployQueen(in: row + 1) { return true } 48 | } 49 | return false 50 | } 51 | } 52 | 53 | func printChessBoard() { 54 | for row in 1...size { 55 | for _ in 1.. State { 26 | guard level != 0 else { return .go } 27 | 28 | for index in 1.. Bool { 45 | let currentState = nonPromising(level: y) 46 | 47 | switch currentState { 48 | case .blocked: 49 | return false 50 | case .reached: 51 | return true 52 | case .go: 53 | for x in 0.. { 9 | private var storage = [Element]() 10 | 11 | var size: Int { 12 | return storage.count 13 | } 14 | var isEmpty: Bool { 15 | return storage.isEmpty 16 | } 17 | var front: Element? { 18 | return storage.first 19 | } 20 | var rear: Element? { 21 | return storage.last 22 | } 23 | 24 | mutating func enqueue(_ element: Element) { 25 | storage.append(element) 26 | } 27 | mutating func dequeue() -> Element? { 28 | if isEmpty { 29 | return nil 30 | } 31 | return storage.removeFirst() 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /BasicConcepts/Queue/Queue_Geon.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Queue_Geon.swift 3 | // Execution 4 | // 5 | // Created by 김준건 on 2021/12/14. 6 | // 7 | 8 | import Foundation 9 | 10 | struct Queue { 11 | private var list: [Any] = [] 12 | 13 | mutating func enqueue(value: Any) { 14 | list.append(value) 15 | } 16 | 17 | mutating func dequeue() -> Any { 18 | if list.isEmpty { 19 | return false 20 | } else { 21 | return list.removeFirst() 22 | } 23 | } 24 | 25 | func empty() -> Any { 26 | if list.isEmpty { 27 | return true 28 | } else { 29 | return false 30 | } 31 | } 32 | 33 | func front() -> Any? { 34 | if list.isEmpty { 35 | return false 36 | } else { 37 | return list.first 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /BasicConcepts/Queue/Queue_Soll.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Queue_Soll.swift 3 | // BasicConcepts 4 | // 5 | // Created by Dasoll Park on 2021/12/16. 6 | // 7 | 8 | final class Queue { 9 | private var storage: [Element] = [] 10 | 11 | var head: Element? { 12 | storage.first 13 | } 14 | var isEmpty: Bool { 15 | storage.isEmpty 16 | } 17 | var size: Int { 18 | storage.count 19 | } 20 | 21 | func enqueue(_ item: Element) { 22 | storage.append(item) 23 | } 24 | 25 | func dequeue() -> Element? { 26 | if storage.isEmpty { return nil } 27 | let element = storage.first 28 | storage = Array(storage.dropFirst()) 29 | return element 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /BasicConcepts/Queue/Queue_Tacocat.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Queue_Tacocat.swift 3 | // AlgorithmStudy_Exercise 4 | // 5 | // Created by Do Yi Lee on 2021/12/10. 6 | // 7 | 8 | import Foundation 9 | 10 | class Queue { 11 | private var storage : [Element]? 12 | 13 | func enqueue(value: Element) { 14 | storage?.append(Element) 15 | } 16 | 17 | func dequeue() -> Element? { 18 | storage?.dropFirst() 19 | } 20 | 21 | func empty() { 22 | storage = nil 23 | } 24 | 25 | func front() -> Element? { 26 | storage?.first 27 | } 28 | 29 | func back() -> Element? { 30 | storage?.last 31 | } 32 | 33 | func size() -> Int? { 34 | storage?.count 35 | } 36 | } 37 | 38 | -------------------------------------------------------------------------------- /BasicConcepts/Queue/Queue_수박.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Queue_수박.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by kjs on 2021/12/09. 6 | // 7 | 8 | struct Queue { 9 | private var linkedList = LinkedList() 10 | 11 | var head: AnyType? { 12 | linkedList.head?.value 13 | } 14 | 15 | var tail: AnyType? { 16 | linkedList.tail?.value 17 | } 18 | 19 | var isEmpty: Bool { 20 | linkedList.head == nil 21 | } 22 | 23 | mutating func insert(_ value: AnyType) { 24 | linkedList.append(value) 25 | } 26 | 27 | mutating func delete() -> AnyType? { 28 | return linkedList.removeFirst() 29 | } 30 | } 31 | 32 | 33 | // MARK: - components 34 | extension Queue { 35 | private class Node { 36 | private(set) var value: AnyType 37 | weak var prev: Node? 38 | var next: Node? 39 | 40 | init(value: AnyType, next: Node? = nil) { 41 | self.value = value 42 | } 43 | 44 | func updateValue(by value: AnyType) { 45 | self.value = value 46 | } 47 | } 48 | 49 | private struct LinkedList { 50 | private(set) var head: Node? 51 | private(set) weak var tail: Node? 52 | 53 | var isEmpty: Bool { 54 | return head == nil 55 | } 56 | 57 | mutating func append(_ value: AnyType) { 58 | let newNode = Node(value: value) 59 | 60 | if isEmpty { 61 | head = newNode 62 | } else { 63 | tail?.next = newNode 64 | newNode.prev = tail 65 | } 66 | 67 | tail = newNode 68 | } 69 | 70 | mutating func removeFirst() -> AnyType? { 71 | defer { 72 | head = head?.next 73 | } 74 | 75 | return head?.value 76 | } 77 | 78 | init() { } 79 | 80 | init(headValue: AnyType) { 81 | self.append(headValue) 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /BasicConcepts/SequentialSearch/SequentialSearch_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SequentialSearch_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2021/12/20. 6 | // 7 | 8 | /* 9 | 순차탐색 구현 10 | 순차탐색은 일반적으로 '정렬되지 않은 컬렉션' 속에서 원하는 값을 찾는 알고리즘이다. 11 | 시간복잡도는 최악의 경우 O(n)이다. 12 | */ 13 | 14 | //MARK: - Iterative version 15 | func sequentialSearch(for value: Element, in storage: Container) -> Container.Index? where Element: Equatable, Container: Collection, Container.Element == Element { 16 | for index in storage.indices { 17 | if storage[index] == value { 18 | return index 19 | } 20 | } 21 | 22 | return nil 23 | } 24 | 25 | //MARK: - Recursive version 26 | func recursiveSeqSearch(for value: Element, in storage: Container, from startIndex: Container.Index, to endIndex: Container.Index) -> Container.Index? where Element: Equatable, Container: Collection, Container.Element == Element, Container.Index: AdditiveArithmetic, Container.Index == Int { 27 | 28 | if startIndex > endIndex { //base case 1 - 모든 값을 조회했으나 찾지 못한 경우 29 | return nil 30 | } else if storage[startIndex] == value { //base case 2 - 값을 찾은 경우 31 | return startIndex 32 | } else { //recursive case - 값을 더 조회해봐야 하는 경우 33 | return recursiveSeqSearch(for: value, in: storage, from: startIndex + 1, to: endIndex) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /BasicConcepts/SequentialSearch/SequentialSearch_Geon.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SequentialSearch_Geon.swift 3 | // Excution 4 | // 5 | // Created by 김준건 on 2021/12/24. 6 | // 7 | 8 | func search(into container: [T], target: T, startIndex: Int, endIndex: Int) -> Int? { 9 | if startIndex > endIndex { 10 | return nil 11 | } else if container[startIndex] == target { 12 | return startIndex 13 | } else { 14 | return search(into: container, target: target, startIndex: startIndex + 1, endIndex: endIndex) 15 | } 16 | } 17 | 18 | func search(into container: [T], target: T) -> Int? { 19 | for index in container.indices { 20 | if container[index] == target { 21 | return index 22 | } 23 | } 24 | return nil 25 | } 26 | -------------------------------------------------------------------------------- /BasicConcepts/SequentialSearch/SequentialSearch_Soll.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SequentialSearch_Soll.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by Dasoll Park on 2021/12/23. 6 | // 7 | 8 | import Foundation 9 | 10 | func sequentialSearch(data: [Int], count: Int, target: Int) -> Int { 11 | for index in 0.. Int { 20 | if begin > end { 21 | return -1 22 | } else if target == data[begin] { 23 | return begin 24 | } else { 25 | return sequentialSearch(data: data, begin: begin + 1, end: end, target: target) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /BasicConcepts/SequentialSearch/SequentialSearch_Tacocat.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SequentialSearch.swift 3 | // AlgorithmStudy_Exercise 4 | // 5 | // Created by Do Yi Lee on 2021/12/24. 6 | // 7 | 8 | import Foundation 9 | 10 | var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 11 | 12 | func search(_ start: Int, _ end: Int, _ target: Int) -> Int { 13 | if start > end { 14 | return -1 15 | } else { 16 | let middle = (start + end) / 2 17 | if data[middle] == target { 18 | return middle 19 | } 20 | 21 | let index = search(start, middle - 1, target) 22 | 23 | if index != -1 { 24 | return index 25 | } else { 26 | return search(middle + 1, end, target) 27 | } 28 | } 29 | } 30 | 31 | print(search(0, 8, 5)) 32 | -------------------------------------------------------------------------------- /BasicConcepts/SequentialSearch/SequentialSearch_수박.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SequentialSearch_수박.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by kjs on 2021/12/23. 6 | // 7 | 8 | enum SearchError: Error { 9 | case elementIsNotExist 10 | } 11 | 12 | func sequentialSearchOnIteration( 13 | element: Element, 14 | within array: [Element] 15 | ) -> Result<(index: Int, element: Element), Error> { 16 | for index in array.indices { 17 | if element == array[index] { 18 | return .success((index, array[index])) 19 | } 20 | } 21 | 22 | return .failure(SearchError.elementIsNotExist) 23 | } 24 | 25 | func sequentialSearchOnRecusion( 26 | element: Element, 27 | within array: [Element] 28 | ) -> Result<(index: Int, element: Element), Error> { 29 | 30 | func recursion( 31 | target: Element, 32 | where index: Int, 33 | within array: [Element] 34 | ) -> Result<(index: Int, element: Element), Error> { 35 | if index >= array.count { 36 | return .failure(SearchError.elementIsNotExist) 37 | } else if array[index] == element { 38 | return .success((index, array[index])) 39 | } else { 40 | return recursion(target: element, where: index+1, within: array) 41 | } 42 | } 43 | 44 | return recursion(target: element, where: .zero, within: array) 45 | } 46 | -------------------------------------------------------------------------------- /BasicConcepts/Stack/Stack_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Stack_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2021/12/06. 6 | // 7 | 8 | struct Stack { 9 | private var storage = [Element]() 10 | 11 | var size: Int { 12 | return storage.count 13 | } 14 | var isEmpty: Bool { 15 | return storage.isEmpty 16 | } 17 | var top: Element? { 18 | return storage.last 19 | } 20 | 21 | mutating func push(_ element: Element) { 22 | storage.append(element) 23 | } 24 | mutating func pop() -> Element? { 25 | return storage.popLast() 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /BasicConcepts/Stack/Stack_Ellen.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Stack_Ellen.swift 3 | // BasicConcepts 4 | // 5 | // Created by Ellen on 2021/12/10. 6 | // 7 | 8 | import Foundation 9 | 10 | final class Node { 11 | var value: T 12 | var next: Node? 13 | var previous: Node? 14 | 15 | init(value: T, previous: Node?, next: Node?) { 16 | self.value = value 17 | self.previous = previous 18 | self.next = next 19 | } 20 | } 21 | 22 | class Stack { 23 | var top: Node? 24 | 25 | var empty: Bool { 26 | if top == nil { 27 | return true 28 | } else { 29 | return false 30 | } 31 | } 32 | 33 | func push(_ value: T) { 34 | if top == nil { 35 | top = Node(value: value, previous: nil, next: nil) 36 | } else { 37 | top?.next = Node(value: value, previous: top, next: nil) 38 | top = top?.next 39 | } 40 | } 41 | 42 | func pop() { 43 | print(top?.value as Any) 44 | top = top?.previous 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /BasicConcepts/Stack/Stack_Geon.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Stack_Geon.swift 3 | // Execution 4 | // 5 | // Created by 김준건 on 2021/12/14. 6 | // 7 | 8 | import Foundation 9 | 10 | struct Stack { 11 | private var list: [Any] = [] 12 | 13 | mutating func push(value: Any) { 14 | list.append(value) 15 | } 16 | 17 | mutating func pop() -> Any { 18 | if list.isEmpty { 19 | return false 20 | } else { 21 | return list.removeLast() 22 | } 23 | } 24 | 25 | func empty() -> Any { 26 | if list.isEmpty { 27 | return true 28 | } else { 29 | return false 30 | } 31 | } 32 | 33 | func top() -> Any? { 34 | if list.isEmpty { 35 | return false 36 | } else { 37 | return list.last 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /BasicConcepts/Stack/Stack_Soll.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Stack_Soll.swift 3 | // BasicConcepts 4 | // 5 | // Created by Dasoll Park on 2021/12/16. 6 | // 7 | 8 | final class Stack { 9 | private var stack: [Element] = [] 10 | 11 | var top: Element? { 12 | stack.last 13 | } 14 | var isEmpty: Bool { 15 | stack.isEmpty 16 | } 17 | var size: Int { 18 | stack.count 19 | } 20 | 21 | func push(item: Element) { 22 | stack.append(item) 23 | } 24 | 25 | func pop() -> Element? { 26 | stack.popLast() 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /BasicConcepts/Stack/Stack_Tacocat.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Stack.swift 3 | // AlgorithmStudy_Exercise 4 | // 5 | // Created by Do Yi Lee on 2021/12/10. 6 | // 7 | 8 | import Foundation 9 | 10 | struct Stack { 11 | var store: [Value] = [] 12 | 13 | mutating func push(this value: Value) { 14 | self.store.append(value) 15 | } 16 | 17 | mutating func pop() -> Value? { 18 | return self.store.popLast() 19 | } 20 | 21 | func isEmpty() -> Bool { 22 | store.isEmpty 23 | } 24 | 25 | func peek() -> Value? { 26 | if let last = self.store.last { 27 | return last 28 | } else { 29 | return nil 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /BasicConcepts/Stack/Stack_수박.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Stack_수박.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by kjs on 2021/12/09. 6 | // 7 | 8 | struct Stack { 9 | private var linkedList = LinkedList() 10 | private(set) var size = 0 11 | 12 | var top: AnyType? { 13 | linkedList.tail?.value 14 | } 15 | 16 | var isEmpty: Bool { 17 | linkedList.head == nil 18 | } 19 | 20 | mutating func push(_ value: AnyType) { 21 | linkedList.append(value) 22 | size += 1 23 | } 24 | 25 | mutating func pop() -> AnyType? { 26 | defer { 27 | if linkedList.removeLast() { 28 | size -= 1 29 | } 30 | } 31 | 32 | return linkedList.tail?.value 33 | } 34 | } 35 | 36 | 37 | // MARK: - components 38 | extension Stack { 39 | private class Node { 40 | private(set) var value: AnyType 41 | weak var prev: Node? 42 | var next: Node? 43 | 44 | init(value: AnyType, next: Node? = nil) { 45 | self.value = value 46 | } 47 | 48 | func updateValue(by value: AnyType) { 49 | self.value = value 50 | } 51 | } 52 | 53 | private struct LinkedList { 54 | private(set) var head: Node? 55 | private(set) weak var tail: Node? 56 | 57 | var isEmpty: Bool { 58 | return head == nil 59 | } 60 | 61 | mutating func append(_ value: AnyType) { 62 | let newNode = Node(value: value) 63 | 64 | if isEmpty { 65 | head = newNode 66 | } else { 67 | tail?.next = newNode 68 | newNode.prev = tail 69 | } 70 | 71 | tail = newNode 72 | } 73 | 74 | mutating func removeLast() -> Bool { 75 | defer { 76 | if tail == nil { 77 | head = nil 78 | } 79 | } 80 | 81 | if tail != nil { 82 | tail = tail?.prev 83 | tail?.next = nil 84 | return true 85 | } else { 86 | return false 87 | } 88 | } 89 | 90 | init() { } 91 | 92 | init(headValue: AnyType) { 93 | self.append(headValue) 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /Boj_Charlotte/1000_charlotte.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1000_charlotte.swift 3 | // Boj_Charlotte 4 | // 5 | // Created by 이예원 on 2021/12/09. 6 | // 7 | 8 | import Foundation 9 | 10 | let userInputArray = readLine()!.components(separatedBy: " ").map { Int($0)! } 11 | let a = userInputArray[0] 12 | let b = userInputArray[1] 13 | 14 | print(a + b) 15 | -------------------------------------------------------------------------------- /Boj_Charlotte/1001_charlotte.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1001_charlotte.swift 3 | // Boj_Charlotte 4 | // 5 | // Created by 이예원 on 2021/12/09. 6 | // 7 | 8 | import Foundation 9 | 10 | let userInputArray = readLine()!.components(separatedBy: " ").map { Int($0)! } 11 | let a = userInputArray[0] 12 | let b = userInputArray[1] 13 | 14 | print(a - b) 15 | -------------------------------------------------------------------------------- /Boj_Charlotte/1008_charlotte.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1008_charlotte.swift 3 | // Boj_Charlotte 4 | // 5 | // Created by 이예원 on 2021/12/09. 6 | // 7 | 8 | import Foundation 9 | 10 | let userInputArray = readLine()!.components(separatedBy: " ").map { Double($0)! } 11 | let a = userInputArray[0] 12 | let b = userInputArray[1] 13 | 14 | print(a / b) 15 | -------------------------------------------------------------------------------- /Boj_Charlotte/10171_charlotte.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10171_charlotte.swift 3 | // Boj_Charlotte 4 | // 5 | // Created by 이예원 on 2021/12/09. 6 | // 7 | 8 | import Foundation 9 | 10 | let cat = """ 11 | \\ /\\ 12 | ) ( ') 13 | ( / ) 14 | \\(__)| 15 | """ 16 | 17 | print(cat) 18 | -------------------------------------------------------------------------------- /Boj_Charlotte/10172_charlotte.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10172_charlotte.swift 3 | // Boj_Charlotte 4 | // 5 | // Created by 이예원 on 2021/12/09. 6 | // 7 | 8 | import Foundation 9 | 10 | let dog = """ 11 | |\\_/| 12 | |q p| /} 13 | ( 0 )\"\"\"\\ 14 | |"^"` | 15 | ||_/=\\\\__| 16 | """ 17 | 18 | print(dog) 19 | -------------------------------------------------------------------------------- /Boj_Charlotte/10430_charlotte.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10430_charlotte.swift 3 | // Boj_Charlotte 4 | // 5 | // Created by 이예원 on 2021/12/09. 6 | // 7 | 8 | import Foundation 9 | 10 | let userInputArray = readLine()!.components(separatedBy: " ").map { Int($0)! } 11 | let a = userInputArray[0] 12 | let b = userInputArray[1] 13 | let c = userInputArray[2] 14 | 15 | print((a+b)%c) 16 | print(((a%c) + (b%c))%c) 17 | print((a*b)%c) 18 | print(((a%c) * (b%c))%c) 19 | -------------------------------------------------------------------------------- /Boj_Charlotte/10718_charlotte.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10718_charlotte.swift 3 | // Boj_Charlotte 4 | // 5 | // Created by 이예원 on 2021/12/09. 6 | // 7 | 8 | import Foundation 9 | 10 | print("강한친구 대한육군") 11 | print("강한친구 대한육군") 12 | -------------------------------------------------------------------------------- /Boj_Charlotte/10869_charlotte.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10869_charlotte.swift 3 | // Boj_Charlotte 4 | // 5 | // Created by 이예원 on 2021/12/09. 6 | // 7 | 8 | import Foundation 9 | 10 | let userInputArray = readLine()!.components(separatedBy: " ").map { Int($0)! } 11 | let a = userInputArray[0] 12 | let b = userInputArray[1] 13 | 14 | 15 | print(a + b) 16 | print(a - b) 17 | print(a * b) 18 | print(a / b) 19 | print(a % b) 20 | -------------------------------------------------------------------------------- /Boj_Charlotte/10998_charlotte.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10998_charlotte.swift 3 | // Boj_Charlotte 4 | // 5 | // Created by 이예원 on 2021/12/09. 6 | // 7 | 8 | import Foundation 9 | 10 | let userInputArray = readLine()!.components(separatedBy: " ").map { Int($0)! } 11 | let a = userInputArray[0] 12 | let b = userInputArray[1] 13 | 14 | print(a * b) 15 | -------------------------------------------------------------------------------- /Boj_Charlotte/2557_charlotte.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 2557_charlotte.swift 3 | // Boj_Charlotte 4 | // 5 | // Created by 이예원 on 2021/12/09. 6 | // 7 | 8 | import Foundation 9 | 10 | print("Hello World!") 11 | -------------------------------------------------------------------------------- /Boj_Coden/1000_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1000_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2021/12/05. 6 | // 7 | 8 | let userInputs = readLine()! 9 | let numbers = userInputs.split(separator: " ").map { Int($0)! } 10 | let sum = numbers.reduce(0, +) 11 | print(sum) 12 | -------------------------------------------------------------------------------- /Boj_Coden/1001_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1001_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2021/12/06. 6 | // 7 | 8 | let userInputs = readLine()! 9 | let numbers = userInputs.split(separator: " ").map { Int($0)! } 10 | let difference = numbers[0] - numbers[1] 11 | print(difference) 12 | -------------------------------------------------------------------------------- /Boj_Coden/1008_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1008_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2021/12/06. 6 | // 7 | 8 | let userInputs = readLine()! 9 | let numbers = userInputs.split(separator: " ").map { Double($0)! } 10 | let division = numbers[0] / numbers[1] 11 | print(division) 12 | -------------------------------------------------------------------------------- /Boj_Coden/1012_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1012_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2022/02/06. 6 | // 7 | 8 | /* 9 | 유기농 배추 10 | 11 | 뭉쳐져 있는 배추 집단을 셈하면 되는 문제로써 DFS/BFS 풀이가 가능하다. 12 | 여기에서는 DFS로 풀이해보고자 한다. 13 | 14 | 1. 2차원배열의 처음부터 훑어가면서 배추가 심어져있는 곳을 찾는다. 15 | 2. 배추를 찾은 경우 DFS를 이용하여 주변의 배추까지 모두 파악한다. 16 | 3. 파악된 모든 배추를 없는 것으로 만들고 필요한 배추흰지렁이의 개수를 1 증가시킨다. 17 | 4. 이 과정을 배열의 끝에 도달할 때까지 반복한다. 18 | */ 19 | 20 | enum Field { //밭의 상태에 대한 열거형 21 | case empty 22 | case cabbageExists 23 | } 24 | 25 | var requiredNumberOfWorms = 0 26 | var cabbageField: [[Field]] = [] 27 | var width = 0 28 | var height = 0 29 | 30 | //입력 시작 31 | let numberOfTestCase = Int(readLine()!)! 32 | 33 | for _ in 1...numberOfTestCase { //테스트 케이스 수만큼 반복한다. 34 | let fieldInformation = readLine()!.split(separator: " ").compactMap { Int(String($0)) } 35 | width = fieldInformation[0] //가로 크기 36 | height = fieldInformation[1] //세로 크기 37 | let numberOfCabbage = fieldInformation[2] //심어져 있는 양배추의 개수 38 | 39 | cabbageField = Array(repeating: Array(repeating: Field.empty, count: width), count: height) //밭 만들기 40 | for _ in 1...numberOfCabbage { 41 | let position = readLine()!.split(separator: " ").compactMap { Int(String($0)) } 42 | let coordX = position[0] 43 | let coordY = position[1] 44 | 45 | cabbageField[coordY][coordX] = Field.cabbageExists 46 | } 47 | //밭에 대한 사전 설정 끝 48 | 49 | //탐색 시작 50 | requiredNumberOfWorms = 0 51 | for row in cabbageField.indices { 52 | for column in cabbageField[row].indices { 53 | if isCabbageClusterExist(x: column, y: row) { 54 | requiredNumberOfWorms += 1 55 | } 56 | } 57 | } 58 | print(requiredNumberOfWorms) 59 | } 60 | 61 | //재귀를 이용한 DFS로 배추군집을 파악할 함수 62 | //군집 존재 여하에 따라 Bool값을 리턴한다. 63 | func isCabbageClusterExist(x column: Int, y row: Int) -> Bool { 64 | if column < 0 || column >= width || row < 0 || row >= height { //base case 1 - 밭의 범위를 넘은 경우 65 | return false 66 | } else if cabbageField[row][column] == .empty { //base case 2 - 해당 구역은 비어있는 곳인 경우 67 | return false 68 | } else { //recursive case - 해당 구역에 양배추가 있는 경우 69 | cabbageField[row][column] = .empty //확인했으니 없는 곳으로 처리 70 | 71 | //상하좌우에 대해 재귀적으로 확인 72 | _ = isCabbageClusterExist(x: column, y: row - 1) 73 | _ = isCabbageClusterExist(x: column + 1, y: row) 74 | _ = isCabbageClusterExist(x: column, y: row + 1) 75 | _ = isCabbageClusterExist(x: column - 1, y: row) 76 | 77 | return true 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /Boj_Coden/10171_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10171_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2021/12/05. 6 | // 7 | 8 | print("\\ /\\") 9 | print(" ) ( ')") 10 | print("( / )") 11 | print(" \\(__)|") 12 | -------------------------------------------------------------------------------- /Boj_Coden/10172_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10172_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2021/12/05. 6 | // 7 | 8 | print("|\\_/|") 9 | print("|q p| /}") 10 | print("( 0 )\"\"\"\\") 11 | print("|\"^\"` |") 12 | print("||_/=\\\\__|") 13 | -------------------------------------------------------------------------------- /Boj_Coden/10430_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10430_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2021/12/06. 6 | // 7 | 8 | let userInputs = readLine()! 9 | let numbers = userInputs.split(separator: " ").map { Int($0)! } 10 | let firstNumber = numbers[0] 11 | let secondNumber = numbers[1] 12 | let thirdNumber = numbers[2] 13 | 14 | print((firstNumber + secondNumber) % thirdNumber) 15 | print(((firstNumber % thirdNumber) + (secondNumber % thirdNumber)) % thirdNumber) 16 | print((firstNumber * secondNumber) % thirdNumber) 17 | print(((firstNumber % thirdNumber) * (secondNumber % thirdNumber)) % thirdNumber) 18 | -------------------------------------------------------------------------------- /Boj_Coden/10718_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10718_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2021/12/05. 6 | // 7 | 8 | print("강한친구 대한육군") 9 | print("강한친구 대한육군") 10 | -------------------------------------------------------------------------------- /Boj_Coden/10816_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10816_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2021/12/24. 6 | // 7 | 8 | /* 9 | 숫자 카드 2 10 | 이 문제는 M개로 주어지는 각각의 숫자들이 N개 요소의 배열 내에서 몇개나 있는지 찾아내는 문제 11 | 12 | 풀이 1 - counting sort를 이용하는 방법 13 | 1. 주어지는 N만큼의 배열 공간을 미리 확보해둔다. array.reserveCapacity(N) 14 | 2. N개 요소의 배열을 처음부터 끝까지 읽으면서 나오는 숫자값을 인덱스로 사용한다. 그리고 해당 인덱스의 값에 1을 더한다. array[number] += 1 15 | 3. 2번 과정까지 거치면 모든 숫자가 몇개 나왔는지 누적합이 구해진다. 16 | 4. M개의 숫자들을 읽으면서 해당 값을 인덱스로 사용한다. 그리고 해당 인덱스에 해당하는 값을 단순히 출력한다. print(array[number]) 17 | 18 | 시간복잡도: O(N + M) 19 | 20 | 풀이 2 - Dictionary(해싱)를 이용하는 방식 21 | 1. N개의 숫자를 읽으면서 각각의 값에 대한 Dictionary를 만든다. 키값이 각각의 숫자가 되며 밸류값은 갯수가 된다. -> O(N) 22 | 존재하지 않는 키값이었다면 밸류는 1로 시작, 이미 존재한다면 1씩 누적시키기 23 | 2. M개 요소 배열을 읽으면서 각 숫자값을 Dictionary 키값으로 이용하여 밸류값을 출력한다. -> O(M) 24 | 25 | 시간복잡도: O(N + M) 26 | 27 | 풀이 3 - 정렬, 이진탐색, 재귀를 이용하는 방식 28 | 1. N개의 숫자를 정렬한다. -> O(Nlog N) 29 | 2. M의 숫자들을 읽으면서 이진탐색으로 찾는다. -> 각각 O(log N), 총 O(Mlog N) 30 | 3. 숫자를 찾으면 양 옆으로 재귀를 이용하여 중복된 값들까지 다 찾아 카운팅한다. -> 최악 O(N) 31 | 4. 카운팅된 수 출력 32 | 33 | 시간복잡도: O(Mlog N + N) 34 | */ 35 | 36 | 37 | //풀이 2. 38 | let n = Int(readLine()!)! 39 | let userCards = readLine()!.split(separator: " ").map { Int($0)! } 40 | let m = Int(readLine()!)! 41 | let targetCards = readLine()!.split(separator: " ").map { Int($0)! } 42 | 43 | //사용자 카드를 Dictionary로 카운팅하며 저장 44 | var userCardBook = [Int: Int]() 45 | for cardNumber in userCards { 46 | if let cardCount = userCardBook[cardNumber] { //이미 카운팅이 되고있던 카드 숫자라면 47 | userCardBook[cardNumber] = cardCount + 1 48 | } else { //처음 카운팅되는 경우라면 49 | userCardBook[cardNumber] = 1 50 | } 51 | } 52 | 53 | var result = "" 54 | for cardNumber in targetCards { 55 | if let cardCount = userCardBook[cardNumber] { //해당 카드숫자가 유저에게 존재하는 것이라면 56 | result += cardCount.description 57 | } else { //유저에게 존재하지 않는 카드 숫자라면 58 | result += "0" 59 | } 60 | result += " " 61 | } 62 | print(result) 63 | 64 | 65 | //아래는 시간초과로 인해 실제 제출한 코드 66 | import Foundation 67 | //라이노님의 Fast FileIO 68 | final class FileIO { 69 | private let buffer:[UInt8] 70 | private var index: Int = 0 71 | 72 | init(fileHandle: FileHandle = FileHandle.standardInput) { 73 | buffer = Array(fileHandle.readDataToEndOfFile())+[UInt8(0)] // 인덱스 범위 넘어가는 것 방지 74 | } 75 | 76 | @inline(__always) private func read() -> UInt8 { 77 | defer { index += 1 } 78 | 79 | return buffer[index] 80 | } 81 | 82 | @inline(__always) func readInt() -> Int { 83 | var sum = 0 84 | var now = read() 85 | var isPositive = true 86 | 87 | while now == 10 88 | || now == 32 { now = read() } // 공백과 줄바꿈 무시 89 | if now == 45 { isPositive.toggle(); now = read() } // 음수 처리 90 | while now >= 48, now <= 57 { 91 | sum = sum * 10 + Int(now-48) 92 | now = read() 93 | } 94 | 95 | return sum * (isPositive ? 1:-1) 96 | } 97 | 98 | @inline(__always) func readString() -> Int { 99 | var now = read() 100 | var str = 0 101 | 102 | while now == 10 || now == 32 { now = read() } // 공백과 줄바꿈 무시 103 | 104 | while now != 10, 105 | now != 32, 106 | now != 0 { 107 | str += Int(now) 108 | now = read() 109 | } 110 | 111 | return str 112 | } 113 | } 114 | 115 | let reader = FileIO() 116 | let n = reader.readInt() 117 | var userCards = [Int]() 118 | for _ in 0.. { 19 | private var storage = [Element]() 20 | 21 | var size: Int { 22 | return storage.count 23 | } 24 | var isEmpty: Bool { 25 | return storage.isEmpty 26 | } 27 | var top: Element? { 28 | return storage.last 29 | } 30 | 31 | mutating func push(_ element: Element) { 32 | storage.append(element) 33 | } 34 | mutating func pop() -> Element? { 35 | return storage.popLast() 36 | } 37 | } 38 | 39 | let numberOfInstructions = Int(readLine()!)! 40 | var stack = Stack() 41 | 42 | for _ in Int.zero..") 34 | -------------------------------------------------------------------------------- /Boj_Coden/1303_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1303_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2022/01/03. 6 | // 7 | 8 | /* 9 | 이 문제는 정해진 좌표 공간 내에서 동일한 값들이 얼마나 뭉쳐져 있는지 알아내야 한다. 10 | Counting Cells in a Blob 문제와 유사하며 DFS / BFS를 이용한 풀이가 가능하다. 11 | 12 | 여기서는 모든 좌표공간 Cell에 대해 DFS를 시도하여 각 값들이 얼마나 뭉쳐져 있는지 알아낼 것이다. 13 | */ 14 | 15 | //입력 16 | let sizeInput = readLine()!.split(separator: " ").map { Int($0)! } 17 | let widthSize = sizeInput[0] 18 | let heightSize = sizeInput[1] 19 | 20 | var battlefield = [[Character]]() //전장 지도 21 | for _ in 0.. Int { 36 | if column < 0 || column >= widthSize || row < 0 || row >= heightSize { //base case 1 - 좌표 벗어남 37 | return 0 38 | } else if battlefield[row][column] == neutralColor { //base case 2 - 이미 셈을 한 곳 39 | return 0 40 | } else if battlefield[row][column] != blobColor { //base case 3 - 셈을 하고 있던 팀과 다른 팀을 만난 경우 41 | return 0 42 | } else { //recursive case - 동일한 팀원을 찾은 경우 43 | battlefield[row][column] = neutralColor 44 | return 1 45 | + countNumberOfTeamMembers(x: column, y: row - 1, color: blobColor) 46 | + countNumberOfTeamMembers(x: column + 1, y: row, color: blobColor) 47 | + countNumberOfTeamMembers(x: column, y: row + 1, color: blobColor) 48 | + countNumberOfTeamMembers(x: column - 1, y: row, color: blobColor) 49 | } 50 | } 51 | 52 | for row in battlefield.indices { 53 | for column in battlefield[row].indices { 54 | let teamColor = battlefield[row][column] //countNumberOfTeamMembers 함수가 실행되면 셈이 된 곳은 neutralColor가 되므로 미리 저장해두기 55 | let numberOfTeamMembers = countNumberOfTeamMembers(x: column, y: row, color: teamColor) 56 | let teamPower = numberOfTeamMembers * numberOfTeamMembers 57 | 58 | if teamColor == allyColor { 59 | allyPower += teamPower 60 | } else { 61 | enemyPower += teamPower 62 | } 63 | } 64 | } 65 | 66 | print("\(allyPower) \(enemyPower)") 67 | -------------------------------------------------------------------------------- /Boj_Coden/15649_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 15649_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2022/02/07. 6 | // 7 | 8 | /* 9 | N과 M (1) 10 | 11 | 모든 경우의 수를 출력해야 하는 전형적인 DFS 문제이다. 12 | (N개 중에서 M개를 중복없이 순서있게 뽑는 순열문제로도 생각해볼 수 있다.) 13 | */ 14 | 15 | //입력 16 | let numberInputs = readLine()!.compactMap { $0.wholeNumberValue } 17 | let upperLimitOfNumbers = numberInputs[0] 18 | let numberToPick = numberInputs[1] 19 | 20 | //풀이 21 | var usedNumberCheckBook = Array(repeating: false, count: upperLimitOfNumbers + 1) //사용된 숫자를 파악하기 위한 배열 22 | usedNumberCheckBook[0] = true //숫자 0은 쓰지 않음 23 | var sequence = Array(repeating: 0, count: numberToPick) //결과를 보여줄 수열(배열) 24 | 25 | pickNumber(for: 0) 26 | 27 | //재귀적으로 (특정 인덱스 위치에 들어갈) 숫자를 뽑으면서 답을 찾아나갈 함수 28 | func pickNumber(for index: Int) { 29 | if index >= numberToPick { //base case - 필요한 숫자를 다 고른 경우 30 | print(sequence.map { $0.description }.joined(separator: " ")) 31 | return 32 | } else { //recursive case - 필요한 숫자를 다 고르지 못했으며 현재 index 위치에 숫자를 더 채워야 하는 경우 33 | for number in 1...upperLimitOfNumbers where usedNumberCheckBook[number] == false { 34 | usedNumberCheckBook[number] = true 35 | sequence[index] = number 36 | pickNumber(for: index + 1) 37 | usedNumberCheckBook[number] = false 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Boj_Coden/1759_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1759_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2022/02/06. 6 | // 7 | 8 | /* 9 | 암호 만들기 10 | 11 | 이 문제는 전형적인 DFS 문제이다. 12 | 1. 모든 경우의 수에 대해 탐색을 한다. 13 | 2. 상태공간트리에서 종단노드에 도착했을 때 조건에 맞는 답인지 체크한다. 14 | 3. 조건에 맞는다면 출력하고 조건에 맞지 않는다면 출력하지 않는다. 15 | */ 16 | 17 | //입력 18 | let numberInput = readLine()!.split(separator: " ").compactMap { Int(String($0)) } 19 | let alphabetInput = readLine()!.split(separator: " ").map { String($0) } 20 | 21 | let lengthOfPassword = numberInput[0] 22 | let numberOfAlphabets = numberInput[1] 23 | let alphabets = alphabetInput.sorted() //오름차순 정렬 24 | 25 | var password = Array(repeating: "", count: lengthOfPassword) //정답 출력을 위한 패스워드 배열 26 | 27 | guessPassword(for: 0, alphabetStartIndex: 0, numberOfVowels: 0, numberOfConsonants: 0) //0번 인덱스 자리부터 탐색을 시작 28 | 29 | //재귀 DFS로 암호를 찾아나갈 함수 30 | //alphabetStartIndex - 오름차순 정렬된 알파벳들 중 어디까지 쓰였는지 체크하기 위한 수. 비밀번호의 다음글자는 이 인덱스에 해당하는 알파벳부터 사용 가능하다. 31 | func guessPassword(for spot: Int, alphabetStartIndex: Int, numberOfVowels: Int, numberOfConsonants: Int) { 32 | if spot >= lengthOfPassword { //base case 1 - 암호가 일단 다 완성되어 인덱스(spot)가 암호 길이를 넘어간 경우 33 | if numberOfVowels >= 1 && numberOfConsonants >= 2 { //sub case 1 - 모음은 1개 이상, 자음은 2개 이상이어야 정답 조건 충족 34 | print(password.joined()) 35 | return 36 | } else { //sub case 2 - 암호는 완성됐지만 모음/자음 개수 조건을 충족하지 못하는 경우 37 | return 38 | } 39 | } else if alphabetStartIndex >= numberOfAlphabets { //base case 2 - 암호가 완성되지 못해서 더 배치해봐야 하는데 사용가능한 뒤쪽 알파벳이 존재하지 않는 경우 40 | return 41 | } else { //recursive case - 암호가 완성되지 않았으며 현재 위치에 배치 가능한 뒤쪽 알파벳이 남아있는 경우 42 | for index in alphabetStartIndex.. BFS 10 | */ 11 | 12 | struct Queue { 13 | private var enqueueStack = Array() 14 | private var dequeueStack = Array() 15 | 16 | var isEmpty: Bool { 17 | return enqueueStack.isEmpty && dequeueStack.isEmpty 18 | } 19 | 20 | mutating func enqueue(_ element: Element) { 21 | enqueueStack.append(element) 22 | } 23 | 24 | mutating func dequeue() -> Element? { 25 | if dequeueStack.isEmpty { 26 | dequeueStack = enqueueStack.reversed() 27 | enqueueStack.removeAll() 28 | } 29 | 30 | return dequeueStack.popLast() 31 | } 32 | 33 | mutating func removeAll() { 34 | enqueueStack.removeAll() 35 | dequeueStack.removeAll() 36 | } 37 | } 38 | 39 | struct Coord: Equatable { 40 | let x: Int 41 | let y: Int 42 | } 43 | 44 | //입력 45 | let sizeInputs = readLine()!.split(separator: " ").map { Int(String($0))! } 46 | let height = sizeInputs[0] 47 | let width = sizeInputs[1] 48 | 49 | var maze = [[Int]]() 50 | for _ in 0..() 58 | queue.enqueue(startingPoint) 59 | maze[0][0] = 2 //시작점을 2로 마킹하여 방문 표시 60 | 61 | while let currentCoord = queue.dequeue() { 62 | let adjacentCoord = [ 63 | Coord(x: currentCoord.x, y: currentCoord.y - 1), 64 | Coord(x: currentCoord.x + 1, y: currentCoord.y), 65 | Coord(x: currentCoord.x, y: currentCoord.y + 1), 66 | Coord(x: currentCoord.x - 1, y: currentCoord.y) 67 | ] 68 | 69 | for nextCoord in adjacentCoord where 70 | nextCoord.x >= 0 && nextCoord.x < width && 71 | nextCoord.y >= 0 && nextCoord.y < height && 72 | maze[nextCoord.y][nextCoord.x] == 1 { 73 | queue.enqueue(nextCoord) 74 | maze[nextCoord.y][nextCoord.x] = maze[currentCoord.y][currentCoord.x] + 1 //거리 표시 겸 방문 표시 75 | 76 | if nextCoord == destinationPoint { //만약 해당 다음 지점이 목적지라면 탐색을 종료해도 됨 77 | queue.removeAll() 78 | break 79 | } 80 | } 81 | } 82 | 83 | print(maze[destinationPoint.y][destinationPoint.x] - 1) //시작점을 2로 체크하기 시작했으므로 1 빼야 함 84 | -------------------------------------------------------------------------------- /Boj_Coden/2557_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 2557_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2021/12/05. 6 | // 7 | 8 | print("Hello World!") 9 | -------------------------------------------------------------------------------- /Boj_Coden/2588_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 2588_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2021/12/06. 6 | // 7 | 8 | let firstNumber = Int(readLine()!)! 9 | let secondNumber = Int(readLine()!)! 10 | 11 | let units = (secondNumber / 1) % 10 12 | let tens = (secondNumber / 10) % 10 13 | let hundreds = (secondNumber / 100) % 10 14 | 15 | print(firstNumber * units) 16 | print(firstNumber * tens) 17 | print(firstNumber * hundreds) 18 | print(firstNumber * secondNumber) 19 | -------------------------------------------------------------------------------- /Boj_Coden/2667_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 2667_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2022/01/03. 6 | // 7 | 8 | /* 9 | 단지번호 붙이기 10 | 전형적인 DFS/BFS 문제이다. 11 | 각 셀마다 탐색을 상하좌우로 해가면서 인접한 셀끼리 묶어 카운팅해주면 된다. 12 | 주의 할 것은, 이미 카운팅 된 셀은 다시 계산되면 안되므로 다른 값으로 바꿔줘야 한다. 13 | 14 | Recursion을 이용한 DFS를 이용해보자 15 | */ 16 | 17 | enum Site { 18 | case vacantLot 19 | case landWithHouse 20 | 21 | var numberDescription: Int { 22 | switch self { 23 | case .vacantLot: 24 | return 0 25 | case .landWithHouse: 26 | return 1 27 | } 28 | } 29 | } 30 | 31 | //입력 32 | let size = Int(readLine()!)! 33 | var map = [[Int]]() 34 | for _ in 0.. Int { 43 | if column < 0 || column >= size || row < 0 || row >= size { //base case 1 - 범위 벗어남 44 | return 0 45 | } else if map[row][column] != Site.landWithHouse.numberDescription { //base case 2 - 집이 아닌 부지를 마주친 경우 46 | return 0 47 | } else { //recursive case - 집이 있는 땅을 마주한 경우 48 | map[row][column] = checkedHouse 49 | return 1 50 | + countHouse(x: column, y: row - 1) 51 | + countHouse(x: column + 1, y: row) 52 | + countHouse(x: column, y: row + 1) 53 | + countHouse(x: column - 1, y: row) 54 | } 55 | } 56 | 57 | var housingComplex = [Int]() 58 | //모든 셀에 대하여 탐색 59 | for row in map.indices { 60 | for column in map[row].indices { 61 | let numberOfHouses = countHouse(x: column, y: row) 62 | 63 | if numberOfHouses > 0 { 64 | housingComplex.append(numberOfHouses) 65 | } 66 | } 67 | } 68 | 69 | var result = "\(housingComplex.count)\n" 70 | result += housingComplex.sorted { $0 < $1 }.map { String($0) }.joined(separator: "\n") 71 | print(result) 72 | -------------------------------------------------------------------------------- /Boj_Coden/4949_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 4949_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2021/12/09. 6 | // 7 | 8 | //이 문제는 숫자값을 이용한 방식으로도 해결할 수 있다. (다만 중간도 균형이 맞아야 한다는 것은 숫자로 풀기에는 난해) 9 | 10 | while let sentence = readLine(), sentence.first != "." { 11 | var stack = "" 12 | 13 | for letter in sentence { 14 | switch letter { 15 | case "(", "[": 16 | stack.append(letter) 17 | case ")": 18 | guard let lastLetter = stack.popLast(), lastLetter == "(" else { 19 | stack.append("fail") 20 | break 21 | } 22 | case "]": 23 | guard let lastLetter = stack.popLast(), lastLetter == "[" else { 24 | stack.append("fail") 25 | break 26 | } 27 | default: 28 | break 29 | } 30 | } 31 | 32 | if stack.isEmpty { 33 | print("yes") 34 | } else { 35 | print("no") 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Boj_Coden/7576_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 7576_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2022/02/17. 6 | // 7 | 8 | /* 9 | 토마토 문제는 대표적인 BFS 문제이다. 10 | 11 | 두개의 큐를 이용하여 풀이 12 | 1. 이미 익은 토마토들에 대한 큐(ripe tomato queue)와 다음날이 되면 익을 토마토들에 대한 큐(unripe tomato queue)를 둔다. 13 | 2. '익은 토마토 큐'에서 요소들을 꺼내면서 BFS를 진행하고 인접한 토마토들 좌표는 '다음날이 되면 익을 토마토 큐'에 넣는다. 14 | 3. '다음날이 되면 익을 토마토 큐'에서 '익은 토마토 큐'로 모든 요소를 이동시킨 뒤 날짜를 하나 더하고 '다음날이 되면 익을 토마토 큐'는 모든 요소를 제거한다. 15 | 4. 이 과정을 '다음날이 되면 익을 토마토 큐'가 빌때까지 진행한다. (더이상 익을 토마토가 없다는 것) 16 | 5. 마지막에 창고의 토마토들을 순회하면서 안익은 것이 있는지 조회한다. 17 | 6. 안익은 것이 있다면 익을 수 없는 것이므로 -1을 출력하고 모든 토마토가 익었다면 계산된 날 수를 출력한다. 18 | */ 19 | 20 | //필요한 자료구조 정의 21 | struct Queue { 22 | private var enqueueStack = Array() 23 | private var dequeueStack = Array() 24 | 25 | var isEmpty: Bool { 26 | return enqueueStack.isEmpty && dequeueStack.isEmpty 27 | } 28 | 29 | mutating func enqueue(_ element: Element) { 30 | enqueueStack.append(element) 31 | } 32 | 33 | mutating func dequeue() -> Element? { 34 | if dequeueStack.isEmpty { 35 | dequeueStack = enqueueStack.reversed() 36 | enqueueStack.removeAll() 37 | } 38 | 39 | return dequeueStack.popLast() 40 | } 41 | 42 | mutating func removeAll() { 43 | enqueueStack.removeAll() 44 | dequeueStack.removeAll() 45 | } 46 | } 47 | 48 | struct Coord { 49 | let x: Int 50 | let y: Int 51 | } 52 | 53 | //입력 54 | let sizeInputs = readLine()!.split(separator: " ").map { Int(String($0))! } 55 | let width = sizeInputs[0] 56 | let height = sizeInputs[1] 57 | 58 | var tomatoBox = [[Int]]() 59 | for _ in 0..() //익은 토마토 큐 65 | var unripeTomatoQueue = Queue() //안익은 토마토 큐 66 | 67 | for row in tomatoBox.indices { 68 | for column in tomatoBox[row].indices { 69 | if tomatoBox[row][column] == 1 { //이미 익은 토마토가 있는 경우 70 | unripeTomatoQueue.enqueue(Coord(x: column, y: row)) //일단은 '안 익은 토마토 큐'에 넣는다. 71 | } 72 | } 73 | } 74 | 75 | var requiredNumberOfDays = -1 //이미 익은 토마토들을 처음에 '다음날이 되면 익을 토마토 큐'에 넣었기 때문에 보정을 위해 -1로 초기화 76 | while !unripeTomatoQueue.isEmpty { //'다음날이 되면 익을 토마토 큐'가 비어있지 않다면 77 | ripeTomatoQueue = unripeTomatoQueue 78 | unripeTomatoQueue.removeAll() 79 | requiredNumberOfDays += 1 //해당 토마토들이 1일이 지나 익었다. 80 | 81 | while let ripeTomato = ripeTomatoQueue.dequeue() { //익은 토마토들을 시작으로 주변에 어떤 토마토들이 다음날에 익을지 확인해보자 82 | let adjacentCoord = [ 83 | Coord(x: ripeTomato.x, y: ripeTomato.y - 1), 84 | Coord(x: ripeTomato.x + 1, y: ripeTomato.y), 85 | Coord(x: ripeTomato.x, y: ripeTomato.y + 1), 86 | Coord(x: ripeTomato.x - 1, y: ripeTomato.y) 87 | ] 88 | 89 | for adjacentTomato in adjacentCoord where 90 | adjacentTomato.x >= 0 && adjacentTomato.x < width && 91 | adjacentTomato.y >= 0 && adjacentTomato.y < height && 92 | tomatoBox[adjacentTomato.y][adjacentTomato.x] == 0 { 93 | //주변 토마토 중 안 익은 토마토가 있다면 해당 토마토는 이제 익을 토마토가 된다. 94 | unripeTomatoQueue.enqueue(adjacentTomato) 95 | tomatoBox[adjacentTomato.y][adjacentTomato.x] = 1 //일단 익은 것처럼 처리(중복 카운팅 방지) 96 | } 97 | } 98 | } //repeat-while문으로 작성하는 것이 자연스러울 수도 있음 99 | 100 | var areAllTheTomatoesRipe = true //모든 토마토들이 다 익었는가 101 | for row in tomatoBox.indices { 102 | for column in tomatoBox[row].indices { 103 | if tomatoBox[row][column] == 0 { //만약 아직 안익은 토마토가 있다면 104 | areAllTheTomatoesRipe = false //모든 토마토를 익게 할 수 없다. 105 | } 106 | } 107 | } 108 | 109 | if areAllTheTomatoesRipe { 110 | print(requiredNumberOfDays) 111 | } else { 112 | print(-1) 113 | } 114 | -------------------------------------------------------------------------------- /Boj_Coden/9019_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 9019_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2022/02/17. 6 | // 7 | 8 | /* 9 | 모든 경우의 수를 다 탐색하면 되는 문제이다. 10 | 단, 이 때 만들어지는 상태공간트리를 DFS로 탐색하는 것이 아닌 BFS로 탐색해야 한다. 11 | 12 | 상태공간트리는 아래와 같이 그려진다.(각각의 '경우노드'에 대해 4개의 자식노드가 계속 붙는 방식) 13 | 14 | 시작 숫자 15 | D를 한 숫자 S를 한 숫자 L을 한 숫자 R을 한 숫자 16 | D적용 S적용 L적용 R적용 .... .... D적용 S적용 L적용 R적용 17 | */ 18 | 19 | struct Queue { 20 | private var container = Array() 21 | private var head = 0 22 | 23 | var isEmpty: Bool { 24 | return head >= container.count 25 | } 26 | 27 | mutating func enqueue(_ element: Element) { 28 | container.append(element) 29 | } 30 | 31 | mutating func dequeue() -> Element? { 32 | if isEmpty { 33 | return nil 34 | } 35 | 36 | let element = container[head] 37 | head += 1 38 | 39 | if head >= 10000 { //head가 10000이 될 때 배열 0~9999의 만개는 제거해줘도 되는 공간이다. 40 | container.removeFirst(head) 41 | head = 0 42 | } 43 | 44 | return element 45 | } 46 | 47 | mutating func removeAll() { 48 | container.removeAll() 49 | head = 0 50 | } 51 | } 52 | 53 | //각각의 경우(상태공간트리 노드)에 대한 타입 54 | struct Register { 55 | let number: Int 56 | let instructions: String 57 | } 58 | 59 | //각각의 명령어에 대한 함수 60 | func multiply(_ number: Int) -> Int { 61 | return (number * 2) % 10000 62 | } 63 | 64 | func subtract(from number: Int) -> Int { 65 | if number == .zero { 66 | return 9999 67 | } else { 68 | return number - 1 69 | } 70 | } 71 | 72 | func shiftToLeft(_ number: Int) -> Int { 73 | if number < 1000 { 74 | return number * 10 75 | } else { 76 | let firstNumber = number / 1000 77 | let remainingNumber = number % 1000 78 | 79 | return remainingNumber * 10 + firstNumber 80 | } 81 | } 82 | 83 | func shiftToRight(_ number: Int) -> Int { 84 | let lastNumber = number % 10 85 | let remainingNumber = number / 10 86 | 87 | return remainingNumber + (lastNumber * 1000) 88 | } 89 | 90 | //입력 및 풀이 91 | let numberOfTestCases = Int(readLine()!)! 92 | var results = "" 93 | 94 | for _ in 0..() 101 | queue.enqueue(startingRegister) 102 | 103 | var isFigureOutPathToNumber = Array(repeating: false, count: 10000) //(해당 숫자로 가기 위한)최단 경로가 파악된 노드는 중복하여 넣을 필요가 없다. 104 | isFigureOutPathToNumber[startingNumber] = true 105 | 106 | while let currentRegister = queue.dequeue() { //노드를 하나 꺼낸다. 107 | //MARK: - D 108 | let multipliedNumber = multiply(currentRegister.number) 109 | let multipliedRegister = Register(number: multipliedNumber, instructions: currentRegister.instructions + "D") 110 | 111 | if isFigureOutPathToNumber[multipliedNumber] == false { //방문한 적 없는 숫자인 경우 112 | if multipliedNumber == targetNumber { 113 | results += (multipliedRegister.instructions + "\n") 114 | break 115 | } else { 116 | queue.enqueue(multipliedRegister) 117 | isFigureOutPathToNumber[multipliedNumber] = true 118 | } 119 | } 120 | 121 | //MARK: - S 122 | let subtractedNumber = subtract(from: currentRegister.number) 123 | let subtractedRegister = Register(number: subtractedNumber, instructions: currentRegister.instructions + "S") 124 | 125 | if isFigureOutPathToNumber[subtractedNumber] == false { 126 | if subtractedNumber == targetNumber { 127 | results += (subtractedRegister.instructions + "\n") 128 | break 129 | } else { 130 | queue.enqueue(subtractedRegister) 131 | isFigureOutPathToNumber[subtractedNumber] = true 132 | } 133 | } 134 | 135 | //MARK: - L 136 | let leftShiftedNumber = shiftToLeft(currentRegister.number) 137 | let leftShiftedRegister = Register(number: leftShiftedNumber, instructions: currentRegister.instructions + "L") 138 | 139 | if isFigureOutPathToNumber[leftShiftedNumber] == false { 140 | if leftShiftedNumber == targetNumber { 141 | results += (leftShiftedRegister.instructions + "\n") 142 | break 143 | } else { 144 | queue.enqueue(leftShiftedRegister) 145 | isFigureOutPathToNumber[leftShiftedNumber] = true 146 | } 147 | } 148 | 149 | //MARK: - R 150 | let rightShiftedNumber = shiftToRight(currentRegister.number) 151 | let rightShiftedRegister = Register(number: rightShiftedNumber, instructions: currentRegister.instructions + "R") 152 | 153 | if isFigureOutPathToNumber[rightShiftedNumber] == false { 154 | if rightShiftedNumber == targetNumber { 155 | results += (rightShiftedRegister.instructions + "\n") 156 | break 157 | } else { 158 | queue.enqueue(rightShiftedRegister) 159 | isFigureOutPathToNumber[rightShiftedNumber] = true 160 | } 161 | } 162 | } 163 | } 164 | 165 | print(results) 166 | -------------------------------------------------------------------------------- /Boj_Coden/9663_Coden.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // 9663_Coden.cpp 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2022/02/05. 6 | // 7 | 8 | //'백준 9663 N-Queen' swift버전이 풀리지 않아 cpp로 풀이해봅니다.(동일한 풀이방식 사용) 9 | //결과: 풀림. Swift에 대한 시간고려가 안된것으로 파악됨 10 | #include 11 | #define MAX 15 12 | using namespace std; 13 | 14 | bool isValidPosition(int row); 15 | void deployQueen(int row); 16 | 17 | int chessBoard[MAX]; //입력값은 14까지 들어올 수 있으며 1~14 인덱스 사용 예정 18 | int numberOfCases = 0; 19 | int size; 20 | 21 | int main(void) { 22 | ios_base::sync_with_stdio(false); 23 | cin.tie(NULL); 24 | 25 | 26 | cin >> size; 27 | deployQueen(0); 28 | cout << numberOfCases; 29 | 30 | return 0; 31 | } 32 | 33 | //row에 배치된 퀸이 유효한가? 34 | bool isValidPosition(int row) { 35 | if(row == 0) { 36 | return true; 37 | } 38 | 39 | for(int prevRow = 1; prevRow < row; prevRow++) { 40 | if(chessBoard[prevRow] == chessBoard[row] || 41 | row - prevRow == abs(chessBoard[row] - chessBoard[prevRow])) { 42 | return false; 43 | } 44 | } 45 | 46 | return true; 47 | } 48 | 49 | //row행에 퀸이 배치된 이후 호출되는 함수 50 | void deployQueen(int row) { 51 | if(!isValidPosition(row)) { 52 | return; 53 | } else if(row == size) { 54 | numberOfCases++; 55 | return; 56 | } else { 57 | for(int column = 1; column <= size; column++) { 58 | chessBoard[row + 1] = column; 59 | deployQueen(row + 1); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Boj_Coden/9663_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 9663_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2022/01/12. 6 | // 7 | 8 | /* 9 | N-Queens Problem은 대표적인 백트래킹 / dfs 문제이다. 10 | 이 문제에서는 가능한 모든 경우의 수를 구하라고 하고 있다. 11 | 모든 경우(노드)를 탐색하는 dfs로 짜되 유망(promising)한 노드만 탐색하도록 할 것이다.(백트래킹) 12 | */ 13 | 14 | //입력 15 | let size = Int(readLine()!)! 16 | 17 | //한 row 행에는 하나의 말만 놓을 것이며 각각의 row에서 어떤 column에 말을 놓은 것인지 추적할 것이다. 18 | var chessboard = [Int]() 19 | for _ in 0...size { //행과 열은 1~size 인덱스를 사용 할 것이다. 20 | chessboard.append(0) 21 | } 22 | 23 | //row 행에 놓인 말이 유효한 것인지 체크 24 | func isValidPosition(in row: Int) -> Bool { 25 | if row == 0 { //상태공간트리에서의 시작지점, root 노드여서 언제나 true여야 함 26 | return true 27 | } 28 | for prevRow in 1.. [Int] { 11 | return readLine()!.split(separator: " ").compactMap{Int($0)} 12 | } 13 | 14 | func combine() { 15 | let input = receiveInput() 16 | let first = input[0] 17 | let second = input[1] 18 | print(first+second) 19 | } 20 | 21 | combine() 22 | -------------------------------------------------------------------------------- /Boj_Geon/1001_Geon.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1001_Geon.swift 3 | // Execution 4 | // 5 | // Created by 김준건 on 2021/12/08. 6 | // 7 | 8 | import Foundation 9 | 10 | func receiveInput() -> [Int] { 11 | return readLine()!.split(separator: " ").compactMap{Int($0)} 12 | } 13 | 14 | func subtraction() { 15 | let input = receiveInput() 16 | let first = input[0] 17 | let second = input[1] 18 | print(first-second) 19 | } 20 | 21 | subtraction() 22 | -------------------------------------------------------------------------------- /Boj_Geon/1008_Geon.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1008_Geon.swift 3 | // Execution 4 | // 5 | // Created by 김준건 on 2021/12/08. 6 | // 7 | 8 | import Foundation 9 | 10 | func receiveInput() -> [Double] { 11 | return readLine()!.split(separator: " ").compactMap{Double($0)} 12 | } 13 | 14 | func divide() { 15 | let input = receiveInput() 16 | let first = input[0] 17 | let second = input[1] 18 | print(first/second) 19 | } 20 | 21 | divide() 22 | -------------------------------------------------------------------------------- /Boj_Geon/10171_Geon.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10171_Geon.swift 3 | // Execution 4 | // 5 | // Created by 김준건 on 2021/12/08. 6 | // 7 | 8 | import Foundation 9 | 10 | var cat = #""" 11 | \ /\ 12 | ) ( ') 13 | ( / ) 14 | \(__)| 15 | """# 16 | 17 | print(cat) 18 | -------------------------------------------------------------------------------- /Boj_Geon/10172_Geon.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10172_Geon.swift 3 | // Execution 4 | // 5 | // Created by 김준건 on 2021/12/08. 6 | // 7 | 8 | import Foundation 9 | 10 | let dog = #""" 11 | |\_/| 12 | |q p| /} 13 | ( 0 )"""\ 14 | |"^"` | 15 | ||_/=\\__| 16 | """# 17 | 18 | print(dog) 19 | -------------------------------------------------------------------------------- /Boj_Geon/10430_Geon.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10430_Geon.swift 3 | // Execution 4 | // 5 | // Created by 김준건 on 2021/12/09. 6 | // 7 | 8 | import Foundation 9 | 10 | func receiveInput() -> [Int] { 11 | return readLine()!.split(separator: " ").compactMap{Int($0)} 12 | } 13 | 14 | func calculateRest() { 15 | let input = receiveInput() 16 | let first = input[0] 17 | let second = input[1] 18 | let third = input[2] 19 | print(((first + second) % third)) 20 | print((((first % third) + (second % third)) % third)) 21 | print(((first * second) % third)) 22 | print((((first % third) * (second % third)) % third)) 23 | } 24 | 25 | 26 | calculateRest() 27 | -------------------------------------------------------------------------------- /Boj_Geon/10718_Geon.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10718_Geon.swift 3 | // Execution 4 | // 5 | // Created by 김준건 on 2021/12/07. 6 | // 7 | 8 | import Foundation 9 | 10 | var text = "강한친구 대한육군" 11 | for _ in 1...2 { 12 | print(text) 13 | } 14 | -------------------------------------------------------------------------------- /Boj_Geon/10828_Geon.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10828_Geon.swift 3 | // Execution 4 | // 5 | // Created by 김준건 on 2021/12/14. 6 | // 7 | 8 | import Foundation 9 | 10 | struct Stack{ 11 | private var list: [Int] = [] 12 | 13 | mutating func push(input: Int) { 14 | list.append(input) 15 | } 16 | 17 | mutating func pop() -> Int{ 18 | if list.isEmpty { 19 | return -1 20 | } else { 21 | return list.removeLast() 22 | } 23 | } 24 | 25 | func size() -> Int { 26 | return list.count 27 | } 28 | 29 | func empty() -> Int { 30 | if list.count == .zero { 31 | return 1 32 | } else { 33 | return .zero 34 | } 35 | } 36 | 37 | func top() -> Int { 38 | if list.isEmpty { 39 | return -1 40 | } else { 41 | return list[list.count - 1] 42 | } 43 | } 44 | } 45 | 46 | 47 | 48 | 49 | var stack = Stack() 50 | 51 | for _ in 0 ..< Int(readLine()!)! { 52 | let command = readLine()!.split(separator: " ") 53 | 54 | switch command[0] { 55 | case "push": 56 | stack.push(input: Int(command[1])!) 57 | case "pop": 58 | print(stack.pop()) 59 | case "size": 60 | print(stack.size()) 61 | case "empty": 62 | print(stack.empty()) 63 | case "top": 64 | print(stack.top()) 65 | default: 66 | break 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Boj_Geon/10869_Geon.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10869.swift 3 | // Execution 4 | // 5 | // Created by 김준건 on 2021/12/08. 6 | // 7 | 8 | import Foundation 9 | 10 | func receiveInput() -> [Int] { 11 | return readLine()!.split(separator: " ").compactMap{Int($0)} 12 | } 13 | 14 | func fourArithmeticOperation() { 15 | let input = receiveInput() 16 | let first = input[0] 17 | let second = input[1] 18 | print(first+second) 19 | print(first-second) 20 | print(first*second) 21 | print(first/second) 22 | print(first%second) 23 | } 24 | 25 | fourArithmeticOperation() 26 | -------------------------------------------------------------------------------- /Boj_Geon/10998_Geon.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10998_Geon.swift 3 | // Execution 4 | // 5 | // Created by 김준건 on 2021/12/08. 6 | // 7 | 8 | import Foundation 9 | 10 | func receiveInput() -> [Int] { 11 | return readLine()!.split(separator: " ").compactMap{Int($0)} 12 | } 13 | 14 | func multiplication() { 15 | let input = receiveInput() 16 | let first = input[0] 17 | let second = input[1] 18 | print(first*second) 19 | } 20 | 21 | multiplication() 22 | -------------------------------------------------------------------------------- /Boj_Geon/11866_Geon.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 11866_Geon.swift 3 | // Execution 4 | // 5 | // Created by 김준건 on 2021/12/17. 6 | // 7 | 8 | import Foundation 9 | 10 | func receiveInput() -> [Int] { 11 | return readLine()!.split(separator: " ").compactMap{Int($0)} 12 | } 13 | 14 | let input = receiveInput() 15 | let n = input[0] 16 | let k = input[1] 17 | var list: [Int] = Array(1...n) 18 | var result: [Int] = [] 19 | var index = k - 1 20 | 21 | while true { 22 | result.append(list.remove(at: index)) 23 | if list.isEmpty { 24 | break 25 | } 26 | index = (index + k - 1 ) % list.count 27 | print(index) 28 | } 29 | 30 | print("<" + result.map({String($0)}).joined(separator: ", ") + ">") 31 | -------------------------------------------------------------------------------- /Boj_Geon/2557_Geon.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 2557_Geon.swift 3 | // Execution 4 | // 5 | // Created by 김준건 on 2021/12/07. 6 | // 7 | 8 | import Foundation 9 | 10 | print("Hello World!") 11 | -------------------------------------------------------------------------------- /Boj_Geon/2588_Geon.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 2588_Geon.swift 3 | // Execution 4 | // 5 | // Created by 김준건 on 2021/12/09. 6 | // 7 | 8 | import Foundation 9 | 10 | func receiveInput() -> Int { 11 | return (Int(readLine() ?? "") ?? 0) 12 | } 13 | 14 | func multiplication() { 15 | let firstInput = receiveInput() 16 | let secondInput = receiveInput() 17 | print(firstInput * (secondInput % 10)) 18 | print(firstInput * ((secondInput % 100) / 10)) 19 | print(firstInput * (secondInput / 100)) 20 | print(firstInput * secondInput) 21 | } 22 | 23 | 24 | multiplication() 25 | -------------------------------------------------------------------------------- /Boj_Geon/4949_Geon.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 4949_Geon.swift 3 | // Execution 4 | // 5 | // Created by 김준건 on 2021/12/17. 6 | // 7 | 8 | import Foundation 9 | 10 | struct Stack { 11 | private var container: [Element] = [] 12 | 13 | func isEmpty() -> Bool { 14 | container.isEmpty ? true : false 15 | } 16 | 17 | mutating func push(value: Element) { 18 | container.append(value) 19 | } 20 | 21 | mutating func pop() -> Element { 22 | return container.removeLast() 23 | } 24 | 25 | func top() -> Element? { 26 | return container.last 27 | } 28 | 29 | } 30 | 31 | while true { 32 | let input = readLine()! 33 | var flag = true 34 | var stack = Stack() 35 | 36 | if input == "." { 37 | break 38 | } else { 39 | for char in input { 40 | if char == "[" || char == "(" { 41 | stack.push(value: char) 42 | } else if char == "]" || char == ")" { 43 | if stack.isEmpty() { 44 | flag = false 45 | break 46 | } 47 | if char == "]" && stack.pop() != "[" { 48 | flag = false 49 | break 50 | } 51 | else if char == ")" && stack.pop() != "(" { 52 | flag = false 53 | break 54 | } 55 | } 56 | } 57 | } 58 | if flag == false { 59 | print("no") 60 | } else { 61 | if stack.isEmpty() == false { 62 | print("no") 63 | } else { 64 | print("yes") 65 | } 66 | } 67 | } 68 | 69 | -------------------------------------------------------------------------------- /Boj_Soll/1000_Soll.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1000_Soll.swift 3 | // Boj_Soll 4 | // 5 | // Created by Dasoll Park on 2021/12/08. 6 | // 7 | 8 | let input = readLine()!.split(separator: " ").map { Int(String($0))! } 9 | 10 | print(input[0] + input[1]) 11 | -------------------------------------------------------------------------------- /Boj_Soll/1001_Soll.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1001_Soll.swift 3 | // Boj_Soll 4 | // 5 | // Created by Dasoll Park on 2021/12/08. 6 | // 7 | 8 | let input = readLine()!.split(separator: " ").map { Int(String($0))! } 9 | print(input[0] - input[1]) 10 | -------------------------------------------------------------------------------- /Boj_Soll/1008_Soll.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1008_Soll.swift 3 | // Boj_Soll 4 | // 5 | // Created by Dasoll Park on 2021/12/08. 6 | // 7 | 8 | let input = readLine()!.split(separator: " ").map { Double(String($0))! } 9 | print(input[0] / input[1]) 10 | -------------------------------------------------------------------------------- /Boj_Soll/10171_Soll.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10171_Soll.swift 3 | // Boj_Soll 4 | // 5 | // Created by Dasoll Park on 2021/12/08. 6 | // 7 | 8 | print("\\ /\\") 9 | print(" ) ( ')") 10 | print("( / )") 11 | print(" \\(__)|") 12 | -------------------------------------------------------------------------------- /Boj_Soll/10172_Soll.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10172_Soll.swift 3 | // Boj_Soll 4 | // 5 | // Created by Dasoll Park on 2021/12/08. 6 | // 7 | 8 | print("|\\_/|") 9 | print("|q p| /}") 10 | print("( 0 )\"\"\"\\") 11 | print("|\"^\"` |") 12 | print("||_/=\\\\__|") 13 | -------------------------------------------------------------------------------- /Boj_Soll/10430_Soll.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10430_Soll.swift 3 | // Boj_Soll 4 | // 5 | // Created by Dasoll Park on 2021/12/08. 6 | // 7 | 8 | let input = readLine()!.split(separator: " ").map{ Int(String($0))! } 9 | let a = input[0] 10 | let b = input[1] 11 | let c = input[2] 12 | 13 | print((a+b)%c) 14 | print(((a%c)+(b%c))%c) 15 | print((a*b)%c) 16 | print(((a%c)*(b%c))%c) 17 | -------------------------------------------------------------------------------- /Boj_Soll/10718_Soll.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10718_Soll.swift 3 | // Boj_Soll 4 | // 5 | // Created by Dasoll Park on 2021/12/08. 6 | // 7 | 8 | print("강한친구 대한육군") 9 | print("강한친구 대한육군") 10 | -------------------------------------------------------------------------------- /Boj_Soll/10816_Soll.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10816_Soll.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by Dasoll Park on 2021/12/23. 6 | // 7 | 8 | import Foundation 9 | 10 | final class FileIO { 11 | private let buffer: Data 12 | private var index: Int = 0 13 | 14 | init(fileHandle: FileHandle = FileHandle.standardInput) { 15 | self.buffer = try! fileHandle.readToEnd()! // 인덱스 범위 넘어가는 것 방지 16 | } 17 | 18 | @inline(__always) private func read() -> UInt8 { 19 | defer { 20 | index += 1 21 | } 22 | guard index < buffer.count else { return 0 } 23 | 24 | return buffer[index] 25 | } 26 | 27 | @inline(__always) func readInt() -> Int { 28 | var sum = 0 29 | var now = read() 30 | var isPositive = true 31 | 32 | while now == 10 33 | || now == 32 { now = read() } // 공백과 줄바꿈 무시 34 | if now == 45 { isPositive.toggle(); now = read() } // 음수 처리 35 | while now >= 48, now <= 57 { 36 | sum = sum * 10 + Int(now-48) 37 | now = read() 38 | } 39 | 40 | return sum * (isPositive ? 1:-1) 41 | } 42 | 43 | 44 | @inline(__always) func readString() -> String { 45 | var str = "" 46 | var now = read() 47 | 48 | while now == 10 49 | || now == 32 { now = read() } // 공백과 줄바꿈 무시 50 | 51 | while now != 10 52 | && now != 32 && now != 0 { 53 | str += String(bytes: [now], encoding: .ascii)! 54 | now = read() 55 | } 56 | 57 | return str 58 | } 59 | } 60 | 61 | let fileIO = FileIO() 62 | 63 | let n = fileIO.readInt() 64 | var inputN = [Int]() 65 | for _ in 0.. Int { 16 | if let n = stack.popLast() { 17 | return n 18 | } 19 | return -1 20 | } 21 | 22 | func size() -> Int { 23 | stack.count 24 | } 25 | 26 | func empty() -> Int { 27 | if stack.isEmpty { 28 | return 1 29 | } 30 | return 0 31 | } 32 | 33 | func top() -> Int { 34 | if let n = stack.last { 35 | return n 36 | } 37 | return -1 38 | } 39 | } 40 | 41 | let n = Int(readLine()!)! 42 | let stack = Stack() 43 | 44 | (0..(1...n) 14 | var result = "" 15 | 16 | while queue.isEmpty == false { 17 | for i in 0..") 33 | -------------------------------------------------------------------------------- /Boj_Soll/18258_Soll.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 18258_Soll.swift 3 | // SwiftStudy 4 | // 5 | // Created by Dasoll Park on 2021/12/17. 6 | // 7 | 8 | import Foundation 9 | 10 | final class FileIO { 11 | private let buffer:[UInt8] 12 | private var index: Int = 0 13 | 14 | init(fileHandle: FileHandle = FileHandle.standardInput) { 15 | 16 | buffer = Array(try! fileHandle.readToEnd()!)+[UInt8(0)] // 인덱스 범위 넘어가는 것 방지 17 | } 18 | 19 | @inline(__always) private func read() -> UInt8 { 20 | defer { index += 1 } 21 | 22 | return buffer[index] 23 | } 24 | 25 | @inline(__always) func readInt() -> Int { 26 | var sum = 0 27 | var now = read() 28 | var isPositive = true 29 | 30 | while now == 10 31 | || now == 32 { now = read() } // 공백과 줄바꿈 무시 32 | if now == 45 { isPositive.toggle(); now = read() } // 음수 처리 33 | while now >= 48, now <= 57 { 34 | sum = sum * 10 + Int(now-48) 35 | now = read() 36 | } 37 | 38 | return sum * (isPositive ? 1:-1) 39 | } 40 | 41 | @inline(__always) func readString() -> Int { 42 | var str = 0 43 | var now = read() 44 | 45 | while now == 10 || now == 32 { now = read() } // 공백과 줄바꿈 무시 46 | 47 | while now != 10 && 48 | now != 32 && 49 | now != 0 { 50 | str += Int(now) 51 | now = read() 52 | } 53 | 54 | return str 55 | } 56 | } 57 | 58 | class Queue { 59 | var left = [Int]() 60 | var right = [Int]() 61 | 62 | var size: Int { 63 | left.count + right.count 64 | } 65 | 66 | var isEmpty: Bool { 67 | left.isEmpty && right.isEmpty 68 | } 69 | 70 | var first: Int? { 71 | guard !isEmpty else { return -1 } 72 | return right.isEmpty ? left.first : right.last 73 | } 74 | 75 | var last: Int? { 76 | guard !isEmpty else { return -1 } 77 | return left.isEmpty ? right.first : left.last 78 | } 79 | 80 | func enqueue(value: Int) { 81 | left.append(value) 82 | } 83 | 84 | func dequeue() -> Int? { 85 | guard !isEmpty else { return -1 } 86 | if right.isEmpty { 87 | right = left.reversed() 88 | left.removeAll() 89 | } 90 | return right.popLast() 91 | } 92 | 93 | func front() -> Int { 94 | queue.isEmpty ? -1 : queue.first! 95 | } 96 | 97 | func back() -> Int { 98 | queue.isEmpty ? -1 : queue.last! 99 | } 100 | } 101 | 102 | let fileIO = FileIO() 103 | let queue = Queue() 104 | var result = "" 105 | 106 | for _ in 0 ..< fileIO.readInt() { 107 | let command = fileIO.readString() 108 | 109 | if command == 448 { 110 | queue.enqueue(value: fileIO.readInt()) 111 | } else if command == 335 { 112 | result += queue.isEmpty ? "-1\n" : "\(queue.dequeue()!)\n" 113 | } else if command == 443 { 114 | result += "\(queue.size)\n" 115 | } else if command == 559 { 116 | result += queue.isEmpty ? "1\n" : "0\n" 117 | } else if command == 553 { 118 | result += "\(queue.front())\n" 119 | } else if command == 401 { 120 | result += "\(queue.back())\n" 121 | } 122 | } 123 | print(result) 124 | -------------------------------------------------------------------------------- /Boj_Soll/2557_Soll.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 2557_Soll.swift 3 | // Boj_Soll 4 | // 5 | // Created by Dasoll Park on 2021/12/08. 6 | // 7 | 8 | print("Hello World!") 9 | -------------------------------------------------------------------------------- /Boj_Soll/2588_Soll.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 2588_Soll.swift 3 | // Boj_Soll 4 | // 5 | // Created by Dasoll Park on 2021/12/09. 6 | // 7 | 8 | let a = Int(readLine()!)! 9 | let b = Int(readLine()!)! 10 | 11 | print(a*(b%10)) 12 | print(a*(b%100/10)) 13 | print(a*(b%1000/100)) 14 | print(a*b) 15 | -------------------------------------------------------------------------------- /Boj_Soll/4949_Soll.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 4949_Soll.swift 3 | // Boj_Soll 4 | // 5 | // Created by Dasoll Park on 2021/12/10. 6 | // 7 | 8 | import Foundation 9 | 10 | class Stack { 11 | var stack: [Character] = [] 12 | var isEmpty: Bool { 13 | stack.isEmpty 14 | } 15 | 16 | func push(x: Character) { 17 | stack.append(x) 18 | } 19 | 20 | func pop() -> Character? { 21 | if let n = stack.popLast() { 22 | return n 23 | } 24 | return nil 25 | } 26 | } 27 | 28 | 29 | while true { 30 | var input = readLine()! 31 | 32 | if input == "." { 33 | break 34 | } 35 | 36 | let bracketStack = Stack() 37 | var isValid = true 38 | 39 | let trimmedInput = input.trimmingCharacters(in: .whitespacesAndNewlines) 40 | 41 | for char in trimmedInput { 42 | if char == "(" || char == "[" { 43 | bracketStack.push(x: char) 44 | } else if char == ")" || char == "]" { 45 | if bracketStack.isEmpty { 46 | isValid = false 47 | break 48 | } 49 | if char == ")" && bracketStack.pop() != "(" { 50 | isValid = false 51 | break 52 | } else if char == "]" && bracketStack.pop() != "[" { 53 | isValid = false 54 | break 55 | } 56 | } 57 | } 58 | 59 | if isValid == false { 60 | print("no") 61 | } else { 62 | if !bracketStack.isEmpty { 63 | print("no") 64 | } else { 65 | print("yes") 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Boj_Soll/9663_Soll.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 9663_Soll.swift 3 | // SwiftStudy 4 | // 5 | // Created by Dasoll Park on 2022/02/11. 6 | // 7 | 8 | import Foundation 9 | 10 | final class NQueen { 11 | var maxLevel = 0 12 | var columns: [Int] = [] 13 | var result = 0 14 | 15 | func solution() { 16 | maxLevel = Int(readLine()!)! 17 | columns = Array(repeating: 0, count: maxLevel + 1) 18 | nQueen(level: 0) 19 | print(result) 20 | } 21 | 22 | // 하나의 노드에 접근 23 | func nQueen(level: Int) -> Bool { 24 | if !promising(level: level) { 25 | return false 26 | } else if level == maxLevel { 27 | result += 1 28 | 29 | return false 30 | } 31 | for index in 1...maxLevel { 32 | columns[level + 1] = index 33 | 34 | // 다음 level의 노드에 접근 35 | if nQueen(level: level + 1) { 36 | return true 37 | } 38 | } 39 | return false 40 | } 41 | 42 | func promising(level: Int) -> Bool { 43 | if 1 < level { 44 | for index in 1.. Int { 69 | guard y < map.count, x < map[0].count else { return .zero } 70 | guard y >= 0, x >= 0 else { return .zero } 71 | 72 | if map[y][x].isFilled == false { return .zero } 73 | if map[y][x].isVisitied { return .zero } 74 | 75 | map[y][x].isVisitied = true 76 | 77 | let directions = [ 78 | (y: y-1, x: x), 79 | (y: y+1, x: x), 80 | (y: y, x: x-1), 81 | (y: y, x: x+1), 82 | ] 83 | 84 | directions.forEach { point in 85 | dfs(y: point.y, x: point.x, within: &map) 86 | } 87 | 88 | return 1 89 | } 90 | -------------------------------------------------------------------------------- /Boj_Soobak/10171_수박.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10171_수박.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by kjs on 2021/12/07. 6 | // 7 | 8 | import Foundation 9 | 10 | let cat = """ 11 | \\ /\\ 12 | ) ( ') 13 | ( / ) 14 | \\(__)| 15 | """ 16 | 17 | print(cat) 18 | 19 | -------------------------------------------------------------------------------- /Boj_Soobak/10172_수박.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10172_수박.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by kjs on 2021/12/07. 6 | // 7 | 8 | import Foundation 9 | 10 | let dog = """ 11 | |\\_/| 12 | |q p| /} 13 | ( 0 )\"\"\"\\ 14 | |"^"` | 15 | ||_/=\\\\__| 16 | """ 17 | 18 | print(dog) 19 | -------------------------------------------------------------------------------- /Boj_Soobak/10430_수박.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10430_수박.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by kjs on 2021/12/07. 6 | // 7 | 8 | import Foundation 9 | 10 | if let input = readLine() { 11 | let numbers = input 12 | .split(separator: " ") 13 | .compactMap { Int($0) } 14 | 15 | let A = numbers[0], B = numbers[1], C = numbers[2] 16 | 17 | print( (A + B) % C ) 18 | print( ((A % C) + (B % C)) % C ) 19 | print( (A * B) % C ) 20 | print( ((A % C) * (B % C)) % C ) 21 | } 22 | -------------------------------------------------------------------------------- /Boj_Soobak/10718_수박.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10718_수박.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by kjs on 2021/12/07. 6 | // 7 | 8 | import Foundation 9 | 10 | print("강한친구 대한육군") 11 | print("강한친구 대한육군") 12 | -------------------------------------------------------------------------------- /Boj_Soobak/10816_수박.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10816_수박.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by kjs on 2022/01/04. 6 | // 7 | 8 | import Foundation 9 | 10 | final class FileIO { 11 | private var buffer:[UInt8] 12 | private var index: Int 13 | 14 | init(fileHandle: FileHandle = FileHandle.standardInput) { 15 | buffer = Array(fileHandle.readDataToEndOfFile())+[UInt8(0)] 16 | index = 0 17 | } 18 | 19 | @inline(__always) private func read() -> UInt8 { 20 | defer { index += 1 } 21 | 22 | return buffer.withUnsafeBufferPointer { $0[index] } 23 | } 24 | 25 | @inline(__always) func readInt() -> Int { 26 | var sum = 0 27 | var now = read() 28 | var isPositive = true 29 | 30 | while now == 10 || now == 32 { now = read() } 31 | if now == 45{ isPositive.toggle(); now = read() } 32 | while now >= 48, now <= 57 { 33 | sum = sum * 10 + Int(now-48) 34 | now = read() 35 | } 36 | 37 | return sum * (isPositive ? 1:-1) 38 | } 39 | 40 | @inline(__always) func readString() -> String { 41 | var str = "" 42 | var now = read() 43 | 44 | while now == 10 || now == 32 { now = read() } 45 | 46 | while now != 10 && now != 32 && now != 0 { 47 | str += String(bytes: [now], encoding: .ascii)! 48 | now = read() 49 | } 50 | 51 | return str 52 | } 53 | } 54 | 55 | let reader = FileIO() 56 | 57 | let baskectLength = reader.readInt() 58 | var cardBasket = [Int]() 59 | 60 | for _ in 0.. { 11 | private var linkedList = LinkedList() 12 | var size = 0 13 | 14 | var head: AnyType? { 15 | linkedList.tail?.value 16 | } 17 | 18 | var isEmpty: Bool { 19 | linkedList.head == nil 20 | } 21 | 22 | mutating func push(_ value: AnyType) { 23 | linkedList.append(value) 24 | size += 1 25 | } 26 | 27 | mutating func pop() -> AnyType? { 28 | defer { 29 | if linkedList.removeLast() { 30 | size -= 1 31 | } 32 | } 33 | 34 | return linkedList.tail?.value 35 | } 36 | } 37 | 38 | 39 | // MARK: - components 40 | extension Stack { 41 | private class Node { 42 | private(set) var value: AnyType 43 | weak var prev: Node? 44 | var next: Node? 45 | 46 | init(value: AnyType, next: Node? = nil) { 47 | self.value = value 48 | } 49 | 50 | func updateValue(by value: AnyType) { 51 | self.value = value 52 | } 53 | } 54 | 55 | private struct LinkedList { 56 | private(set) var head: Node? 57 | private(set) weak var tail: Node? 58 | 59 | var isEmpty: Bool { 60 | return head == nil 61 | } 62 | 63 | mutating func append(_ value: AnyType) { 64 | let newNode = Node(value: value) 65 | 66 | if isEmpty { 67 | head = newNode 68 | head?.next = newNode 69 | } else { 70 | tail?.next = newNode 71 | newNode.prev = tail 72 | } 73 | 74 | tail = newNode 75 | } 76 | 77 | var target: Node? { 78 | return head?.next 79 | } 80 | 81 | mutating func removeLast() -> Bool { 82 | defer { 83 | if tail == nil { 84 | head = nil 85 | } 86 | } 87 | if tail != nil { 88 | tail = tail?.prev 89 | tail?.next = nil 90 | return true 91 | } else { 92 | return false 93 | } 94 | } 95 | 96 | init() { } 97 | 98 | init(headValue: AnyType) { 99 | self.append(headValue) 100 | } 101 | } 102 | } 103 | 104 | enum InputCases: String { 105 | case push 106 | case pop 107 | case size 108 | case empty 109 | case top 110 | } 111 | 112 | enum ResultCases: Int { 113 | case canNotFindHead = -1 114 | case notEmptied 115 | case emptied 116 | } 117 | 118 | if let input = readLine(), 119 | let orderSize = Int(input) { 120 | 121 | var stack = Stack() 122 | var result = "" 123 | 124 | for _ in 0..() 15 | for int in 1...desiredLength { 16 | queue.insert(int) 17 | } 18 | 19 | //solution 20 | var index = 0 21 | while result.count < desiredLength { 22 | index += 1 23 | 24 | if let element = queue.delete() { 25 | if index % term == 0 { 26 | result.append(element) 27 | index = 0 28 | } else { 29 | queue.insert(element) 30 | } 31 | } 32 | } 33 | 34 | print(result.reduce("<") { $0 + $1.description + ", "}.dropLast(2) + ">") 35 | } 36 | 37 | 38 | 39 | 40 | struct Queue { 41 | private var linkedList = LinkedList() 42 | private(set) var size = 0 43 | 44 | var head: AnyType? { 45 | linkedList.head?.value 46 | } 47 | 48 | var tail: AnyType? { 49 | linkedList.tail?.value 50 | } 51 | 52 | var isEmpty: Bool { 53 | linkedList.head == nil 54 | } 55 | 56 | mutating func insert(_ value: AnyType) { 57 | linkedList.append(value) 58 | size += 1 59 | } 60 | 61 | mutating func delete() -> AnyType? { 62 | defer { 63 | if linkedList.removeFirst() { 64 | size -= 1 65 | } 66 | } 67 | 68 | return linkedList.head?.value 69 | } 70 | } 71 | 72 | 73 | // MARK: - components 74 | extension Queue { 75 | private class Node { 76 | private(set) var value: AnyType 77 | weak var prev: Node? 78 | var next: Node? 79 | 80 | init(value: AnyType, next: Node? = nil) { 81 | self.value = value 82 | } 83 | 84 | func updateValue(by value: AnyType) { 85 | self.value = value 86 | } 87 | } 88 | 89 | private struct LinkedList { 90 | private(set) var head: Node? 91 | private(set) weak var tail: Node? 92 | 93 | var isEmpty: Bool { 94 | return head == nil 95 | } 96 | 97 | mutating func append(_ value: AnyType) { 98 | let newNode = Node(value: value) 99 | 100 | if isEmpty { 101 | head = newNode 102 | } else { 103 | tail?.next = newNode 104 | newNode.prev = tail 105 | } 106 | 107 | tail = newNode 108 | } 109 | 110 | var target: Node? { 111 | return head?.next 112 | } 113 | 114 | mutating func removeFirst() -> Bool { 115 | if head != nil { 116 | head = head?.next 117 | return true 118 | } else { 119 | return false 120 | } 121 | } 122 | 123 | init() { } 124 | 125 | init(headValue: AnyType) { 126 | self.append(headValue) 127 | } 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /Boj_Soobak/1303_수박.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1303_수박.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by kjs on 2022/01/05. 6 | // 7 | 8 | // 1. 아군과 적군을 구분해야하면서 카운팅을 했던 적이 있는지 확인할 노드가 필요함 9 | // 2. 입력을 받고 이를 노드의 2차원 배열로 맵핑해줄 로직이 필요함 10 | // 3. N명이 붙어있을 때, 재귀적으로 이게 얼만큼 뭉쳐잇는지 확인할 로직이 필요함 11 | // 4. 각 진영의 위력을 N^2을 한 뒤 합쳐주는 로직이 필요함 12 | 13 | 14 | // 1v 15 | struct Node: CustomStringConvertible { 16 | var description: String { 17 | if isEnemy { 18 | return "X" 19 | } else { 20 | return "O" 21 | } 22 | } 23 | 24 | let isEnemy: Bool 25 | var isVisited = false 26 | 27 | init(_ character: Character) { 28 | if character == "B" { 29 | isEnemy = true 30 | } else { 31 | isEnemy = false 32 | } 33 | } 34 | } 35 | 36 | 37 | if let input = readLine() { 38 | let size = input.split(separator: " ").compactMap({ Int($0) }) 39 | let width = size[0], height = size[1] 40 | 41 | var map = [[Node]]() 42 | for _ in 0.. Int { 80 | guard y < map.count, x < map[0].count else { return .zero } 81 | guard y >= 0, x >= 0 else { return .zero } 82 | 83 | if map[y][x].isEnemy != condition { return .zero } 84 | if map[y][x].isVisited { return .zero } 85 | 86 | map[y][x].isVisited = true 87 | 88 | let directions = [ 89 | (y: y-1, x: x), 90 | (y: y+1, x: x), 91 | (y: y, x: x-1), 92 | (y: y, x: x+1) 93 | ] 94 | 95 | return 1 + directions.reduce(0, { partialResult, point in 96 | partialResult + 97 | countingCellsInEiBlob(y: point.y, x: point.x, with: condition, within: &map) 98 | }) 99 | } 100 | 101 | -------------------------------------------------------------------------------- /Boj_Soobak/1759_수박.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1759_수박.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by kjs on 2022/01/13. 6 | // 7 | 8 | let originOfVowel = ["a", "e", "i", "o", "u"] 9 | 10 | var result = [String]() 11 | 12 | if let input = readLine()?.split(separator: " ").compactMap({ Int($0 )}), 13 | let characters = readLine()?.split(separator: " ").map({ String($0) }).sorted() { 14 | let N = input[0] 15 | let vowels = originOfVowel.filter { characters.contains($0) } 16 | 17 | for index in 0...(characters.count-N) { 18 | build(string: "", index: index, desiredLength: N, vowels: vowels, map: characters) 19 | } 20 | 21 | print(result.joined(separator: "\n")) 22 | } 23 | 24 | 25 | 26 | func build(string: String, index: Int, desiredLength: Int, vowels: [String],map: [String]) { 27 | //base case for checking index 28 | guard index < map.count else { return } 29 | 30 | var string = string 31 | string += map[index] 32 | 33 | //base case for cheking buildedString 34 | if string.count == desiredLength { 35 | 36 | // condition 1 37 | if string.count < 3 { 38 | return 39 | } 40 | 41 | // condition 2 42 | let filteredVowel = string.filter { vowels.contains(String($0)) } 43 | if filteredVowel.count < 1 { 44 | return 45 | } 46 | 47 | // condition 3 48 | let filteredConsonant = string.filter { !vowels.contains(String($0)) } 49 | if filteredConsonant.count < 2 { 50 | return 51 | } 52 | 53 | result.append(string) 54 | 55 | return 56 | } 57 | 58 | for index in (index+1).. UInt8 { 24 | defer { index += 1 } 25 | return buffer[index] 26 | } 27 | 28 | @inline(__always) func readInt() -> Int { 29 | var sum = 0 30 | var now = read() 31 | var isPositive = true 32 | 33 | while now == 10 || now == 32 { 34 | now = read() 35 | } 36 | if now == 45 { 37 | isPositive.toggle() 38 | now = read() 39 | } 40 | while now >= 48, now <= 57 { 41 | sum = sum * 10 + Int(now-48) 42 | now = read() 43 | } 44 | 45 | return sum * (isPositive ? 1:-1) 46 | } 47 | 48 | @inline(__always) func readInput() -> Int { 49 | var now = read() 50 | var str = 0 51 | 52 | while now == 10 || now == 32 { 53 | now = read() 54 | } 55 | 56 | while now != 10, now != 32, now != 0 { 57 | str += Int(now) 58 | now = read() 59 | } 60 | 61 | return str 62 | } 63 | } 64 | 65 | enum InputCases: Int { 66 | case push = 448 67 | case pop = 335 68 | case size = 443 69 | case empty = 559 70 | case front = 553 71 | case back = 401 72 | } 73 | 74 | enum ResultCases: Int { 75 | case canNotFind = -1 76 | case notEmptied 77 | case emptied 78 | } 79 | 80 | let reader = FileIO() 81 | let orderSize = reader.readInt() 82 | var queue = Queue() 83 | var result = "" 84 | 85 | for _ in 0.. { 130 | private var linkedList = LinkedList() 131 | var size = 0 132 | 133 | var head: AnyType? { 134 | linkedList.head?.value 135 | } 136 | 137 | var tail: AnyType? { 138 | linkedList.tail?.value 139 | } 140 | 141 | var isEmpty: Bool { 142 | linkedList.head == nil 143 | } 144 | 145 | mutating func insert(_ value: AnyType) { 146 | linkedList.append(value) 147 | size += 1 148 | } 149 | 150 | mutating func delete() -> AnyType? { 151 | defer { 152 | if linkedList.removeFirst() { 153 | size -= 1 154 | } 155 | } 156 | 157 | return linkedList.head?.value 158 | } 159 | } 160 | 161 | // MARK: - components 162 | extension Queue { 163 | private class Node { 164 | private(set) var value: AnyType 165 | var next: Node? 166 | 167 | init(value: AnyType) { 168 | self.value = value 169 | } 170 | } 171 | 172 | private class LinkedList { 173 | private(set) var head: Node? 174 | private(set) weak var tail: Node? 175 | 176 | var isEmpty: Bool { 177 | return head == nil 178 | } 179 | 180 | func append(_ value: AnyType) { 181 | let newNode = Node(value: value) 182 | 183 | if isEmpty { 184 | head = newNode 185 | } else { 186 | tail?.next = newNode 187 | } 188 | 189 | tail = newNode 190 | } 191 | 192 | func removeFirst() -> Bool { 193 | guard let head = head else { 194 | return false 195 | } 196 | self.head = head.next 197 | return true 198 | } 199 | } 200 | } 201 | -------------------------------------------------------------------------------- /Boj_Soobak/2178_수박.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 2178_수박.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by kjs on 2022/02/18. 6 | // 7 | 8 | struct Node { 9 | var order = 0 10 | var isVisitied = false 11 | var isBlocked: Bool 12 | 13 | init(isBlocked: Bool) { 14 | self.isBlocked = isBlocked 15 | } 16 | } 17 | 18 | if let input = readLine()?.split(separator: " ").compactMap({ Int($0) }), 19 | input.count >= 2 { 20 | // 1. prepare 21 | let height = input[0], width = input[1] 22 | var map = [[Node]]() 23 | 24 | for y in 0..() 38 | queue.enqueue((y: .zero, x: .zero)) 39 | map[.zero][.zero].order = 1 40 | 41 | while queue.isEmpty == false { 42 | guard let (y, x) = queue.dequeue() else { break } 43 | 44 | map[y][x].isVisitied = true 45 | 46 | let directions = [ 47 | (y: y+1, x: x), 48 | (y: y-1, x: x), 49 | (y: y, x: x+1), 50 | (y: y, x: x-1) 51 | ] 52 | 53 | directions 54 | .filter { (y: Int, x: Int) in 55 | y < height && 56 | x < width && 57 | y >= .zero && 58 | x >= .zero && 59 | map[y][x].isBlocked == false && 60 | map[y][x].isVisitied == false 61 | } 62 | .forEach { nextPoint in 63 | map[nextPoint.y][nextPoint.x].order = map[y][x].order + 1 64 | map[nextPoint.y][nextPoint.x].isVisitied = true 65 | 66 | queue.enqueue(nextPoint) 67 | } 68 | } 69 | 70 | print(map[height-1][width-1].order) 71 | } 72 | 73 | class Queue { 74 | private var list = [Element]() 75 | var isEmpty: Bool { 76 | list.count == 0 77 | } 78 | 79 | func enqueue(_ element: Element) { 80 | list.append(element) 81 | } 82 | 83 | func dequeue() -> Element? { 84 | guard list.count >= 1 else { return nil } 85 | 86 | return list.removeFirst() 87 | } 88 | } 89 | 90 | -------------------------------------------------------------------------------- /Boj_Soobak/2557_수박.swift: -------------------------------------------------------------------------------- 1 | // 2 | // HelloWorld_수박.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by kjs on 2021/12/07. 6 | // 7 | 8 | import Foundation 9 | 10 | print("Hello World!") 11 | -------------------------------------------------------------------------------- /Boj_Soobak/2558_수박.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 2558_수박.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by kjs on 2021/12/07. 6 | // 7 | 8 | import Foundation 9 | 10 | if let inputA = readLine(), 11 | let inputB = readLine(), 12 | let upperNumber = Int(inputA), 13 | let lowerNumber = Int(inputB) { 14 | let eachDigitOfLowerNumber = lowerNumber.description 15 | .compactMap { Int($0.description) } 16 | .reversed() 17 | 18 | for digit in eachDigitOfLowerNumber { 19 | print(upperNumber * digit) 20 | } 21 | 22 | print(upperNumber * lowerNumber) 23 | } 24 | -------------------------------------------------------------------------------- /Boj_Soobak/2667_수박.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 2667_수박.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by kjs on 2022/01/05. 6 | // 7 | 8 | /* 9 | 1. 각각의 포인트에서 색칠이 된 것인지, 방문이 된 것인지를 확인할 값타입이(Node) 필요함 10 | 2. 입력값을 이러한 값타입의 2차원 배열로 맵핑할 로직이 필요함 11 | 3. 각각의 포인트에서 상하좌우를 재귀적으로 찾아가며 카운트를 해줄 함수가 필요함 12 | - 이 때 한번이라도 카운팅이 된 노드는 다시 카운팅이 되면 안됨. 재귀함수에서 미리 조치를 취해야함 13 | 4. 모든 포인트에 대해서, 카운트가 0이면 넘어가고 0이 아니면 이 양의 정수를 저장해놓을 배열과 로직이 필요함 14 | 5. 정수를 저장해놓은 배열의 카운트와 함께 각각의 요소를 계행하면서 프린트를 해줄 로직이 필요함 15 | */ 16 | 17 | // 1v 18 | struct Node: CustomStringConvertible { 19 | //print 해보기용 20 | var description: String { 21 | if isFilled { 22 | return "O" 23 | } else { 24 | return " " 25 | } 26 | 27 | } 28 | 29 | let isFilled: Bool 30 | var isVisited = false 31 | 32 | init(_ character: Character) { 33 | if character == "0" { 34 | isFilled = false 35 | } else { 36 | isFilled = true 37 | } 38 | } 39 | } 40 | 41 | var countedComplexes = [Int]() 42 | 43 | if let input = readLine(), 44 | let rectangleSize = Int(input) { 45 | 46 | var map = [[Node]]() 47 | 48 | // 2v 49 | for _ in 0.. Int { 92 | guard y < map.count, x < map.count else { return .zero } 93 | guard y >= 0, x >= 0 else { return .zero } 94 | 95 | if map[y][x].isVisited { return .zero } 96 | 97 | map[y][x].isVisited = true 98 | 99 | if map[y][x].isFilled { 100 | let directions = [ 101 | (y: y-1, x: x), 102 | (y: y, x: x-1), 103 | (y: y, x: x+1), 104 | (y: y+1, x: x), 105 | ] 106 | return 1 + directions.reduce(0, { partialResult, point in 107 | return partialResult + countingHouseNearBy(y: point.y, x: point.x, on: &map) 108 | }) 109 | } else { 110 | return .zero 111 | } 112 | } 113 | 114 | -------------------------------------------------------------------------------- /Boj_Soobak/4949_수박.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 4949_수박.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by kjs on 2021/12/10. 6 | // 7 | 8 | import Foundation 9 | 10 | enum RoundBracket: Character { 11 | case open = "(" 12 | case closed = ")" 13 | } 14 | 15 | enum SquareBracket: Character { 16 | case open = "[" 17 | case closed = "]" 18 | } 19 | 20 | var result = "" 21 | 22 | while let input = readLine(), input != "." { 23 | var stack = Stack() 24 | var isBreaked = false 25 | 26 | for character in input { 27 | if character == RoundBracket.open.rawValue { 28 | stack.push(RoundBracket.open.rawValue) 29 | } else if character == SquareBracket.open.rawValue { 30 | stack.push(SquareBracket.open.rawValue) 31 | } else if character == RoundBracket.closed.rawValue && 32 | stack.head == RoundBracket.open.rawValue { 33 | let _ = stack.pop() 34 | } else if character == SquareBracket.closed.rawValue && 35 | stack.head == SquareBracket.open.rawValue { 36 | let _ = stack.pop() 37 | } else if character == RoundBracket.closed.rawValue || character == SquareBracket.closed.rawValue { 38 | isBreaked = true 39 | break 40 | } 41 | } 42 | 43 | if stack.size == 0 && isBreaked == false { 44 | result += "yes\n" 45 | } else { 46 | result += "no\n" 47 | } 48 | } 49 | 50 | print(result.trimmingCharacters(in: .whitespacesAndNewlines)) 51 | 52 | struct Stack { 53 | private var linkedList = LinkedList() 54 | var size = 0 55 | 56 | var head: AnyType? { 57 | linkedList.tail?.value 58 | } 59 | 60 | var isEmpty: Bool { 61 | linkedList.head == nil 62 | } 63 | 64 | mutating func push(_ value: AnyType) { 65 | linkedList.append(value) 66 | size += 1 67 | } 68 | 69 | mutating func pop() -> AnyType? { 70 | defer { 71 | if linkedList.removeLast() { 72 | size -= 1 73 | } 74 | } 75 | 76 | return linkedList.tail?.value 77 | } 78 | } 79 | 80 | 81 | // MARK: - components 82 | extension Stack { 83 | private class Node { 84 | private(set) var value: AnyType 85 | weak var prev: Node? 86 | var next: Node? 87 | 88 | init(value: AnyType, next: Node? = nil) { 89 | self.value = value 90 | } 91 | 92 | func updateValue(by value: AnyType) { 93 | self.value = value 94 | } 95 | } 96 | 97 | private struct LinkedList { 98 | private(set) var head: Node? 99 | private(set) weak var tail: Node? 100 | 101 | var isEmpty: Bool { 102 | return head == nil 103 | } 104 | 105 | mutating func append(_ value: AnyType) { 106 | let newNode = Node(value: value) 107 | 108 | if isEmpty { 109 | head = newNode 110 | head?.next = newNode 111 | } else { 112 | tail?.next = newNode 113 | newNode.prev = tail 114 | } 115 | 116 | tail = newNode 117 | } 118 | 119 | var target: Node? { 120 | return head?.next 121 | } 122 | 123 | mutating func remove(target: Node?) { 124 | var targetToDelete = head 125 | 126 | while target !== targetToDelete { 127 | targetToDelete = targetToDelete?.next 128 | } 129 | 130 | if let previousNode = targetToDelete?.prev { 131 | previousNode.next = targetToDelete?.next 132 | previousNode.next?.prev = previousNode 133 | } else { 134 | head = targetToDelete?.next 135 | } 136 | } 137 | 138 | mutating func removeLast() -> Bool { 139 | defer { 140 | if tail == nil { 141 | head = nil 142 | } 143 | } 144 | 145 | if tail != nil { 146 | tail = tail?.prev 147 | tail?.next = nil 148 | return true 149 | } else { 150 | return false 151 | } 152 | } 153 | 154 | init() { } 155 | 156 | init(headValue: AnyType) { 157 | self.append(headValue) 158 | } 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /Boj_Soobak/7576_수박.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 7576_수박.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by kjs on 2022/02/17. 6 | // 7 | 8 | struct TomatoBox { 9 | var order = 0 10 | var isRiped = false 11 | var isBlocked: Bool 12 | 13 | init(isBlocked: Bool) { 14 | self.isBlocked = isBlocked 15 | } 16 | } 17 | 18 | if let input = readLine()?.split(separator: " ").compactMap({ Int($0) }), 19 | input.count >= 2 { 20 | // 1. prepare 21 | let width = input[0], height = input[1] 22 | let queue = Queue<(y: Int, x: Int)>() 23 | var map = Array( 24 | repeating: Array(repeating: TomatoBox(isBlocked: false), count: width), 25 | count: height 26 | ) 27 | 28 | for y in 0..= .zero && 73 | point.x >= .zero && 74 | map[point.y][point.x].isBlocked == false && 75 | map[point.y][point.x].isRiped == false 76 | } 77 | .forEach { nextPoint in 78 | map[nextPoint.y][nextPoint.x].isRiped = true 79 | map[nextPoint.y][nextPoint.x].order = map[y][x].order + 1 80 | result = map[nextPoint.y][nextPoint.x].order 81 | queue.enqueue(nextPoint) 82 | } 83 | } 84 | 85 | //3 check unreached point 86 | for row in map { 87 | for tomato in row { 88 | if tomato.isBlocked == false && tomato.isRiped == false { 89 | result = -1 90 | break 91 | } 92 | } 93 | } 94 | 95 | print(result) 96 | } 97 | 98 | 99 | // MARK: - Note 100 | /* 101 | Queue를 struct로 mutating하게 만들면 102 | 시간이 아슬아슬해서 서버 상태에 따라 성공하기도 하고 시간초과가 나기도 함 103 | class로 만들어서 heap을 쓰게 되면 잘 통과함 104 | */ 105 | class Queue { 106 | private let linkedList = LinkedList() 107 | 108 | var isEmpty: Bool { 109 | linkedList.head == nil 110 | } 111 | 112 | func enqueue(_ element: Element) { 113 | linkedList.append(element) 114 | } 115 | 116 | func dequeue() -> Element? { 117 | return linkedList.removeFirst() 118 | } 119 | 120 | private class Node { 121 | private(set) var value: Element 122 | weak var prev: Node? 123 | var next: Node? 124 | 125 | init(value: Element) { 126 | self.value = value 127 | } 128 | } 129 | 130 | private class LinkedList { 131 | private(set) var head: Node? 132 | private(set) weak var tail: Node? 133 | 134 | var isEmpty: Bool { 135 | return head == nil 136 | } 137 | 138 | func append(_ element: Element) { 139 | let newNode = Node(value: element) 140 | 141 | if isEmpty { 142 | head = newNode 143 | } else { 144 | tail?.next = newNode 145 | newNode.prev = tail 146 | } 147 | 148 | tail = newNode 149 | } 150 | 151 | func removeFirst() -> Element? { 152 | defer { 153 | head = head?.next 154 | } 155 | 156 | return head?.value 157 | } 158 | 159 | init() { } 160 | } 161 | } 162 | 163 | -------------------------------------------------------------------------------- /Boj_Soobak/9019_수박.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 9019_수박.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by kjs on 2022/02/20. 6 | // 7 | 8 | typealias DSLR = (_ n: Int) -> Int 9 | 10 | func D(_ n: Int) -> Int { 11 | return (2 * n) % 10000 12 | } 13 | 14 | func S(_ n: Int) -> Int { 15 | return n == 0 ? 9999 : n-1 16 | } 17 | 18 | func L(_ n: Int) -> Int { 19 | let pulledN = (n % 1000) * 10 20 | let last = n / 1000 21 | return pulledN + last 22 | } 23 | 24 | func R(_ n: Int) -> Int { 25 | let pushedN = n / 10 26 | let first = (n % 10) * 1000 27 | return first + pushedN 28 | } 29 | 30 | let directions: [(DSLR, String)] = [ 31 | (D, "D"), 32 | (S, "S"), 33 | (L, "L"), 34 | (R, "R") 35 | ] 36 | 37 | if let inputLength = readLine().flatMap(Int.init) { 38 | var result = "" 39 | 40 | for _ in 0..() 50 | queue.enqueue((number: startNumber, flag: "")) 51 | 52 | var everVisitied = Array(repeating: false, count: 10000) 53 | everVisitied[startNumber] = true 54 | 55 | var inProgress = true 56 | while inProgress { 57 | guard let (number, currentFlag) = queue.dequeue() else { break } 58 | 59 | for (dslr, flag) in directions { 60 | let number = dslr(number) 61 | 62 | if everVisitied[number] { 63 | continue 64 | } 65 | 66 | let flag = currentFlag + flag 67 | if number == targetNumber { 68 | result += flag + "\n" 69 | inProgress = false 70 | break 71 | } else { 72 | everVisitied[number] = true 73 | queue.enqueue((number: number, flag: flag)) 74 | } 75 | } 76 | } 77 | } 78 | 79 | print(result) 80 | } 81 | 82 | // MARK: - struct queue 83 | struct Queue { 84 | private var list = [Element]() 85 | private var index = 0 86 | 87 | var isEmpty: Bool { 88 | return index >= list.count 89 | } 90 | 91 | mutating func enqueue(_ element: Element) { 92 | list.append(element) 93 | } 94 | 95 | mutating func dequeue() -> Element? { 96 | if isEmpty { 97 | return nil 98 | } 99 | 100 | defer { 101 | index += 1 102 | } 103 | 104 | return list[index] 105 | } 106 | } 107 | 108 | // MARK: - class queue 109 | //class Queue { 110 | // private var list = [Element]() 111 | // private var index = 0 112 | // 113 | // var isEmpty: Bool { 114 | // return index >= list.count 115 | // } 116 | // 117 | // func enqueue(_ element: Element) { 118 | // list.append(element) 119 | // } 120 | // 121 | // func dequeue() -> Element? { 122 | // if isEmpty { 123 | // return nil 124 | // } 125 | // 126 | // defer { 127 | // index += 1 128 | // } 129 | // 130 | // return list[index] 131 | // } 132 | //} 133 | 134 | 135 | 136 | 137 | -------------------------------------------------------------------------------- /Boj_Soobak/9663_수박.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 9663_수박.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by kjs on 2022/02/11. 6 | // 7 | 8 | if let N = readLine().flatMap({ Int($0) }) { 9 | let result = NQueens(N).excute() 10 | print(result) 11 | } 12 | 13 | final class NQueens { 14 | private let limitOfFirstRow: Int 15 | private var board: [Int] 16 | private var summary = 0 17 | 18 | private var isOdd: Bool 19 | private var extraSummary = 0 20 | 21 | init(_ N: Int) { 22 | self.board = Array(repeating: .zero, count: N) 23 | limitOfFirstRow = N/2 24 | 25 | if N % 2 == 1 { 26 | isOdd = true 27 | } else { 28 | isOdd = false 29 | } 30 | } 31 | 32 | func excute() -> Int { 33 | dfs(level: .zero) 34 | var result = summary * 2 35 | if isOdd { 36 | result += extraSummary 37 | } 38 | return result 39 | } 40 | 41 | private func dfs(level: Int) { 42 | if isOdd { 43 | if board[0] > limitOfFirstRow { return } 44 | } else { 45 | if board[0] >= limitOfFirstRow { return } 46 | } 47 | 48 | if level == board.count { 49 | if isOdd && board[0] == limitOfFirstRow { 50 | extraSummary += 1 51 | } else { 52 | summary += 1 53 | } 54 | return 55 | } 56 | 57 | for x in 0.. Bool { 66 | for index in 0.. UInt8 { 25 | defer { 26 | index += 1 27 | } 28 | guard index < buffer.count else { return 0 } 29 | 30 | return buffer[index] 31 | } 32 | 33 | @inline(__always) func readInt() -> Int { 34 | var sum = 0 35 | var now = read() 36 | var isPositive = true 37 | 38 | while now == 10 39 | || now == 32 { now = read() } // 공백과 줄바꿈 무시 40 | if now == 45 { isPositive.toggle(); now = read() } // 음수 처리 41 | while now >= 48, now <= 57 { 42 | sum = sum * 10 + Int(now-48) 43 | now = read() 44 | } 45 | 46 | return sum * (isPositive ? 1:-1) 47 | } 48 | 49 | 50 | @inline(__always) func readString() -> String { 51 | var str = "" 52 | var now = read() 53 | 54 | while now == 10 55 | || now == 32 { now = read() } // 공백과 줄바꿈 무시 56 | 57 | while now != 10 58 | && now != 32 && now != 0 { 59 | str += String(bytes: [now], encoding: .ascii)! 60 | now = read() 61 | } 62 | 63 | return str 64 | } 65 | } 66 | class Queue { 67 | var storage : [Value] = [] 68 | 69 | func enqueue(value: Value) { 70 | storage.append(value) 71 | } 72 | 73 | func dequeue() -> Value? { 74 | storage.removeFirst() 75 | } 76 | 77 | func empty() { 78 | storage = [] 79 | } 80 | 81 | func front() -> Value? { 82 | storage.first 83 | } 84 | 85 | func back() -> Value? { 86 | storage.last 87 | } 88 | 89 | func size() -> Int? { 90 | storage.count 91 | } 92 | } 93 | 94 | let reader = FileIO() 95 | 96 | let first = reader.readInt() 97 | let queue = Queue() 98 | var result: [Int] = [] 99 | 100 | for i in 1...first { 101 | queue.enqueue(value: i) 102 | } 103 | 104 | if queue.storage.count == 1 { 105 | result.append(first) 106 | } 107 | 108 | let second = reader.readInt() 109 | 110 | while queue.back()! - queue.front()! != 0 { 111 | if second == 1 { 112 | queue.storage.map { number in 113 | result.append(number) 114 | } 115 | break 116 | } else { 117 | // term에 해당하는 것 까지 디큐해서 인큐하기 118 | for _ in 1...second - 1 { 119 | queue.enqueue(value: queue.dequeue()!) 120 | } 121 | result.append(queue.dequeue() ?? .zero) 122 | } 123 | 124 | if queue.storage.count == 1 { 125 | result.append(queue.front() ?? .zero) 126 | } 127 | } 128 | 129 | print("<" + result.map{ $0.description }.joined(separator: ", ") + ">") 130 | -------------------------------------------------------------------------------- /Boj_Tacocat/2557_Tacocat.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 2557.swift 3 | // AlgorithmStudy_Exercise 4 | // 5 | // Created by Do Yi Lee on 2021/12/08. 6 | // 7 | 8 | import Foundation 9 | //https://www.acmicpc.net/problem/2557 10 | 11 | print("Hello World!") 12 | 13 | -------------------------------------------------------------------------------- /Boj_Tacocat/2588_Tacocat.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 2588_Tacocat.swift 3 | // AlgorithmStudy_Exercise 4 | // 5 | // Created by Do Yi Lee on 2021/12/08. 6 | // 7 | 8 | import Foundation 9 | 10 | let firstInput = readLine()! 11 | let secondInput = readLine()! 12 | 13 | secondInput.description.compactMap { Int(String($0)) }.reversed().map { number in 14 | print(Int(firstInput)! * number) 15 | } 16 | print(Int(firstInput)! * Int(secondInput)!) 17 | -------------------------------------------------------------------------------- /Boj_Tacocat/4949_Tacocat.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 4949_Tacocat.swift 3 | // AlgorithmStudy_Exercise 4 | // 5 | // Created by Do Yi Lee on 2021/12/10. 6 | // 7 | 8 | import Foundation 9 | 10 | /* 11 | 이 문제는 스택을 활용하는 문제 12 | 13 | 방법 14 | 1. 괄호들을 추출한다 15 | 2. 괄호를 저장한 배열과 추가하는 배열을 비교한다. 16 | 3. 일치하는 경우 스택에 쌓지 않고 마지막 원소는 삭제한다. 17 | */ 18 | 19 | var flag = true 20 | var result = "" 21 | 22 | enum Bracket: Character { 23 | case roundOpen = "(" 24 | case roundClose = ")" 25 | case rectOpen = "[" 26 | case rectClose = "]" 27 | 28 | var mate: Self { 29 | switch self { 30 | case .roundOpen: 31 | return .roundClose 32 | case .roundClose: 33 | return .rectOpen 34 | case .rectOpen: 35 | return .rectClose 36 | case .rectClose: 37 | return .rectOpen 38 | } 39 | } 40 | } 41 | 42 | class Stack { 43 | var storage: [Character] = [] 44 | 45 | func pop() -> Character? { 46 | return storage.popLast() 47 | } 48 | 49 | func push(element: Character) { 50 | storage.append(element) 51 | } 52 | } 53 | 54 | while let input = readLine(), input != "." { 55 | let stack = Stack() 56 | var isSymetric = false 57 | 58 | for character in input { 59 | if character == Bracket.rectOpen.rawValue { 60 | stack.push(element: character) 61 | } else if character == Bracket.roundOpen.rawValue { 62 | stack.push(element: character) 63 | } else if character == Bracket.rectClose.rawValue && 64 | stack.storage.last == Bracket.rectOpen.rawValue { 65 | let _ = stack.pop() 66 | } else if character == Bracket.roundClose.rawValue && 67 | stack.storage.last == Bracket.roundOpen.rawValue { 68 | let _ = stack.pop() 69 | } else if character == Bracket.roundClose.rawValue || character == Bracket.rectClose.rawValue { 70 | isSymetric = true 71 | break 72 | } 73 | } 74 | 75 | if stack.storage.count == .zero, isSymetric == false { 76 | result += "yes\n" 77 | } else { 78 | result += "no\n" 79 | } 80 | } 81 | 82 | print(result.trimmingCharacters(in: .whitespacesAndNewlines)) 83 | -------------------------------------------------------------------------------- /Boj_ellen/1000_Ellen.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1000_Ellen.swift 3 | // Boj_Ellen 4 | // 5 | // Created by Ellen on 2021/12/09. 6 | // 7 | 8 | let userInput = readLine()! 9 | let array = userInput.split(separator: " ") 10 | print(Int(array[0])! + Int(array[1])!) 11 | -------------------------------------------------------------------------------- /Boj_ellen/1001_Ellen.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1001_Ellen.swift 3 | // Boj_Ellen 4 | // 5 | // Created by Ellen on 2021/12/09. 6 | // 7 | 8 | let userInput = readLine()! 9 | let array = userInput.split(separator: " ") 10 | print(Int(array[0])! - Int(array[1])!) 11 | -------------------------------------------------------------------------------- /Boj_ellen/1008_Ellen.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1008_Ellen.swift 3 | // Boj_Ellen 4 | // 5 | // Created by Ellen on 2021/12/09. 6 | // 7 | 8 | let userInput = readLine()! 9 | let array = userInput.split(separator: " ") 10 | print(Double(array[0])! / Double(array[1])!) 11 | -------------------------------------------------------------------------------- /Boj_ellen/10171_Ellen.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10171_Ellen.swift 3 | // Boj_Ellen 4 | // 5 | // Created by Ellen on 2021/12/09. 6 | // 7 | 8 | print("\\ /\\") 9 | print(" ) ( ')") 10 | print("( / )") 11 | print(" \\(__)|") 12 | -------------------------------------------------------------------------------- /Boj_ellen/10172_Ellen.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10172_Ellen.swift 3 | // Boj_Ellen 4 | // 5 | // Created by Ellen on 2021/12/09. 6 | // 7 | 8 | print(#"|\_/|"#) 9 | print(#"|q p| /}"#) 10 | print(#"( 0 )"""\"#) 11 | print(#"|"^"` |"#) 12 | print(#"||_/=\\__|"#) 13 | -------------------------------------------------------------------------------- /Boj_ellen/10430_Ellen.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10430_Ellen.swift 3 | // Boj_Ellen 4 | // 5 | // Created by Ellen on 2021/12/09. 6 | // 7 | 8 | let userInput = readLine()! 9 | let numbers = userInput.split(separator: " ") 10 | let a = Int(numbers[0])!, b = Int(numbers[1])!, c = Int(numbers[2])! 11 | 12 | print((a + b) % c) 13 | print(((a % c) + (b % c)) % c) 14 | print((a * b) % c) 15 | print((a % c) * (b % c) % c) 16 | -------------------------------------------------------------------------------- /Boj_ellen/10718_Ellen.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10718_Ellen.swift 3 | // Boj_Ellen 4 | // 5 | // Created by Ellen on 2021/12/09. 6 | // 7 | 8 | print("강한친구 대한육군") 9 | print("강한친구 대한육군") 10 | -------------------------------------------------------------------------------- /Boj_ellen/10828_Ellen.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10828_Ellen.swift 3 | // Boj_Ellen 4 | // 5 | // Created by Ellen on 2021/12/10. 6 | // 7 | 8 | let userInput = Int(readLine()!)! 9 | let params = ["push", "pop", "size", "empty", "top"] 10 | var stack: [Int] = [] 11 | 12 | for _ in 1...userInput { 13 | let userInput = readLine()! 14 | let splitedInput = userInput.split(separator: " ") 15 | if params.contains(String(splitedInput[0])) { 16 | switch splitedInput[0] { 17 | case "push": 18 | stack.append(Int(splitedInput[1])!) 19 | case "pop": 20 | if stack.isEmpty { 21 | print("-1") 22 | } else { 23 | print(stack.popLast()!) 24 | } 25 | case "size": 26 | print(stack.count) 27 | case "empty": 28 | if stack.isEmpty { 29 | print("1") 30 | } else { 31 | print("0") 32 | } 33 | case "top": 34 | if stack.isEmpty { 35 | print("-1") 36 | } else { 37 | print(stack.last!) 38 | 39 | } 40 | default: break 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Boj_ellen/10869_Ellen.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10869_Ellen.swift 3 | // Boj_Ellen 4 | // 5 | // Created by Ellen on 2021/12/09. 6 | // 7 | 8 | let userInput = readLine()! 9 | let array = userInput.split(separator: " ") 10 | 11 | print(Int(array[0])! + Int(array[1])!) 12 | print(Int(array[0])! - Int(array[1])!) 13 | print(Int(array[0])! * Int(array[1])!) 14 | print(Int(array[0])! / Int(array[1])!) 15 | print(Int(array[0])! % Int(array[1])!) 16 | -------------------------------------------------------------------------------- /Boj_ellen/10998_Ellen.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 10998_Ellen.swift 3 | // Boj_Ellen 4 | // 5 | // Created by Ellen on 2021/12/09. 6 | // 7 | 8 | let userInput = readLine()! 9 | let array = userInput.split(separator: " ") 10 | print(Int(array[0])! * Int(array[1])!) 11 | -------------------------------------------------------------------------------- /Boj_ellen/1158_Ellen.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 1158_Ellen.swift 3 | // Boj_Ellen 4 | // 5 | // Created by Ellen on 2021/12/17. 6 | // 7 | 8 | let userInput = readLine()!.split(separator: " ") 9 | 10 | let n: Int = Int(userInput[0])! 11 | let k: Int = Int(userInput[1])! 12 | 13 | var index: Int = 0 14 | var queue: [Int] = [] 15 | var answer: [Int] = [] 16 | 17 | for i in 1...n { 18 | queue.append(i) 19 | } 20 | 21 | while !queue.isEmpty { 22 | index += (k-1) 23 | if index > queue.count - 1 { 24 | index %= queue.count 25 | } 26 | answer.append(queue.remove(at: index)) 27 | } 28 | 29 | print("<", terminator: "") 30 | for i in 0...answer.count - 2 { 31 | print(answer[i], terminator: ", ") 32 | } 33 | print("\(answer.last!)>") 34 | -------------------------------------------------------------------------------- /Boj_ellen/18258_Ellen.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 18258_ellen.swift 3 | // Boj_Ellen 4 | // 5 | // Created by Ellen on 2021/12/17. 6 | // 7 | 8 | let userInput = Int(readLine()!)! 9 | let params = ["push", "pop", "size", "empty", "front", "back"] 10 | var queue: [Int] = [] 11 | 12 | for _ in 1...userInput { 13 | let splitedInput = readLine()!.split(separator:" ").map { String($0) } 14 | if params.contains(splitedInput[0]) { 15 | switch splitedInput[0] { 16 | case "push": 17 | queue.append(Int(splitedInput[1])!) 18 | case "pop": 19 | if queue.isEmpty { 20 | print("-1") 21 | } else { 22 | print(queue.popLast()!) 23 | } 24 | case "size": 25 | print(queue.count) 26 | case "empty": 27 | if queue.isEmpty { 28 | print("1") 29 | } else { 30 | print("0") 31 | } 32 | case "front": 33 | if queue.isEmpty { 34 | print("-1") 35 | } else { 36 | print(queue.first!) 37 | } 38 | case "back": 39 | if queue.isEmpty { 40 | print("-1") 41 | } else { 42 | print(queue.last!) 43 | } 44 | default: break 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Boj_ellen/2557_Ellen.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 2557_Ellen.swift 3 | // Boj_Ellen 4 | // 5 | // Created by Ellen on 2021/12/09. 6 | // 7 | 8 | print("Hello World!") 9 | -------------------------------------------------------------------------------- /Boj_ellen/2588_Ellen.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 2588_Ellen.swift 3 | // Boj_Ellen 4 | // 5 | // Created by Ellen on 2021/12/09. 6 | // 7 | 8 | let firstUserInput = readLine()! 9 | let secondUserInput = readLine()! 10 | var array: [Int] = [] 11 | var result: Int = 0 12 | 13 | for i in secondUserInput.reversed() { 14 | let number = Int(firstUserInput)! * i.wholeNumberValue! 15 | array.append(number) 16 | print(number) 17 | } 18 | 19 | array[1] *= 10 20 | array[2] *= 100 21 | 22 | array.forEach { i in 23 | result += i 24 | } 25 | 26 | print(result) 27 | -------------------------------------------------------------------------------- /Boj_ellen/4949_Ellen.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 4949_Ellen.swift 3 | // Boj_Ellen 4 | // 5 | // Created by Ellen on 2021/12/17. 6 | // 7 | 8 | while true { 9 | let userInput = readLine()! 10 | var check = true 11 | if userInput == "." { 12 | break 13 | } 14 | var stack: [String.Element] = [] 15 | 16 | for char in userInput { 17 | if "([".contains(char) { 18 | stack.append(char) 19 | } else if char == ")" { 20 | if !stack.isEmpty && stack.last! == "(" { 21 | stack.popLast() 22 | } else { 23 | check = false 24 | break 25 | } 26 | } else if char == "]" { 27 | if !stack.isEmpty && stack.last! == "[" { 28 | stack.popLast() 29 | } else { 30 | check = false 31 | break 32 | } 33 | } 34 | } 35 | 36 | if stack.isEmpty && check { 37 | print("yes") 38 | } else { 39 | print("no") 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Programmers_Coden/모의고사_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 모의고사_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2021/12/24. 6 | // 7 | 8 | /* 9 | 이 문제는 각 사람의 점수가 몇점인지 모두 체크해야 하는 문제이다. -> 완전탐색 10 | 반복문으로도 해결 가능하고 재귀로도 해결 가능하다. 11 | 12 | 풀이 13 | 1. 문제 정답 answers에 대해 모든 사람의 점수를 체크한다. -> 재귀 이용할 것임 14 | 2. 그 중 최고점인 사람의 점수를 뽑아낸다. 15 | 3. 첫번째 사람부터 세번째 사람까지 최고점과 동일한 점수일 경우 해당 사람의 번호를 반환할 배열에 차례대로 저장한다. -> 오름차순이 알아서 된다. 16 | 4. 만들어진 배열을 반환한다. 17 | */ 18 | 19 | var answer = [Int]() //실제 정답을 담을 배열 20 | 21 | func solution(_ answers:[Int]) -> [Int] { 22 | answer = answers 23 | //각 사람들의 정답 24 | let firstGuesses = [1, 2, 3, 4, 5] 25 | let secondGuesses = [2, 1, 2, 3, 2, 4, 2, 5] 26 | let thirdGuesses = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5] 27 | 28 | //각 사람들의 점수를 계산하고 순서대로 배열에 채점 결과를 저장 29 | var scoreResult = [Int]() 30 | scoreResult.append(checkScore(of: firstGuesses, answerIndex: .zero)) 31 | scoreResult.append(checkScore(of: secondGuesses, answerIndex: .zero)) 32 | scoreResult.append(checkScore(of: thirdGuesses, answerIndex: .zero)) 33 | 34 | let maxScore = scoreResult.max()! //최고 점수를 뽑아낸다. 35 | var result = [Int]() //반환 할 결과 값 36 | 37 | //최고 점수와 동일한 점수를 가진 사람들의 번호를 result에 추가한다. 38 | for index in scoreResult.indices { 39 | if scoreResult[index] == maxScore { 40 | result.append(index + 1) 41 | } 42 | } 43 | 44 | return result 45 | } 46 | 47 | //특정 사람의 추측성 답안지에 대해 점수를 체크하여 반환한다. 48 | func checkScore(of guesses: [Int], answerIndex: Int) -> Int{ 49 | if answerIndex >= answer.count { //base case - 모든 답 체크 완료 50 | return 0 51 | } else if guesses[answerIndex % guesses.count] == answer[answerIndex] { //recursive case 1 - 한 문제 맞춘 경우 52 | return 1 + checkScore(of: guesses, answerIndex: answerIndex + 1) 53 | } else { //recursive case 2 - 맞추지 못한 경우 54 | return checkScore(of: guesses, answerIndex: answerIndex + 1) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Programmers_Coden/수박수박수박수박수박수?_Coden.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 수박수박수박수박수박수?_Coden.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by JINHONG AN on 2022/01/06. 6 | // 7 | 8 | /* 9 | 주어지는 숫자 n의 길이에 맞춰 '수박' 글자를 반복하여 누적한 뒤 반환하는 문제 10 | n이 3이면 수박수 11 | n이 4이면 수박수박 12 | 13 | 이 문제는 단순 구현문제. 14 | 1. n이 짝수이면 n/2 만큼 '수박' 글자를 반복시키기 15 | 2. n이 홀수이면 n/2 만큼 '수박' 글자를 반복시킨 뒤 맨 뒤에 '수' 붙이기 16 | */ 17 | 18 | func solution(_ length: Int) -> String { // n -> length로 네이밍 변경 19 | let watermelon = "수박" 20 | let numberOfRepetitions = length / 2 //기본적으로 n/2만큼은 반복해야 한다. 21 | var result = "" 22 | 23 | for _ in 0.. Int { 22 | availableNumbers = numbers 23 | targetNumber = target 24 | 25 | accumulateNumber(of: 0, to: 0) //0번 인덱스의 값부터 0에 누적시켜 나아가자 26 | 27 | return numberOfWays 28 | } 29 | 30 | //재귀적으로 돌아가며 index 위치의 값을 sum에 누적시켜 답을 찾아나갈 DFS 함수 31 | func accumulateNumber(of index: Int, to sum: Int) { 32 | if index >= availableNumbers.count { //base case - 모든 숫자를 다 더한 경우 33 | if sum == targetNumber { 34 | numberOfWays += 1 35 | } 36 | return 37 | } else { //recursive case - 아직 더해볼 숫자가 남아있는 경우 38 | accumulateNumber(of: index + 1, to: sum + availableNumbers[index]) 39 | accumulateNumber(of: index + 1, to: sum - availableNumbers[index]) 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Programmers_Soobak/모의고사_수박.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 모의고사_수박.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by kjs on 2021/12/23. 6 | // 7 | 8 | func solution(_ answers:[Int]) -> [Int] { 9 | let patterns = [ 10 | [1, 2, 3, 4, 5], 11 | [2, 1, 2, 3, 2, 4, 2, 5], 12 | [3, 3, 1, 1, 2, 2, 4, 4, 5, 5] 13 | ] 14 | 15 | var scoreBoard = [1: 0, 2: 0, 3: 0] 16 | 17 | for pattern in patterns { 18 | if let index = patterns.firstIndex(of: pattern) { 19 | let scoreIndex = index + 1 20 | 21 | var score = 0 22 | 23 | for index in answers.indices { 24 | let currentPick = pattern[index % pattern.count] 25 | 26 | if answers[index] == currentPick { 27 | score += 1 28 | } 29 | } 30 | 31 | scoreBoard[scoreIndex] = score 32 | } 33 | } 34 | 35 | return scoreBoard 36 | .filter { (key: Int, value: Int) in 37 | value == scoreBoard.values.max() 38 | } 39 | .map { (key: Int, value: Int) in 40 | return key 41 | } 42 | .sorted() 43 | } 44 | -------------------------------------------------------------------------------- /Programmers_Soobak/수박수박수?_수박.swift: -------------------------------------------------------------------------------- 1 | // 2 | // 수박수박수?_수박.swift 3 | // AlgorithmStudy 4 | // 5 | // Created by kjs on 2021/12/24. 6 | // 7 | 8 | func solution(_ n:Int) -> String { 9 | let length = n / 2 10 | 11 | var result = "" 12 | 13 | for _ in 0.. Int { 9 | var result = 0 10 | build(number: .zero, index: .zero, desiredNumber: target, origin: numbers, result: &result) 11 | return result 12 | } 13 | 14 | func build(number: Int, index: Int, desiredNumber: Int, origin: [Int], result: inout Int) { 15 | if index == origin.count { 16 | if number == desiredNumber { 17 | result += 1 18 | } 19 | return 20 | } 21 | 22 | let direction = [origin[index], -origin[index]] 23 | 24 | direction.forEach { int in 25 | let number = number + int 26 | build( 27 | number: number, index: index+1, 28 | desiredNumber: desiredNumber, origin: origin, result: &result 29 | ) 30 | } 31 | } 32 | --------------------------------------------------------------------------------