티스토리 뷰
Jim's Burgers has a line of hungry customers. Orders vary in the time it takes to prepare them. Determine the order the customers receive their orders. Start by numbering each of the customers from 1 to n, front of the line to the back. You will then be given an order number and a preparation time for each customer.
The time of delivery is calculated as the sum of the order number and the preparation time. If two orders are delivered at the same time, assume they are delivered in ascending customer number order.
풀이
function jimOrders(orders) {
let result = []
for(let i = 0; i < orders.length; i++){
orders[i][2] = orders[i][0] + orders[i][1];
orders[i][3] = i + 1;
}
orders.sort(function(a, b) {
if(a[2] == b[2]) { return a[3] - b[3] }
return a[2] - b[2]
}).forEach(function(value) {
return result.push(value[3]);
});
return result.join(" ");
}
1. for문을 돌면서 order[i]와 prep[i]를 합한 값을 배열의 3번째 값으로 추가해줌
2. 인덱스에 1을 더한 값, 즉 주문 순서를 배열의 4번째 값으로 넣어줌
3. 3번째 값을 기준으로 배열을 정렬함. 이 때, 3번째 값이 같으면 4번째 값으로 비교함
4. 4번째 값만 결과 배열에 넣어줌.
5. join()을 이용해 결과값을 공백으로 합쳐줌.
다른 사람의 풀이
function jimOrders(orders) {
return orders.map((x, idx) => [idx + 1, x[0] + x[1]])
.sort((x, y) => x[1] - y[1])
.map(x => x[0]);
}
map()을 이용해서 배열을 주문 순서와 합친 값으로 새롭게 만들어줌!
바로 이어서 sort()로 정렬해주고, 다시 map()으로 주문 순서가 있는 배열 값만 꺼내줌.
오늘의 교훈 : map()을 잘 활용하자..! (근데 어디서 본건데 의외로 맵보다 for문 성능이 빠르다고함)
'1Day 1Algorithm' 카테고리의 다른 글
[DAY 13] Equal Stacks @ (0) | 2019.10.13 |
---|---|
[DAY 12] Time Conversion (0) | 2019.10.13 |
[DAY 10] Balanced Brackets @ (0) | 2019.10.10 |
[DAY 9] Max Min (0) | 2019.10.09 |
[DAY 8] Greedy Florist (0) | 2019.10.08 |
- Total
- Today
- Yesterday
- 배치처리시스템
- Props
- sort
- 운영체제
- Array
- Algorithm
- 타입스크립트
- 컴퓨터공학
- 구간합
- redux-saga
- 리액트
- 자료구조
- 프로그래머스
- 시분할시스템
- reduce()
- 우아한테크러닝
- 웹팩
- greedyAlgorithm
- React
- Webpack
- javascript
- 멀티프로그래밍
- 1day1algorithm
- 자바스크립트
- Typescript
- 배열
- 알고리즘
- js
- OS
- sort()
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |