본문 바로가기

algorithm/codewars

[6kyu] crashing boxes

문제설명

Description:

You are stacking some boxes containing gold weights on top of each other. If a box contains more weight than the box below it, it will crash downwards and combine their weights. e.g. If we stack [2] on top of [1], it will crash downwards and become a single box of weight [3]

[2]
[1] --> [3]

Given an array of arrays, return the bottom row (i.e. the last array) after all crashings are complete.

crashing_weights([[1, 2, 3],  --> [[1, 2,  ],      [[1,  ,  ]],
                  [2, 3, 1],  -->  [2, 3, 4],  -->  [2, 2,  ],
                  [3, 1, 2]])      [3, 1, 2]]  -->  [3, 4, 6]]

therefore return [3, 4, 6]

More details

boxes can be stacked to any height, and the crashing effect can snowball:

[3]
[2]     [5]
[4] --> [4] --> [9]

Crashing should always start from as high up as possible -- this can alter the outcome! e.g.

[3]                      [3]
[2]     [5]              [2]     [3]
[1] --> [1] --> [6], not [1] --> [3]

Weights will always be integers. The matrix (array of arrays) may have any height or width > 1, and may not be square, but it will always be "nice" (all rows will have the same number of columns, etc).





나의 풀이

function crashingWeights(grid){ for(var i = 0; i < grid.length-1; i+=1){ for(var j = 0; j < grid[i].length; j+=1){ if(grid[i][j] > grid[i+1][j]){ grid[i+1][j] = grid[i][j] + grid[i+1][j]; } } } return grid[grid.length-1]; };




다른사람의 풀이

function crashingWeights(grid) { return grid.reduce((s, v) => v.map((x, i) => s[i] > x ? s[i] + x : x), []) }




느낀점

reduce 메서드의 초기값을 빈배열 []로 처리한 것이 비교에 있어서 주요한 역할을 했다. 나는 딱 눈에 보이는대로 풀었다. 


'algorithm > codewars' 카테고리의 다른 글

[6kyu] Simple string expansion  (0) 2018.02.07
[7kyu] Homogenous array  (0) 2018.02.04
[6kyu] playing with digits  (0) 2018.01.28
[6kyu] multiples of 3 or 5  (0) 2018.01.28
[6kyu] TGI Friday !!  (0) 2018.01.22