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; }
조금 리팩토링 해봄