Skip to content

Instantly share code, notes, and snippets.

@JCSooHwanCho
Last active April 27, 2024 10:53
Show Gist options
  • Star 51 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save JCSooHwanCho/30be4b669321e7a135b84a1e9b075f88 to your computer and use it in GitHub Desktop.
Save JCSooHwanCho/30be4b669321e7a135b84a1e9b075f88 to your computer and use it in GitHub Desktop.
ps할 때 입력을 한꺼번에 받기 위한 유틸리티 클래스. fread의 swift 버전.
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)])
}
}
// stdin Input: 1
import Foundation
let fIO = FileIO()
let n = fIO.readInt()
print(n) // 1
@JCSooHwanCho
Copy link
Author

20/04/05 - Int 처리기능만 가지는 상태

@JCSooHwanCho
Copy link
Author

20/04/15 - String 입력 받을 수 있는 메소드 추가

@JCSooHwanCho
Copy link
Author

20/09/16

  • 공백과 줄바꿈을 제외한 문자열의 아스키 값을 그대로 읽을 수 있는 메소드 추가
  • String 입력 메소드 및 FileIO 전체 성능 최적화

@JacksonPk
Copy link

덕분에 백준 잘 풀고있습니다. 감사합니다!!

@Mingyuuu0108
Copy link

감사합니다 ㅠㅠ

@iOS-Dev-Hyun
Copy link

감사합니다!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment