function compute(fr, fc, sr, sc) {
return Math.abs(fr - sr) + Math.abs(fc - sc);
}
function hasWiban(fr, fc, sr, sc, daegisil) {
let result = false;
if (fr === sr) {
if (daegisil[fr][(fc + sc) / 2] === "O") {
result = true;
}
}
if (fc === sc) {
if (daegisil[(fr + sr) / 2][fc] === "O") {
result = true;
}
}
if (daegisil[sr][fc] === "O" || daegisil[fr][sc] === "O") {
result = true;
}
return result;
}
function solution(places) {
const answer = [];
places.forEach((daegisil) => {
let isPerfect = true;
const peoples = [];
daegisil.forEach((line, row) => {
line
.split("")
.forEach(
(seat, column) => seat === "P" && peoples.push({ row, column })
);
});
for (let i = 0; i < peoples.length; i++) {
for (let j = i + 1; j < peoples.length; j++) {
const { row: fr, column: fc } = peoples[i];
const { row: sr, column: sc } = peoples[j];
const value = compute(fr, fc, sr, sc);
if (
(value === 2 && hasWiban(fr, fc, sr, sc, daegisil)) ||
value === 1
) {
isPerfect = false;
break;
}
}
// 더 조사할 필요가 없으므로.
if (!isPerfect) break;
}
answer.push(isPerfect ? 1 : 0);
});
return answer;
}
if(value === 2){
if(hasWiban---){
같은 로직
}
}
if(value === 1){
같은 로직
}
을 밑으로 압축하였다.
if (
(value === 2 && hasWiban(fr, fc, sr, sc, daegisil)) ||
value === 1
) {
isPerfect = false;
break;
}
hasWiban
함수를 추가하였다.function hasWiban(fr, fc, sr, sc, daegisil) {
let result = false;
if (fr === sr) {
if (daegisil[fr][(fc + sc) / 2] === "O") {
result = true;
}
}
if (fc === sc) {
if (daegisil[(fr + sr) / 2][fc] === "O") {
result = true;
}
}
if (daegisil[sr][fc] === "O" || daegisil[fr][sc] === "O") {
result = true;
}
return result;
}
코드는 짧지만, 나에게 매우 강렬했던 문제.
const dict = [...new Array(26)].map((_, i) => String.fromCharCode(65 + i));
function getWC(string, current, next, dict) {
// 재귀 형태
if (next >= string.length)
// next가 문자열의 길이 이상이라면, 즉, c에 해당하는 문자가 없는 경우라면 바로 w인덱스를 넘긴다.
return [dict.indexOf(string.slice(current, next)) + 1, next - current - 1];
// 그게 아니라면 w와 c를 받는다.
const w = string.slice(current, next);
const c = string.slice(next, next + 1);
// w+c가 이미 존재한다면 더 길어질 수 있다.
// 존재하지 않는다면 최대 길이다.
const index = dict.indexOf(w + c);
if (index === -1) {
// 존재하지 않는다면 현재 입력과 일치하는 가장 긴 문자열 w이다.
dict.push(w + c);
return [dict.indexOf(w) + 1, next - current - 1];
} else {
// 존재한다면 현재 입력과 일치하는 가장 긴 문자열 w가 아니므로 재귀로 한번더.
return getWC(string, current, next + 1, dict);
}
}
function solution(msg) {
var answer = [];
for (let check = 0; check < msg.length; check++) {
// 출력할 색인과 문자가 얼마나 길어진 것인지를 나타내는 depth를 반환한다.
const [print, depth] = getWC(msg, check, check + 1, dict);
answer.push(print);
check += depth;
}
return answer;
}
dict
를 정적인 배열 말고 동적인 객체로 만들어보자. fromCharCode
메소드로 구현가능하다. fromCharCode
는 문자를 리턴하며, 인자로 숫자를 받는다.
문자열의 마지막 문자를 뽑아내는법
let last_char = str.charAt(str.length-1);
let last_char = str.substring(str.length-1, str.length);
let last_char = str.slice(str.length-1, str.length);
문자열의 마지막 문자를 제거하는 법
w = cur.slice(0, -1);