πŸ“
til
  • TIL(Today I Learned)
  • javascript
    • value-number-string-boolean-null-undefined
    • primitive-reference
    • Hoisting
    • Prototypes in Javascript
    • this
    • prototype
    • μ½œλ°±ν•¨μˆ˜ (Callback function)
    • ν•¨μˆ˜μ˜ 호좜
    • 자료ꡬ쑰 new keyword
    • closure
    • Promise
    • event-loop
    • array-object
    • 객체
    • Arguments
    • higher order function
    • operators-function-control-flow
    • 객체 생성 νŒ¨ν„΄ 3κ°€μ§€
    • Javascript scopes
    • Functional Programming
    • Design Patterns
    • 데이터 νƒ€μž…
    • Object 객체
    • ν‘œμ€€ λ‚΄μž₯ 객체의 ν™•μž₯
    • μ°Έμ‘°
    • ν•¨μˆ˜
    • 상속(Inheritance)
    • this - 'this'λ₯Ό μ‚¬μš©ν•˜λŠ” ν•΄λ‹Ή ν•¨μˆ˜λ₯Ό 'μ–΄λ–»κ²Œ' μ‹€ν–‰ν•˜λŠλƒμ— λ”°λ₯Έ 4κ°€μ§€ this μ •μ˜
    • 전역객체(Global object)
    • 객체 μ§€ν–₯ ν”„λ‘œκ·Έλž˜λ°
    • The 'new' keyword - Object Creation in JavaScript
  • javascript-api
    • Number
      • Number.MAX_VALUE
      • Number.isInteger
      • Number.NEGATIVE_INFINITY
      • Number.isNaN()
      • Number.POSITIVE_INFINITY
      • Number.parseFloat
      • Number.EPSILON
      • number.toExponential
      • Number.MAX_SAFE_INTEGER
      • Number1 - μžμ—°μˆ˜, μ •μˆ˜, 10μ§„μˆ˜, 2μ§„μˆ˜, λΆ€λ™μ†Œμˆ˜μ , μ‹€μˆ˜
      • Number.isSafeInteger()
      • Number.MIN_VALUE
      • Number.parseInt
      • Number.NaN
      • Number.isFinite()
      • Number.MIN_SAFE_INTEGER
      • toFixed
    • string.split
    • String.fromCodePoint
    • string.trimEnd
    • string.padStart
    • string.@@iterator
    • String.fromCharCode
    • string.toUpperCase
    • string.codePointAt
    • string.toLowerCase()
    • string.toString
    • string.includes
    • string.replace()
    • string.charAt
    • String.lastIndexOf
    • string.slice
    • string.search
    • string.padEnd
    • string.substring
    • string.length
    • string.trim
    • string.localeCompare
    • String.indexOf
    • string.endsWith
    • string.valueOf
    • String.raw
    • string.matchAll()
    • string.repeat
    • string.match
    • String.prototype
    • string.startsWith
    • string.charCodeAt
    • string.trimStart
    • string.concat
    • string.toLocaleUpperCase()
    • string.toLocaleLowerCase
    • String
  • learn-node
    • debugger
    • Tip
  • schema-design
    • Database Schema Design
    • Database Schema Design
  • react
    • LifeCycle
    • redux
    • Context API
    • ν•¨μˆ˜ν˜• μ»΄ν¬λ„ŒνŠΈμ™€ 클래슀, μ–΄λ–€ 차이가 μ‘΄μž¬ν• κΉŒ?
    • Hooksκ³Ό useEffect μ‚¬μš©ν•΄ 보기
    • Route
    • async wait μ‚¬μš©ν•˜κΈ°
    • Hooks API Reference
    • context
    • npm uninstall ν•˜λŠ”λ²•
    • test λ§Œλ“€κΈ°
  • tip
    • ν΄λ¦°μ½”λ“œ
    • BxSlider둜 ν…μŠ€νŠΈ 흐λ₯΄λŠ” 효과 λ§Œλ“€κΈ°
  • javascript30
    • Event Capture, Propagation, Bubbling and Once
    • Object and Arrays - Reference VS Copy
  • typescript
    • μš°μ•„ν•œ νƒ€μž…μŠ€ν¬λ¦½νŠΈ 2λΆ€
    • The Basic Cheatsheet
    • TypeScript
    • Type Guards and Differnetiating Types
    • μš°μ•„ν•œ νƒ€μž…μŠ€ν¬λ¦½νŠΈ
    • Generics
  • git-from-the-hell
    • git
    • init-status-add-commit-log-stage-repository
    • log-diff
    • λ¨Έμ§€ ν›„ branch μ‚­μ œν•˜κΈ°
    • μ§€μ˜₯μ—μ„œ 온 Git
    • reset-revert
    • develop branch λ₯Ό pull ν•˜κ³  μ‹Άμ„λ•Œ
  • conference-and-seminar
    • λͺ¨λ˜ ν”„λ‘ νŠΈμ—”λ“œ κ°œλ°œν™˜κ²½μ˜ 이해
  • fire-base
    • Firebase .gitignore
  • vanillacoding
    • Data Structures
    • Sorting Algorithms - part 1
    • Promise
    • class
    • 04.quiz
    • 07.event-loop
    • Design Patterns
    • OOP (Object Oriented Programming)
  • etc
    • μ•Œκ³ λ¦¬μ¦˜ μ½”λ“œλ¦¬λ·°
    • 슀슀둜 κ³΅λΆ€ν•˜λŠ” 법
    • 바닐라코딩 μˆ˜κ°• ν›„κΈ°
    • async 과제 ν›„κΈ° - 비동기, 동기, ν΄λ‘œμ €, λ°°μ—΄κ³Ό 객체
    • μœ μš©ν•œ μ‚¬μ΄νŠΈ
  • algorithm
    • The Supermarket Queue
    • Find the odd int
    • The Office III - Broken Photocopier
    • Directions Reduction
    • The Office II - Boredom Score
    • Divisible Sum Pairs
    • Codewars 이용자 μ†”λ£¨μ…˜ λͺ¨μŒ
    • Shortest Word
    • find key
    • Two Sum
    • Simple Pig Latin
  • Book
    • the essence of object-orientation
      • νƒ€μž…κ³Ό 좔상화
      • 객체 지도
      • μ΄μƒν•œ λ‚˜λΌμ˜ 객체
      • 좔상화 기법
      • 05. μ±…μž„κ³Ό λ©”μ‹œμ§€
      • 07.ν•¨κ»˜ λͺ¨μœΌκΈ°
      • 04. μ—­ν• , μ±…μž„, ν˜‘λ ₯
      • ν˜‘λ ₯ν•˜λŠ” κ°μ²΄λ“€μ˜ 곡동체
  • ecma-script2015
    • Object Literal Upgrades
    • default-parameter-template-literals-arrow-functions
    • spread-operator-rest-param
    • let-const-rest-parameter-spread-operator-destructuring
  • http
    • μ›Ή λΈŒλΌμš°μ €μ— URL을 μž…λ ₯ν–ˆμ„ λ•Œ μ–΄λ–»κ²Œ μ›Ή νŽ˜μ΄μ§€κ°€ λ³΄μ—¬μ§ˆκΉŒ?
  • jest
    • toThrow(error?)
  • data-structures
    • Data Structures
  • express
    • express generator
    • CORS
  • css-flexible-box-layout
    • flex 해버렸지 뭐야
  • git
    • Git
  • mongodb
    • MongoDB
  • markdown
    • use-markdown
  • cmder
    • cmd λͺ…λ Ήμ–΄ λͺ¨μŒ
  • debug
    • trackClicksEx function error
  • npm
    • NPM TOKEN μ„€μ •ν•˜κΈ°
  • storybook
    • Storybook
  • sort
    • Sorting Algorithms - part 1
  • javascript-koans
    • Javascript Koans μ˜€λ‹΅λ…ΈνŠΈ
  • rxjs
    • Rx.js
  • dom-elements
    • HTML Element
  • redux-toolkit
    • Redux Toolkit
  • github-actions
    • GitHub Actions
  • redux-middleware
    • redux middleware
  • rest
    • rest
  • css-rendering
    • μ½”λ“œ μŠ€ν”ΌμΈ  - CSS Rendering 1회차 2/2
    • μ½”λ“œ μŠ€ν”ΌμΈ  - CSS Rendering 1회차 1/2
  • you-dont-know-js
    • νƒ€μž…
  • server
    • # shutdown local server
  • semantic-versioning
    • Semantic Versioning 2.0.0
