learnings/PS

[๊ตฌ๋ฆ„Level] ๊ทœ์น™ ์ˆซ์ž ์•ผ๊ตฌ Swift ํ’€์ด

Une. 2024. 6. 15. 13:17

๋ฌธ์ œ์˜ ์š”๊ตฌ์‚ฌํ•ญ์„ ์ดํ•ดํ•˜๊ธฐ ํž˜๋“ค์—ˆ๋˜,,,
2๋‹จ๊ณ„์—์„œ fail์ผ ๋•Œ, ์ˆซ์ž ๋ณ€ํ™˜ ํ›„ 2๋‹จ๊ณ„๊ฐ€ ๋ชจ๋‘ ๋๋‚œ ๊ฐ’์„ ๋‹ค์‹œ ํ‰๊ฐ€ํ•˜์—ฌ 3๋‹จ๊ณ„๋ฅผ ์ง„ํ–‰ํ•˜๋Š” ์ค„ ์ดํ•ดํ–ˆ๋‹ค.
1๋‹จ๊ณ„์—์„œ๋งŒ ํ™•์ธํ•˜์˜€๋˜ strike๊ฐ’์— ๋Œ€ํ•ด์„œ๋งŒ 3๋‹จ๊ณ„๋ฅผ ์ง„ํ–‰ํ•˜๋„๋ก ์œ ์˜ํ•˜์ž.

๋ฌธ์ œ๋งํฌ

์†Œ์Šค์ฝ”๋“œ

๋”๋ณด๊ธฐ
let answer = readLine()!.map{ Int(String($0))! }
var expectation = readLine()!.map{ Int(String($0))! }
func isCorrect()->Bool{
		for i in 0..<4{
		if answer[i] != expectation[i]{ return false}
	}
	return true
}
if isCorrect() { print(1) }
else{
	var count = 1
		step2: while !isCorrect(){
		//2๋‹จ๊ณ„ ์ค‘ ball์˜ ๋ฐœ์ƒ์œ ๋ฌด
		var strikeIdx: [Int] = []
		var isBalled = false
		for i in 0..<4{
			if expectation[i] == answer[i]{ //strike๋ผ๋ฉด ๋‹ค์Œ ์ž๋ฆฌ๊ฐ’ ๊ฒ€์‚ฌ
				strikeIdx.append(i)
				continue } 
			if answer.contains(expectation[i]) == false{ //ํ˜„์žฌ ์ž๋ฆฌ๊ฐ’์ด fail์ด๋ผ๋ฉด
				var newExpectNum = expectation[i]
				while expectation.contains(newExpectNum) == true{ //๊ณ„์‚ฐ๊ฐ’์ด ๋‹ค๋ฅธ์ž๋ฆฌ์— ์กด์žฌํ•˜์ง€ ์•Š์„ ๋•Œ ๊นŒ์ง€ ๋ฐ˜๋ณต
					newExpectNum = (newExpectNum + 1) % 10
				}
				expectation[i] = newExpectNum
				continue
			}
			isBalled = true
		}
		if isBalled{
			var strikes: [Int] = []
			for i in strikeIdx{
				let strike = expectation[i]
				strikes.append(strike)
			}
			for strike in strikes{
				let idx = expectation.firstIndex(of:strike)!
				expectation.remove(at:idx)
			}
			let shiftLast = expectation.removeLast()
			expectation.insert(shiftLast, at:0)
				for i in strikeIdx.indices{
					expectation.insert(strikes[i], at: strikeIdx[i])
			}
		}
		count += 1
	}
	print(count)
}