-
[프로그래머스]붕대감기 자바코딩테스트 2025. 3. 27. 17:22반응형
https://school.programmers.co.kr/learn/courses/30/lessons/250137
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
마지막 공격이 끝날 때 까지 붕대감기스킬을 시전하여 체력을 회복하고 남은 hp를 반환하는 문제.
도중 체력이 0이 되면 -1을 반환하고, 그 외의 경우 남은 체력을 반환해야 한다.
이중배열에 담긴 attack 정보를
int[] attackTimes 와 attackDamages로 분류하기 위해 Arrays.stream(attacks).mapToInt(attack -> attack[x]).toArray()를 사용해보았고
현재 시점이 피격시점인지 파악하기 위해 OptionalInt attackIdx = IntStream.range(0, attackTimes.length).filter(idx -> attackTimes[idx] == current).findFirst(); 로 필터링 한 후 isPresent()로 비교하여 처리하였다.
나에게 비교적 생소한 문법을 사용해볼 수 있어서 재밌었다.
import java.util.Arrays; import java.util.OptionalInt; import java.util.stream.IntStream; public class WrappingBandage { /** * t초 동안 매 초마다 x만큼 체력 회복. t초 연속으로 붕대감기 성공 시 y만큼 추가 회복. * 1. 시전 도중 피격시 기술 취소 * 2. 피격 순간시 체력 회복 불가 * 3. 피격 취소 혹은 시전 종료 후 즉시 재시전하며 연속 성공 시간은 0으로 초기화. * 4. 체력이 0 이하가 되면 더 이상의 회복 불가 * * bandage = {시전시간, 초당 회복량, 추가 회복량} * health = 최대 체력 * attacks = { {공격 시간, 피해량}, ... } * 모든 공격이 끝난 후 잔여 체력을 반환. * 단, 체력이 0 이하가 될 경우 -1 반환. * * */ public int solution(int[] bandage, int health, int[][] attacks) { int lastAttackTime = attacks[attacks.length -1][0]; int maxHp = health; int keepCount = 0; int actTime = bandage[0]; int recoverAmount = bandage[1]; int additionalR = bandage[2]; int [] attackTimes = Arrays.stream(attacks).mapToInt(attack -> attack[0]).toArray(); int [] attackDamages = Arrays.stream(attacks).mapToInt(attack -> attack[1]).toArray(); for(int i = 0; i <= lastAttackTime; i ++){ if(i > 0){ final int current = i; OptionalInt attackIdx = IntStream.range(0, attackTimes.length) .filter(idx -> attackTimes[idx] == current) .findFirst(); if(attackIdx.isPresent()) { // 공격 발생 int idx = attackIdx.getAsInt(); keepCount = 0; health = Math.max(health - attackDamages[idx], 0); if(health <= 0) return -1; //체력 0이하 즉시 종료. } else { //회복 keepCount ++; if(keepCount == actTime){ //추가회복 health = Math.min(health + recoverAmount + additionalR, maxHp); keepCount = 0; } else { //보통 회복 health = Math.min(health + recoverAmount, maxHp); } } } } return health; } }
반응형'코딩테스트' 카테고리의 다른 글
[프로그래머스]PCCE 기출문제[PCCE 기출문제] 10번 / 데이터 분석 자바 (0) 2025.03.28 [프로그래머스] [PCCE 기출문제] 9번 / 이웃한 칸 자바 (0) 2025.03.28 [프로그래머스] 가장 많이 받은 선물 자바 (0) 2025.03.27 [프로그래머스] [PCCE 기출문제] 10번 / 공원 (0) 2025.03.26 [프로그래머스] [PCCE 기출문제] 9번 / 지폐 접기 자바 (0) 2025.03.25