Powered by GitBook
On this page
  • 문제
  • 문제 이해
  • ν•΄κ²° 방법
  • μ½”λ“œ κ΅¬ν˜„
  • κ²°κ³Ό 뢄석

Was this helpful?

  1. algorithm

Directions Reduction

PreviousThe Office III - Broken PhotocopierNextThe Office II - Boredom Score

Last updated 5 years ago

Was this helpful?

문제

Once upon a time, on a way through the old wild west,…

… a man was given directions to go from one point to another. The directions were "NORTH", "SOUTH", "WEST", "EAST". Clearly "NORTH" and "SOUTH" are opposite, "WEST" and "EAST" too. Going to one direction and coming back the opposite direction is a needless effort. Since this is the wild west, with dreadfull weather and not much water, it's important to save yourself some energy, otherwise you might die of thirst!

How I crossed the desert the smart way.

The directions given to the man are, for example, the following:

["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]

You can immediatly see that going "NORTH" and then "SOUTH" is not reasonable, better stay to the same place! So the task is to give to the man a simplified version of the plan. A better plan in this case is simply:

["WEST"]

Other examples:

In["NORTH", "SOUTH", "EAST", "WEST"], the direction "NORTH" + "SOUTH" is going north and coming back right away. What a waste of time! Better to do nothing.

The path becomes ["EAST", "WEST"], now "EAST" and "WEST" annihilate each other, therefore, the final result is [] .

In ["NORTH", "EAST", "WEST", "SOUTH", "WEST", "WEST"], "NORTH" and "SOUTH" are not directly opposite but they become directly opposite after the reduction of "EAST" and "WEST" so the whole path is reducible to ["WEST", "WEST"].

Task

Write a function dirReduc which will take an array of strings and returns an array of strings with the needless directions removed (W<->E or S<->N side by side).

The Haskell version takes a list of directions with data Direction = North | East | West | South. The Clojure version returns nil when the path is reduced to nothing. The Rust version takes a slice of enum Direction {NORTH, SOUTH, EAST, WEST}.

Examples

dirReduc(["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]) => ["WEST"]
dirReduc(["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH"]) => []

Note

Not all paths can be made simpler. The path ["NORTH", "WEST", "SOUTH", "EAST"] is not reducible. "NORTH" and "WEST", "WEST" and "SOUTH", "SOUTH" and "EAST" are not directly opposite of each other and can't become such. Hence the result path is itself : ["NORTH", "WEST", "SOUTH", "EAST"].

문제 이해

문제 μ„€λͺ…이 맀우 μΉœμ ˆν•˜λ‹€.

배열을 μ­‰ ν›‘λŠ”λ° "WEST" <-> "EAST", NORTH<->SOUTHκ°€ 겹치면 두 μš”μ†Œλ₯Ό μ œκ±°ν•œλ‹€. 그리고 λ‹€μ‹œ μ²˜μŒλΆ€ν„° μ²΄ν¬ν•΄μ„œ μ œκ±°ν•˜κ³  λ‹€μ‹œ μ²˜μŒλΆ€ν„° μ²΄ν¬ν•΄μ„œ 또 μ œκ±°ν•œλ‹€.

그리고 μ΅œμ’… 남은 μš”μ†Œλ₯Ό return ν•œλ‹€.

ν•΄κ²° 방법

  1. λ™μ„œλ‚¨λΆμ„ 담은 배열을 λ§Œλ“ λ‹€.

  2. λ°°μ—΄ μš”μ†Œ ν•˜λ‚˜ν•˜λ‚˜μ— μ ‘κ·Όν•œλ‹€.

  3. λ°°μ—΄μš”μ†Œμ™€ λ™μ„œλ‚¨λΆμ„ 담은 λ°°μ—΄κ³Ό λ§€μΉ˜ν•΄ κ·Έ λ‹€μŒ μš”μ†Œλ‘œ 였면 μ•ˆλ˜λŠ”κ²Œ μžˆλŠ” μ§€ ν™•μΈν•œλ‹€.

  4. μžˆλ‹€λ©΄ ν˜„μž¬ μš”μ†Œμ™€ λ‹€μŒ μš”μ†Œλ₯Ό μ‚­μ œν•œλ‹€.

  5. λ‹€μ‹œ 2둜 λŒμ•„κ°„λ‹€.

  6. κ²ΉμΉ˜λŠ” μš”μ†Œκ°€ μ—†λ‹€λ©΄ return ν•œλ‹€.

μ½”λ“œ κ΅¬ν˜„

function dirReduc(arr) {
  const compass = ["NORTH", "SOUTH", "WEST", "EAST"];

  arr.map((dir, idx) => {
    let MatchIdx = compass.findIndex(ele => {
      return dir === ele;
    });

    let comIdx = MatchIdx % 2 ? MatchIdx - 1 : MatchIdx + 1;

    if (arr[idx + 1] === compass[comIdx]) {
      arr.splice(idx, 2);
      dirReduc(arr);
    };
  });

  return arr;
}

κ²°κ³Ό 뢄석

random ν…ŒμŠ€νŠΈ 톡과

function dirReduc(plan) {
  var opposite = {
    'NORTH': 'SOUTH',
    'EAST': 'WEST',
    'SOUTH': 'NORTH',
    'WEST': 'EAST'
  };
  return plan.reduce(function (dirs, dir) {
    if (dirs[dirs.length - 1] === opposite[dir])
      dirs.pop();
    else
      dirs.push(dir);
    return dirs;
  }, []);
}

λ³€μˆ˜λͺ…이 λ§ˆμŒμ— λ“ λ‹€. opposite else도 ν•œμ€„λ‘œ μ“Έ 수 μžˆκ΅¬λ‚˜.

opposite 객체둜 λ§Œλ“ κ²Œ 훨씬 κΉ”λ”ν•˜κ³  가독성이 μ’‹λ‹€.

pop()은 λ°°μ—΄μ—μ„œ λ§ˆμ§€λ§‰ μš”μ†Œλ₯Ό 제거 ν•œλ‹€.

λ‚΄ μ½”λ“œμ˜ 단점은

  1. ν™•μΈν•œ μš”μ†Œλ₯Ό λ‹€μ‹œ μ²˜μŒλΆ€ν„° 확인해야 ν•œλ‹€.

  2. μž¬κ·€ν•¨μˆ˜λ₯Ό μ΄μš©ν–ˆκΈ° λ•Œλ¬Έμ— μƒˆλ‘œμš΄ 배열에 담을 수 μ—†λ‹€.

λ₯Ό λ‹¨μ μœΌλ‘œ κ°€μ‘ŒλŠ”λ° 이 solution에선 μ΄λŸ¬ν•œ 점이 λ³΄μ•ˆλ˜μ–΄μžˆλ‹€.

배열을 κ²€μˆ˜ν•˜λŠ” 일을 reduceλ₯Ό μ‚¬μš©ν•΄ μƒˆλ‘œμš΄ 배열을 λ§Œλ“€μ—ˆλ‹€.

dirReduc(["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH"]) => []

λ§Œμ•½ μ΄λŸ°μ˜ˆμ‹œκ°€ μžˆλ‹€λ©΄,

  1. μ΄μ „μš”μ†Œκ°€ μ—†κΈ° λ•Œλ¬Έμ— 맨처음 dirsμ—λŠ” "NORTH"κ°€ λ‹΄κΈ΄λ‹€.

  2. dirs의 λ§ˆμ§€λ§‰ μš”μ†Œμ™€ λ°°μ—΄μ˜ ν˜„μž¬μš”μ†Œμ™€ 비ꡐ

    1. "NORTH" === opposite["SOUTH"] λŠ” κ°™λ‹€

    2. dirsμ—μ„œ "NORTH"λŠ” 제거 λœλ‹€.

  3. μ΄μ „μš”μ†Œκ°€ μ—†κΈ° λ•Œλ¬Έμ— "SOUTH"κ°€ λ‹΄κΈ΄λ‹€.

  4. "SOUTH" === opposite["EAST"] λŠ” κ°™μ§€ μ•ŠκΈ° λ•Œλ¬Έμ— "EAST"λŠ” dirs에 λ‹΄κΈ΄λ‹€.

  5. "EAST" === opposite["WEST"] 와 κ°™κΈ° λ•Œλ¬Έμ— dirsμ—μ„œ "EAST"λŠ” 제거 λœλ‹€.

  6. dirsλ°°μ—΄μ—” "SOUTH"만 λ‚¨λŠ”λ‹€.

  7. "SOUTH" === opposite["NORTH"] κ°™κΈ° λ•Œλ¬Έμ— "SOUTH" 제거 λœλ‹€.

  8. 빈 λ°°μ—΄λ§Œ return ν•œλ‹€.

λ‚΄κ°€ μ§  μ½”λ“œλŠ” ν˜„μž¬μš”μ†Œμ™€ λ‹€μŒμš”μ†Œλ§Œμ„ λΉ„κ΅ν•˜μ—¬ μ œκ±°ν–ˆκΈ° λ•Œλ¬Έμ— κ²€μˆ˜κ°€ μ™„λ²½ν•˜λ‹€κ³  ν•  수 μ—†λ‹€. μ΄μ „μš”μ†Œκ°€ μƒˆλ‘œμš΄ ν™˜κ²½μ΄ 될 수 μžˆλŠ” κ°€λŠ₯성에 μ²˜μŒλΆ€ν„° λ‹€μ‹œ 배열을 κ²€μˆ˜ ν–ˆλ‹€.

ν•˜μ§€λ§Œ 이 μ½”λ“œλŠ” μ΄μ „μš”μ†Œμ™€ ν˜„μž¬ μš”μ†Œλ₯Ό λΉ„κ΅ν•˜μ—¬ μ΄μ „μš”μ†Œλ₯Ό μ‚­μ œν•˜κΈ° λ•Œλ¬Έμ— μ΄μ „μš”μ†Œκ°€ μƒˆλ‘œμš΄ ν™˜κ²½μ— λ”°λ₯Έ 상황에 훨씬 λŒ€μ‘ν•˜κΈ° νŽΈν•œ μ½”λ“œμ΄λ‹€.

, , , , , 's Solution

Codewars Link
Unnamed
Meow
Quantumke
JeffP6
jmcilhargey
Dimzdey
js파일보기