https://school.programmers.co.kr/learn/courses/30/lessons/120861
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
나의 풀이
class Solution {
public int[] solution(String[] keyinput, int[] board) {
int weight = board[0] / 2;
int height = board[1] / 2;
int x = 0; int y = 0;
for (String input : keyinput) {
int nx = x;
int ny = y;
switch (input) {
case "left" -> nx = x - 1;
case "right" -> nx = x + 1;
case "up" -> ny = y + 1;
default -> ny = y - 1;
}
if (nx >= -weight && nx <= weight && ny >= -height && ny <= height) {
x = nx;
y = ny;
}
}
return new int[]{x, y};
}
}
다른 풀이
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
class Solution {
public int[] solution(String[] keyInput, int[] board) {
return Arrays.stream(keyInput).map(s -> getMap().get(s)).reduce((ints1, ints2) -> new int[] {
Math.abs(ints1[0] + ints2[0]) > board[0] / 2 ? board[0] / 2 * (ints1[0] < 0 ? -1 : 1) : ints1[0] + ints2[0],
Math.abs(ints1[1] + ints2[1]) > board[1] / 2 ? board[1] / 2 * (ints1[1] < 0 ? -1 : 1) : ints1[1] + ints2[1]
}).orElse(new int[]{0, 0});
}
private Map<String, int[]> getMap() {
Map<String, int[]> map = new HashMap<>();
map.put("up", new int[] {0, 1});
map.put("down", new int[] {0, - 1});
map.put("left", new int[] {-1, 0});
map.put("right", new int[] {1, 0});
return map;
}
}