Rectangle into Squares ( 6 kyu )
문제
The drawing below gives an idea of how to cut a given “true” rectangle into squares (“true” rectangle meaning that the two dimensions are different).
alternative text
Can you translate this drawing into an algorithm?
You will be given two dimensions
a positive integer length (parameter named lng)
a positive integer width (parameter named wdth)
You will return an array with the size of each of the squares.
Shell bash returns a string.
sqInRect(5, 3) should return [3, 2, 1, 1]
sqInRect(3, 5) should return [3, 2, 1, 1]
너비와 높이가 주어지면 안에 들어갈 수 있는 정사각형의 변의 길이를 배열로 담아 리턴
풀이
function sqInRect(lng, wdth){
if ( lng === wdth ) return null;
let result = [];
while ( lng > 0 && wdth > 0 ) {
if ( lng > wdth ) {
result.push(wdth);
lng = lng - wdth;
} else {
result.push(lng);
wdth = wdth - lng
}
}
return result;
}
lng, wdth중 큰 값에서 작은값을 빼면서 결과에 추가하는 방법으로 반복
다른 사람의 풀이
function sqInRect(lng, wdth){
let arr = []
if(lng === wdth) return null
while(lng > 0 && wdth > 0){
arr.push(lng > wdth ? wdth : lng)
lng > wdth ? lng -= wdth : wdth -= lng
}
return arr
}
똑같이 풀었는데 삼항 연산자를 잘 사용한 풀이