[Swift] νλ‘κ·Έλλ¨Έμ€ μν΄λ¦¬ μ±λ¦°μ§ κ΅μ μ λ³ λ§λ€κΈ°
Problem
Solution
ν΄λΉ λ¬Έμ μ ν΅μ¬μ λ μ§μ (λ°©μ μ)μ κ΅μ μ μ°Ύλ λ°©λ²μ μλ κ²μ λλ€.
μλ λ μ§μ μ΄ μλ€κ³ κ°μ νκ² μ΅λλ€.
1. ax + by + c
2. dx + ey + f
κ΅μ μ μ°Ύλ μμ μλμ κ°μ΅λλ€.
x = (bf - ed) / (ad - bc)
y = (ec - af) / (ad - bc)
μ¬κΈ°μ ad - bcκ° λ§μ½ 0μ΄λΌλ©΄ λ μ§μ μ νννλ€λ μλ―Έμ λλ€.
μ λ°©μλλ‘ λͺ¨λ μ§μ μ κ΅μ μ μ°ΎμΌλ©° xμ κ°μ₯ ν° κ°κ³Ό μμ κ°, yμ κ°μ₯ ν° κ°κ³Ό μμ κ°μ μ°Ύμ μ΅μ μ¬κ°νμ λ²μλ₯Ό μ ν©λλ€.
λ§μ§λ§μΌλ‘ λ²μ μμμ κ΅μ μ μμΉλ₯Ό λ³λ‘ λ°κΏμ€ λ€ λ°νν©λλ€.
μ½λ ν΄μ€
κ΅μ ,μ΅μ μ¬κ°ν,μ§μ μ ꡬ쑰체λ₯Ό λ§λ€μ΄μ€λλ€.
struct Line {
let x:Int,y:Int,c:Int
}
struct Square {
var minX:Int = Int.max
var maxX:Int = -Int.max
var minY:Int = Int.max
var maxY:Int = -Int.max
}
struct Meet {
let x:Int,y:Int
}
1. κ΅μ μ μ°Ύλλ€.
μμμ κ΅μ μ ꡬνλ μμΌλ‘ λ μ§μ μ κ΅μ μ ꡬν΄μ€λλ€.
λ€λ§ λ¬Έμ μμ xμ y λͺ¨λ μ μμΈ κ΅μ λ§ νμνλ―λ‘ μ μκ° μλ κ²μ nilλ‘ λ°νν©λλ€.
func findMeet(_ l1:Line,_ l2:Line) -> Meet? {
let adbc = l1.x*l2.y - l1.y*l2.x
if adbc == 0 { return nil }
let bfed = l1.y*l2.c - l1.c*l2.y
let ecaf = l1.c*l2.x - l1.x*l2.c
let meet = Meet(x:bfed/adbc, y:ecaf/adbc)
return bfed % adbc == 0 && ecaf % adbc == 0 ? meet : nil
}
2. λͺ¨λ μ§μ μ κ΅μ μ ꡬνλ€.
λͺ¨λ μ§μ μ κ΅μ μ μ°Ύμ μ μ₯ν©λλ€.
func getIntegerMeet(lines:[[Int]]) -> [Meet] {
var lines:[[Int]] = lines
var meets:[Meet] = []
while !lines.isEmpty {
let first = lines.removeFirst()
let firstLine = Line(x:first[0], y:first[1], c: first[2])
for l in lines {
let otherLine = Line(x: l[0], y: l[1], c: l[2])
if let meet = findMeet(firstLine,otherLine) {
meets.append(meet)
}
}
}
return meets
}
3. λͺ¨λ κ΅μ λ€μ μ΄μ©ν΄ μ΅μ μ¬κ°νμ λ²μλ₯Ό μ νλ€.
func getSquare(meets:[Meet]) -> Square {
var square:Square = Square()
meets.forEach {
square.minX = min(square.minX,$0.x)
square.maxX = max(square.maxX,$0.x)
square.minY = min(square.minY,$0.y)
square.maxY = max(square.maxY,$0.y)
}
return square
}
4. μ΅μ μ¬κ°νμ κ΅μ μ λ³λ‘ λ°κΏμ€λ€.
xμ μ΅λκ° - μ΅μκ° + 1λ§νΌμ λ°°μ΄μ yμ μ΅λκ° - μ΅μκ° + 1λ§νΌ λ§λ€μ΄μ€λλ€.
κ·Έ λ€μ κ΅μ λ€μ νμΈνλ©΄μ λ³λ‘ λ°κΏμ€λλ€.
μ£Όμνμ€ μ μ μ’νμμ yκ°μ μλ‘ κ°μλ‘ μ»€μ§κΈ° λλ¬Έμ μ΅λκ°μμ νμ¬ yκ°μ λΉΌμ€λλ€.
func changeMeetsToStar(meets:[Meet],square:Square) -> [String] {
var sqaureDot = Array(repeating: Array(repeating: ".", count: square.maxX-square.minX+1), count: square.maxY-square.minY+1)
for meet in meets {
let x = meet.x - square.minX
let y = square.maxY - meet.y
sqaureDot[y][x] = "*"
}
return sqaureDot.map{$0.joined()}
}
5. λ³λ‘ λ°κΎΌ μ¬κ°νμ λ°ννλ€.
func solution(_ line:[[Int]]) -> [String] {
let meets:[Meet] = getIntegerMeet(lines:line)
let square = getSquare(meets: meets)
return changeMeetsToStar(meets: meets, square: square)
}
Source Code