Skip to content

Instantly share code, notes, and snippets.

@stripe-q
Last active Aug 31, 2017
Embed
What would you like to do?
포커게임 점수계산
import Foundation
func poker(_ s: Substring) -> (Int, Int, Int) {
// 입력되는 카드정보 파싱
let cards = s.split(separator: " ")
let priorities = "23456789TJQKA"
var faceMap: [Character:Int] = [:]
var numberMap: [Int:Int] = [:]
var value = 0
var h1: Int? = nil
var h2: Int? = nil
for card in cards {
let (n, f) = (card.first!, card.last!)
let p = card.distance(from:priorities.startIndex,
to:(priorities.index(of: n))!) + 2
faceMap[f] = (faceMap[f] ?? 0) + 1
numberMap[p] = (numberMap[p] ?? 0) + 1
}
// Four of a Kind
numberMap.filter{ $0.1 == 4}.forEach {
value += 80_000
if h1 == nil { h1 = $0.0 }
}
// Flush
faceMap.filter{ $0.1 == 5 }.forEach { _ in
value += 50_000
if h1 == nil { h1 = numberMap.sorted{ $0.0 > $1.0 }.first?.0 }
}
// Straight
let isBefore:(Character, Character) -> Bool = { a, b in
let x = priorities.index(of: a) ?? priorities.startIndex
let y = priorities.index(of: b) ?? priorities.startIndex
return x < y
}
let k = String(cards.flatMap{ $0.first }.sorted(by: isBefore))
if let _ = priorities.range(of: k) {
value += 45_000
if h1 == nil { h1 = numberMap.sorted{ $0.0 > $1.0 }.first?.0 }
else if h2 == nil { h2 = numberMap.sorted{ $0.0 > $1.0 }.first?.0 }
}
// Three of a Kind
numberMap.filter{ $0.1 == 3 }.forEach { _ in
value += 40_000
if h1 == nil { h1 = numberMap.filter{ $0.1 == 3 }.first?.0 }
}
// Pairs
let n = (numberMap.filter{ $0.value == 2 })
n.sorted{ $0.0 > $1.0 }.forEach {
value += 15_000
if h1 == nil { h1 = $0.0 }
else if h2 == nil { h2 = $0.0 }
}
// High card
let m = numberMap.filter{ $0.1 == 1 }
m.sorted{ $0.0 > $1.0}.forEach{
if h1 == nil { h1 = $0.0 }
else if value > 0, h2 == nil { h2 = $0.0 }
}
return (value ,h1 ?? 0,h2 ?? 0)
}
func duel(_ a:Substring, _ b: Substring) -> Bool {
let (x, y) = (poker(a), poker(b))
if x.0 != y.0 { return x.0 > y.0 }
else if x.1 != y.1 { return x.1 > y.1 }
return x.2 > y.2
}
func main() {
guard let url = URL(string: "http://euler.synap.co.kr/files/poker.txt"),
let contents = try? String(contentsOf: url)
else { return }
let rounds = contents.split(separator: "\r\n") // 윈도에서 작성된 파일인듯?
var result = 0
for round in rounds {
let midPos = round.index(round.startIndex, offsetBy: round.count / 2)
let (p1, p2) = (round[..<midPos], round[midPos...])
result += (duel(p1, p2) ? 1 : 0)
}
print(result)
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment