๋Œ€ํ‘œ๊ฐ’

2022. 10. 1. 09:47ใ†Algorithm

๋Œ€ํ‘œ๊ฐ’

 

 

 ๋ฌธ์ œ ์„ค๋ช…

 

N๋ช…์˜ ํ•™์ƒ์˜ ์ˆ˜ํ•™์ ์ˆ˜๊ฐ€ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. N๋ช…์˜ ํ•™์ƒ๋“ค์˜ ํ‰๊ท (์†Œ์ˆ˜ ์ฒซ์งธ์ž๋ฆฌ ๋ฐ˜์˜ฌ๋ฆผ)์„ ๊ตฌํ•˜๊ณ , N๋ช…์˜ ํ•™์ƒ ์ค‘ ํ‰๊ท ์— ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ํ•™์ƒ์€ ๋ช‡ ๋ฒˆ์งธ ํ•™์ƒ์ธ์ง€ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์„ธ ์š”.
ํ‰๊ท ๊ณผ ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ์ ์ˆ˜๊ฐ€ ์—ฌ๋Ÿฌ ๊ฐœ์ผ ๊ฒฝ์šฐ ๋จผ์ € ์ ์ˆ˜๊ฐ€ ๋†’์€ ํ•™์ƒ์˜ ๋ฒˆํ˜ธ๋ฅผ ๋‹ต์œผ๋กœ ํ•˜๊ณ , ๋†’์€ ์ ์ˆ˜๋ฅผ ๊ฐ€์ง„ ํ•™์ƒ์ด ์—ฌ๋Ÿฌ ๋ช…์ผ ๊ฒฝ์šฐ ๊ทธ ์ค‘ ํ•™์ƒ๋ฒˆํ˜ธ๊ฐ€ ๋น ๋ฅธ ํ•™์ƒ์˜ ๋ฒˆํ˜ธ๋ฅผ ๋‹ต์œผ๋กœ ํ•ฉ๋‹ˆ๋‹ค.

โ–ฃ ์ž…๋ ฅ์„ค๋ช…
์ฒซ์ค„์— ์ž์—ฐ์ˆ˜ N(5<=N<=100)์ด ์ฃผ์–ด์ง€๊ณ , ๋‘ ๋ฒˆ์งธ ์ค„์—๋Š” ๊ฐ ํ•™์ƒ์˜ ์ˆ˜ํ•™์ ์ˆ˜์ธ N๊ฐœ์˜ ์ž์—ฐ ์ˆ˜๊ฐ€ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. ํ•™์ƒ์˜ ๋ฒˆํ˜ธ๋Š” ์•ž์—์„œ๋ถ€ํ„ฐ 1๋กœ ์‹œ์ž‘ํ•ด์„œ N๊นŒ์ง€์ด๋‹ค.

โ–ฃ ์ถœ๋ ฅ์„ค๋ช…
์ฒซ์ค„์— ํ‰๊ท ๊ณผ ํ‰๊ท ์— ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ํ•™์ƒ์˜ ๋ฒˆํ˜ธ๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค. ํ‰๊ท ์€ ์†Œ์ˆ˜ ์ฒซ์งธ ์ž๋ฆฌ์—์„œ ๋ฐ˜์˜ฌ๋ฆผํ•ฉ๋‹ˆ๋‹ค.

โ–ฃ

10 45

โ–ฃ

74

์ž…๋ ฅ์˜ˆ์ œ 1
73 66 87 92 67 75 79 75 80

์ถœ๋ ฅ์˜ˆ์ œ 1 7

์˜ˆ์ œ์„ค๋ช…)
ํ‰๊ท ์ด 74์ ์œผ๋กœ ํ‰๊ท ๊ณผ ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ์ ์ˆ˜๋Š” 73(2๋ฒˆ), 75(7๋ฒˆ), 75(9๋ฒˆ)์ž…๋‹ˆ๋‹ค. ์—ฌ๊ธฐ์„œ ์ ์ˆ˜๊ฐ€ ๋†’์€ 75(7๋ฒˆ), 75(9๋ฒˆ)์ด ๋‹ต์ด ๋  ์ˆ˜ ์žˆ๊ณ , 75์ ์ด ๋‘๋ช…์ด๋ฏ€๋กœ ํ•™์ƒ๋ฒˆํ˜ธ๊ฐ€ ๋น ๋ฅธ 7๋ฒˆ์ด ๋‹ต์ด ๋ฉ๋‹ˆ๋‹ค.

 

 ๋‚˜์˜ ํ’€์ด

 

import Foundation

let n = Int(readLine()!)!
let input = readLine()!
let arr = input.components(separatedBy: " ")

let intArr = arr.map{Int($0)!}
let avg = Int(round(Double(intArr.reduce(0, +)) / Double(intArr.count)))
var minVal = 100
var minIdx = 0
var curVal = 0


for (i, num) in intArr.enumerated() {
  if abs(avg-num) <= minVal {
    if abs(avg-num) == minVal {
      if num > curVal {
        minVal = abs(avg-num)
        minIdx = i+1
        curVal = num
      } 
    } else {
        minVal = abs(avg-num)
        minIdx = i+1   
        curVal = num
    }
  }
}
print("\(avg) \(minIdx)")

 

 

 

 ๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด

 

import Foundation

let n = Int(readLine()!)!
let input = readLine()!
let arr = input.components(separatedBy: " ")

let intArr = arr.map{Int($0)!}
let avg = Int(round(Double(intArr.reduce(0, +)) / Double(intArr.count)))
var minVal = 100
var minIdx = 0
var curVal = 0


for (i, num) in intArr.enumerated() {
  let tmp = abs(avg-num)
  if tmp < minVal {
    minIdx = i+1
    minVal = tmp
    curVal = num
  } else if (tmp == minVal) {
    if num > curVal {
      minIdx = i+1
      curVal = num
    }
  }
}
print("\(avg) \(minIdx)")

 

 

 ํ”ผ๋“œ๋ฐฑ

1. ๋‚ด ํ’€์ด์—์„œ๋Š” if๋ฌธ ์•ˆ์—์„œ ๊ฐ€์€ ๊ฒฝ์šฐ์˜ ์ˆ˜(==)์„ ๋‘ ๋ฒˆ ์‚ฌ์šฉํ•ด์„œ ์กฐ๊ฑด์„ ํšจ๊ณผ์ ์œผ๋กœ ๋‚˜๋ˆ„์ง€ ๋ชปํ–ˆ๋‹ค. (์กฐ๊ฑด์„ ์ž˜ ๋‚˜๋ˆ„๋Š” ๊ฒƒ์ด ์ค‘์š”)

2. ์ค‘๋ณต๋˜๋Š” abs(avg-num)๋ฅผ ๋ณ€์ˆ˜๋กœ ๋‘์ž