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

[Swift Algorithm] ๋‚ด์  Programmers(Lv.1)

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

๊ธธ์ด๊ฐ€ ๊ฐ™์€ ๋‘ 1์ฐจ์› ์ •์ˆ˜ ๋ฐฐ์—ด a, b๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. a์™€ b์˜ ๋‚ด์ ์„ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.

์ด๋•Œ, a์™€ b์˜ ๋‚ด์ ์€ a[0]*b[0] + a[1]*b[1] + ... + a[n-1]*b[n-1] ์ž…๋‹ˆ๋‹ค. (n์€ a, b์˜ ๊ธธ์ด)

 

์ œํ•œ ์กฐ๊ฑด
  • a, b์˜ ๊ธธ์ด๋Š” 1 ์ด์ƒ 1,000 ์ดํ•˜์ž…๋‹ˆ๋‹ค.
  • a, b์˜ ๋ชจ๋“  ์ˆ˜๋Š” -1,000 ์ด์ƒ 1,000 ์ดํ•˜์ž…๋‹ˆ๋‹ค.

 

์ž…์ถœ๋ ฅ ์˜ˆ
a b result
[1,2,3,4] [-3,-1,0,2] 3
[-1,0,1] [1,0,-1] -2

 

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

func solution(_ a:[Int], _ b:[Int]) -> Int {
    var sum = 0
    for i in 0..<a.count {
        sum += a[i] * b[i]
    }
    return sum
}
  • ๋‘ ๋ฐฐ์—ด์˜ ๊ธธ์ด๊ฐ€ ๊ฐ™์œผ๋ฏ€๋กœ, ๊ทธ๋ƒฅ a ๋ฐฐ์—ด ๊ธธ์ด๊นŒ์ง€ ๋ฐ˜๋ณต๋ฌธ์„ ๋Œ๋ ค์คฌ๊ณ , ๋‘ ๋ฐฐ์—ด์˜ ๊ฐ™์€ ์›์†Œ ๊ฐ’์„ ๊ณฑํ•ด์„œ ๋ˆ„์ ํ–ˆ๋‹ค.

 

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

func solution(_ a:[Int], _ b:[Int]) -> Int {
    return zip(a, b).map(*).reduce(0, +)
}
  • zip์„ ์‚ฌ์šฉํ•˜์—ฌ a, b ๋ฐฐ์—ด์˜ ๊ฐ™์€ ์œ„์น˜ ์š”์†Œ๋“ค์„ ๊ณฑํ•ด์ค€ ํ›„ ๋ชจ๋‘ ๋”ํ•ด์ฃผ์—ˆ๋‹ค.!

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • zip์€ ๊ฑฐ์˜ ์‚ฌ์šฉํ•ด๋ณธ ์ ์ด ์—†์–ด์„œ ์ƒ๊ฐ์ง€๋„ ๋ชปํ–ˆ๋Š”๋ฐ, ์ด๋ ‡๊ฒŒ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค๊ณ  ๋ฐฐ์šธ ์ˆ˜ ์žˆ์—ˆ๋‹ค,,!!!

 


 

๋ฌธ์ œ

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

๋Œ“๊ธ€