ํ๋ก๊ทธ๋๋จธ์ค ์๊ณ ๋ฆฌ์ฆ ํ์ด
https://school.programmers.co.kr/learn/courses/30/lessons/120844
์ฌ์ฉ ์ธ์ด : ์๋ฐ์คํฌ๋ฆฝํธ JavaScript JS
1. ๋ฐฐ์ด ํ์ ์ํค๊ธฐ
1) ๋ฌธ์ ์ค๋ช
์ ์๊ฐ ๋ด๊ธด ๋ฐฐ์ด numbers์ ๋ฌธ์์ด direction๊ฐ ๋งค๊ฐ๋ณ์๋ก ์ฃผ์ด์ง๋๋ค. ๋ฐฐ์ด numbers์ ์์๋ฅผ direction๋ฐฉํฅ์ผ๋ก ํ ์นธ์ฉ ํ์ ์ํจ ๋ฐฐ์ด์ returnํ๋๋ก solution ํจ์๋ฅผ ์์ฑํด์ฃผ์ธ์.
2) ์ ํ ์ฌํญ
- 3 ≤ numbers์ ๊ธธ์ด ≤ 20
- direction์ "left" ์ "right" ๋ ์ค ํ๋์ ๋๋ค.
3) ์ ์ถ๋ ฅ ์
numbers | direction | result |
[1, 2, 3] | "right" | [3, 1, 2] |
[4, 455, 6, 4, -1, 45, 6] | "left" | [455, 6, 4, -1, 45, 6, 4] |
2. ์ฌ์ฉ ๋ฉ์๋ - shift(), unshift(), push(), pop()
Array.prototype.shift()
shift() ๋ฉ์๋๋ ๋ฐฐ์ด์์ ์ฒซ ๋ฒ์งธ ์์๋ฅผ ์ ๊ฑฐํ๊ณ , ์ ๊ฑฐ๋ ์์๋ฅผ ๋ฐํํ๋ค. ์ด ๋ฉ์๋๋ ๋ฐฐ์ด์ ๊ธธ์ด๋ฅผ ๋ณํ๊ฒ ํ๋ค.
const array1 = [1, 2, 3];
const firstElement = array1.shift();
console.log(array1); // [2, 3]
console.log(firstElement); // 1
Array.prototype.unshift()
unshift() ๋ฉ์๋๋ ์๋ก์ด ์์๋ฅผ ๋ฐฐ์ด์ ๋งจ ์์ชฝ์ ์ถ๊ฐํ๊ณ , ์๋ก์ด ๊ธธ์ด๋ฅผ ๋ฐํํ๋ค.
const array1 = [1, 2, 3];
console.log(array1.unshift(4, 5)); // 5
console.log(array1); // [4, 5, 1, 2, 3]
Array.prototype.push()
push() ๋ฉ์๋๋ ๋ฐฐ์ด์ ๋์ ํ๋ ์ด์์ ์์๋ฅผ ์ถ๊ฐํ๊ณ , ๋ฐฐ์ด์ ์๋ก์ด ๊ธธ์ด๋ฅผ ๋ฐํํ๋ค.
const animals = ['pigs', 'goats', 'sheep'];
const count = animals.push('cows');
console.log(count); // 4
console.log(animals); // ["pigs", "goats", "sheep", "cows"]
animals.push('chickens', 'cats', 'dogs');
console.log(animals); // ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]
Array.prototype.pop()
pop() ๋ฉ์๋๋ ๋ฐฐ์ด์์ ๋ง์ง๋ง ์์๋ฅผ ์ ๊ฑฐํ๊ณ ๊ทธ ์์๋ฅผ ๋ฐํํ๋ค.
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
console.log(plants.pop()); // "tomato"
console.log(plants); // ["broccoli", "cauliflower", "cabbage", "kale"]
3. ๋ต์
1) ๋์ ํ์ด
function solution(numbers, direction) {
if (direction === "right") {
numbers.unshift(numbers.pop())
} else {
numbers.shift(numbers.push(numbers[0]))
}
return numbers;
}
๋ฉ์๋๊ฐ ์ ๋ง ์์ธ์์ ธ์ ๋ฉฐ์น ์ ๋ถ๋ค๊ณ ์์๋ ๋ฌธ์ ์ธ๋ฐ, ์์ ๋ฐํฌ(deque) ์ด๋ฏธ์ง๋ฅผ ๋ณด๊ณ ๊ธ๋ฐฉ ์ธ์ธ ์ ์์๋ค.
๋ผ๊ณ ์๊ฐํ์์ผ๋ numbers.shift(numbers.push(numbers[0])) ์ ๋ญ๊น..๐ ์๋์ฒ๋ผ ์์ ํ๋ฉด ๋ ๊น๋ํ๊ณ ์ฌ๋ฐ๋ฅธ ๋ต์์ด ๋๋ค.
2) ๋ค๋ฅธ ์ฌ๋์ ํ์ด
function solution(numbers, direction) {
if (direction === "right") {
numbers.unshift(numbers.pop())
} else {
// ์ด๋ ๊ฒ ํ๋ฉด ๊น๋..!
// numbers.shift()๊ฐ ์ด์ฐจํผ ๋ฐฐ์ด์ ๋งจ ์ฒ์ ์์๋ฅผ ๊ฐ์ ธ์ด
numbers.push(numbers.shift())
}
return numbers;
}
'๐ป Programming > Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ํ๋ก๊ทธ๋๋จธ์ค Lv. 0] 369๊ฒ์ (0) | 2023.08.02 |
---|---|
[ํ๋ก๊ทธ๋๋จธ์ค Lv. 1] ์ฝ๋ผ์ธ ์ถ์ธก (0) | 2023.08.02 |
[ํ๋ก๊ทธ๋๋จธ์ค Lv. 0] ๊ฐ๊น์ด 1 ์ฐพ๊ธฐ (0) | 2023.07.28 |
[ํ๋ก๊ทธ๋๋จธ์ค Lv. 0] ํน๋ณํ ์ด์ฐจ์ ๋ฐฐ์ด 2 (0) | 2023.07.28 |
[ํ๋ก๊ทธ๋๋จธ์ค Lv. 0] ์ธ๋ฑ์ค ๋ฐ๊พธ๊ธฐ (0) | 2023.06.25 |