๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
3๏ธโƒฃ Swift/Problem Solving

[Swift Algorithm] ์Œ์–‘ ๋”ํ•˜๊ธฐ Programmers(Lv.1)

by seolhee2750 2021. 6. 18.
๋ฌธ์ œ ์„ค๋ช…

์–ด๋–ค ์ •์ˆ˜๋“ค์ด ์žˆ์Šต๋‹ˆ๋‹ค. ์ด ์ •์ˆ˜๋“ค์˜ ์ ˆ๋Œ“๊ฐ’์„ ์ฐจ๋ก€๋Œ€๋กœ ๋‹ด์€ ์ •์ˆ˜ ๋ฐฐ์—ด absolutes์™€ ์ด ์ •์ˆ˜๋“ค์˜ ๋ถ€ํ˜ธ๋ฅผ ์ฐจ๋ก€๋Œ€๋กœ ๋‹ด์€ ๋ถˆ๋ฆฌ์–ธ ๋ฐฐ์—ด signs๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. ์‹ค์ œ ์ •์ˆ˜๋“ค์˜ ํ•ฉ์„ ๊ตฌํ•˜์—ฌ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.

 

์ œํ•œ ์กฐ๊ฑด
  • absolutes์˜ ๊ธธ์ด๋Š” 1 ์ด์ƒ 1,000 ์ดํ•˜์ž…๋‹ˆ๋‹ค.
    • absolutes์˜ ๋ชจ๋“  ์ˆ˜๋Š” ๊ฐ๊ฐ 1 ์ด์ƒ 1,000 ์ดํ•˜์ž…๋‹ˆ๋‹ค.
  • signs์˜ ๊ธธ์ด๋Š” absolutes์˜ ๊ธธ์ด์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค.
    • signs[i] ๊ฐ€ ์ฐธ์ด๋ฉด absolutes[i] ์˜ ์‹ค์ œ ์ •์ˆ˜๊ฐ€ ์–‘์ˆ˜์ž„์„, ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด ์Œ์ˆ˜์ž„์„ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค.

 

์ž…์ถœ๋ ฅ ์˜ˆ
absolutes signs result
[4,7,12] [true,false,true] 9
[1,2,3] [false,false,true] 0

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
import Foundation

func solution(_ absolutes:[Int], _ signs:[Bool]) -> Int {
    var sum = 0
    
    for i in 0..<absolutes.count {
        signs[i] ? (sum += absolutes[i]) : (sum -= absolutes[i])
    }
    
    return sum
}
  • ์‚ผํ•ญ ์—ฐ์‚ฐ์ž๋ฅผ ์‚ฌ์šฉํ–ˆ๊ณ , ๋ฐฐ์—ด์ด Bool ๋ฐฐ์—ด์ด๊ธฐ ๋•Œ๋ฌธ์— ๋”ฐ๋กœ ์—ฐ์‚ฐ์ž ํ•„์š” ์—†์ด signs[i] ? ๋กœ ์‚ฌ์šฉํ–ˆ๋‹ค.
  • true๋ฉด ๋”ํ•ด์ฃผ๊ณ  false๋ฉด ๋นผ์ฃผ๋ฉด์„œ ๊ฐ’์„ ๋ˆ„์ ํ•ด์ฃผ์—ˆ๋‹ค.

 

์ธ์ƒ์ ์ธ ํ’€์ด
import Foundation

func solution(_ absolutes: [Int], _ signs: [Bool]) -> Int {
    var index = -1
    return absolutes.reduce(0) {
        index += 1
        return signs[index] ? $0 + $1 : $0 - $1
    }
}

 

 

  • reduce, ํด๋กœ์ €๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ฐ˜๋ณต๋ฌธ ์—†์ด ์™„์„ฑํ•œ ๊ฒƒ์ด ์ธ์ƒ๊นŠ์–ด ๊ฐ€์ ธ์™”๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ์‰ฌ์šด ๋ฌธ์ œ๋ผ ๊ธˆ๋ฐฉ ํ’€์—ˆ๋‹ค,.!!
  • reduce๋กœ ๋”ํ•ด์ฃผ๋Š” ๊ฒƒ๋„ ์ข‹์€ ๋ฐฉ๋ฒ•๊ฐ™๋‹ค.

 


๋ฌธ์ œ

https://programmers.co.kr/learn/courses/30/lessons/76501

๋Œ“๊ธ€