Last active
December 19, 2024 06:21
-
-
Save JCSooHwanCho/30be4b669321e7a135b84a1e9b075f88 to your computer and use it in GitHub Desktop.
ps할 때 입력을 한꺼번에 받기 위한 유틸리티 클래스. fread의 swift 버전.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
final class FileIO { | |
private let buffer:[UInt8] | |
private var index: Int = 0 | |
init(fileHandle: FileHandle = FileHandle.standardInput) { | |
buffer = Array(try! fileHandle.readToEnd()!)+[UInt8(0)] // 인덱스 범위 넘어가는 것 방지 | |
} | |
@inline(__always) private func read() -> UInt8 { | |
defer { index += 1 } | |
return buffer[index] | |
} | |
@inline(__always) func readInt() -> Int { | |
var sum = 0 | |
var now = read() | |
var isPositive = true | |
while now == 10 | |
|| now == 32 { now = read() } // 공백과 줄바꿈 무시 | |
if now == 45 { isPositive.toggle(); now = read() } // 음수 처리 | |
while now >= 48, now <= 57 { | |
sum = sum * 10 + Int(now-48) | |
now = read() | |
} | |
return sum * (isPositive ? 1:-1) | |
} | |
@inline(__always) func readString() -> String { | |
var now = read() | |
while now == 10 || now == 32 { now = read() } // 공백과 줄바꿈 무시 | |
let beginIndex = index-1 | |
while now != 10, | |
now != 32, | |
now != 0 { now = read() } | |
return String(bytes: Array(buffer[beginIndex..<(index-1)]), encoding: .ascii)! | |
} | |
@inline(__always) func readByteSequenceWithoutSpaceAndLineFeed() -> [UInt8] { | |
var now = read() | |
while now == 10 || now == 32 { now = read() } // 공백과 줄바꿈 무시 | |
let beginIndex = index-1 | |
while now != 10, | |
now != 32, | |
now != 0 { now = read() } | |
return Array(buffer[beginIndex..<(index-1)]) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// stdin Input: 1 | |
import Foundation | |
let fIO = FileIO() | |
let n = fIO.readInt() | |
print(n) // 1 |
20/04/15 - String 입력 받을 수 있는 메소드 추가
20/09/16
- 공백과 줄바꿈을 제외한 문자열의 아스키 값을 그대로 읽을 수 있는 메소드 추가
- String 입력 메소드 및 FileIO 전체 성능 최적화
덕분에 백준 잘 풀고있습니다. 감사합니다!!
감사합니다 ㅠㅠ
감사합니다!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
20/04/05 - Int 처리기능만 가지는 상태