Today's Codekata
// 성격 유형 검사하기
class Solution {
public String solution(String[] survey, int[] choices) {
String answer = "";
Map<Character, Integer> map = new HashMap<>();
for (char c : new char[]{'R', 'T', 'C', 'F', 'J', 'M', 'A', 'N'}) {
map.put(c, 0);
}
for (int i = 0; i < survey.length; i++) {
int score = Math.abs(4 - choices[i]);
if (choices[i] < 4) {
map.put(survey[i].charAt(0), map.get(survey[i].charAt(0)) + score);
} else if (choices[i] > 4) {
map.put(survey[i].charAt(1), map.get(survey[i].charAt(1)) + score);
}
}
answer += (map.get('R') >= map.get('T')) ? "R" : "T";
answer += (map.get('C') >= map.get('F')) ? "C" : "F";
answer += (map.get('J') >= map.get('M')) ? "J" : "M";
answer += (map.get('A') >= map.get('N')) ? "A" : "N";
return answer;
}
}
객체를 활용하면 불필요한 변수 선언 없이도 깔끔하게 만들 수 있다는 걸 알게 되었다.
// 바탕화면 정리
class Solution {
public int[] solution(String[] wallpaper) {
int lux = 51;
int luy = 51;
int rdx = 0;
int rdy = 0;
for (int i = 0; i < wallpaper.length; i++) {
for (int j = 0; j < wallpaper[i].length(); j++) {
if (wallpaper[i].charAt(j) == '#') {
lux = Math.min(lux, i);
luy = Math.min(luy, j);
rdx = Math.max(rdx, i + 1);
rdy = Math.max(rdy, j + 1);
}
}
}
return new int[]{lux, luy, rdx, rdy};
}
}
최근에 `Map<>` 구조를 자꾸 활용하다보니 자연스럽게 맵에 담아서 최종적으로 작은 값과 큰 값을 꺼내면 되겠다고 생각했다. 하지만 생각해보니, 좌표를 탐색하면서 바로 갱신해주는 방식이 훨씬 간단하고 직관적이라 생각되어서 위와 같이 짜봤다.
# Average Time of Process per Machine
SELECT
s.machine_id,
ROUND(AVG(e.timestamp - s.timestamp), 3) AS processing_time
FROM Activity s
JOIN Activity e
ON s.machine_id = e.machine_id
WHERE s.activity_type = 'start'
AND e.activity_type = 'end'
GROUP BY s.machine_id;
# Employee Bonus
SELECT e.name, b.bonus
FROM Employee e
LEFT JOIN Bonus b on e.empId = b.empId
WHERE b.bonus < 1000 OR b.bonus IS NULL;
# Students and Examinations
SELECT s.student_id, s.student_name, sub.subject_name,
IFNULL(e.attended_exams, 0) as attended_exams
FROM Students s
CROSS JOIN Subjects sub
LEFT JOIN (
SELECT student_id, subject_name, COUNT(*) as attended_exams
FROM Examinations
GROUP BY student_id, subject_name
) e
ON s.student_id = e.student_id AND sub.subject_name = e.subject_name
ORDER BY s.student_id, sub.subject_name;
`CROSS JOIN`은 SQL에서 두 테이블의 모든 가능한 조합을 만드는 방식이다. 두 테이블 A와 B가 있고, A가 3개의 행, B가 2개의 행이 있다면 `A CROOS JOIN B`는 3 x 2 = 6개의 행을 만들어낸다. 위에서는 시험을 안 본 경우도 포함하기 위해 사용해줬다.
오늘도 잠깐이나마 코드카타를 통해 반복숙달하는 시간을 가졌다. 코드 한줄 한줄이 쌓여서 실력이 될거라 생각한다.