[TIL] 2019-10-15

undefcat·2019년 10월 14일
0

TIL

목록 보기
27/228

알고리즘

종만북

  • 9.2 - 여행 짐 싸기

Coding Math

  • 그동안 잠시 쉬었던(?) Coding Math 시리즈를 퇴근하고 집에 와서 하기로 마음먹었다. 일단 할 수 있는 강의까지 다시 달려보자. 우선 지금까지 배웠던 내용 중 가장 중요한 Vector 클래스를 구현해보자.
export default class Vector {
  private _x: number
  private _y: number
  
  constructor(x: number, y: number) {
    this._x = x
    this._y = y
  }
  
  get x(): number {
    return this._x
  }
  
  get y(): number {
    return this._y
  }
  
  get length(): number {
    // 피타고라스 정리에 의해
    return Math.sqrt(this.y*this.y + this.x+this.x)
  }
  
  set length(l: number) {
    // angle은 radian
    const angle = this.angle
    
    // 삼각함수에 의해
    this._x = l*Math.cos(angle)
    this._y = l*Math.sin(angle)
  }
  
  get angle(): number {
    return Math.atan2(this.y, this.x)
  }
  
  set angle(r: number) {
    const length = this.length
    
    this._x = length*Math.cos(r)
    this._y = length*Math.sin(r)
  }
}
  • 벡터의 경우 (x, y)에 의해 길이와 각도가 모두 결정된다. 원을 좌표평면에 그리고 원의 반지름을 r이라고 할 때, x, y의 좌표는 각각 r*cos(theta) r*sin(theta)로 표현된다. 이 때 r이 바로 길이가 되는 것이다.
  • 길이와 각도를 바꿀 때에는 바뀐 길이값, 바뀐 각도값을 변하지 않은 각도, 길이값을 이용하여 새롭게 x, y좌표를 할당만 해주면 된다.
  • 내일 다시 11장부터 시작하자!
profile
undefined cat

0개의 댓글