Some people are standing in a row in a park. There are trees between them which cannot be moved. Your task is to rearrange the people by their heights in a non-descending order without moving the trees. People can be very tall!
For a = [-1, 150, 190, 170, -1, -1, 160, 180], the output should be
sortByHeight(a) = [-1, 150, 160, 170, -1, -1, 180, 190].
function sortByHeight(a) {
if(a.every((el) => {return el === -1})){return a}
let peopleOnly = [];
peopleOnly = a.filter((el) => {
return el !== -1
})
const sorted = peopleOnly.sort((a,b) => {return a - b});
for(i = 0; i < sorted.length; i++) {
if(a[i] === -1) {
sorted.splice(i,0,-1)
}
}
return sorted;
}
Hidden Test 한 문항을 통과하지 못했다.. 어떤 것 때문일까?
function sortByHeight(a) {
let aFiltered = a.filter(x => {
if(x !== -1 ){
return x;
}
}).sort((a,b) => a-b);
for(let i = 0; i < a.length; i++) {
if(a[i] != -1) {
a[i] = aFiltered.shift();
console.log(a[i],aFiltered)
}
}
return a;
}
//https://gist.github.com/RahmatSaeedi/be4d23110624e526e95958c8067cb9d6
function sortByHeight(a) {
if(a.every((el) => {return el === -1})){return a}
let peopleOnly = [];
peopleOnly = a.filter((el) => {
return el !== -1
}).sort((a,b) => {return a - b});
//굳이 필요없는 sorted 변수 지정 대신 peopleOnly 변수 하나에 정렬했다.
for(i = 0; i < a.length; i++) {
if(a[i] !== -1) {
a[i] = peopleOnly.shift();
//바로 peopleOnly 사용
//peopleOnly 요소를 순서대로 a배열 요소중 -1이 아닌 요소 대신 넣는다.
}
}
return a;
}