CodeWars 코딩 문제 2021/04/22 - Don't Drink the Water

이호현·2021년 4월 22일
0

Algorithm

목록 보기
108/138

[문제]

Don't Drink the Water

Given a two-dimensional array representation of a glass of mixed liquids, sort the array such that the liquids appear in the glass based on their density. (Lower density floats to the top) The width of the glass will not change from top to bottom.

======================

The glass representation may be larger or smaller. If a liquid doesn't fill a row, it floats to the top and to the left.

(요약) 밀도가 낮은걸 앞으로 보내고, 높으면 뒤로 보내라.

[풀이]

function separateLiquids(glass) {
  if(!glass.length) return [];

  const answer = [];
  const rows = glass.length;
  const columns = glass[0].length;
  const obj = {O: 0, A: 1, W: 2, H: 3};
  const obj2 = {0: 'O', 1: 'A', 2: 'W', 3: 'H'};
  const flatArr = [];

  for(let i = 0; i < rows; i++) {
    for(let j = 0; j < columns; j++) {
      flatArr.push(glass[i][j]);
    }
  }

  flatArr.map(char => obj[char])
    .sort()
    .map(n => obj2[n])
    .forEach((char, idx) => {
      if(!(idx % columns)) {
        answer.push([char]);
      }
      else {
        answer[Math.floor(idx / columns)].push(char);
      }
    })

  return answer;
}

flat을 이용해 1차원 배열로 만들려고 했는데 flat 메소드가 사용이 안되서 문자를 하나씩 뽑아 flatArr에 저장.

그릭고 obj, obj2로 각 액체별 밀도의 순서를 매기고, map을 돌면서 변환 > 정렬 > 변환을 함.

마지막에 다시 2차원 배열로 바꾸고 return.

function separateLiquids(glass) {
  if(!glass.length) return [];

  const answer = [];
  const rows = glass.length;
  const columns = glass[0].length;
  const obj = {O: 0, A: 1, W: 2, H: 3};
  const flatArr = [];

  for(let i = 0; i < rows; i++) {
    flatArr.push(...glass[i])
  }

  flatArr.sort((a, b) => {
      return obj[a] - obj[b];
    })
    .forEach((char, idx) => {
      if(!(idx % columns)) {
        answer.push([char]);
      }
      else {
        answer[Math.floor(idx / columns)].push(char);
      }
    })

  return answer;
}

조금 리팩토링 해봄

profile
평생 개발자로 살고싶습니다

0개의 댓글