코딩테스트 정리 (1)

Yeonjoo Yoo·2022년 2월 7일
0

TIL

목록 보기
10/12
프로그래머스 코딩테스트를 풀면서 알게된 부분 정리
다른 사람 풀이를 참고하여 작성함

Array.prototype.find()

const solution = (p, c) => 
    p.find(
        name => !c[name]--,
        c.map(name => c[name] = (c[name]|0)+1)
    )

Array.prototype.sort()

  • 기본 정렬 방식 (arr.sort()) 은 UTF-16 문자열로 취급하여 오름차순 정렬
  • 내림차순 & 오름차순
// 내림차순
arr.sort((a, b) => a - b)
// 오름차순
arr.sort((a, b) => b - a)
function solution(array, commands) {
    return commands.map(c => {
        const [ s, e, idx ] = c
        const newArr = array.slice(s-1, e).sort((a,b) => Number(a)-Number(b))
        return newArr[idx-1]
    })
}
function solution(numbers) {
    var answer = numbers.map(v => v + '')
                        .sort((a, b) => (b+a)*1 - (a+b)*1)
                        .join('');

    return answer[0] === '0' ? '0' : answer;
}
function solution(genres, plays) {
    const genreDic = genres.reduce((p, c, i) => {
        p[c] = (p[c] | 0) + plays[i]
        return p
    }, {})
    
    const cntType = {}
    
    return genres
        .map((g, i) => {
            return { type: g, cnt: plays[i], idx: i}
        })
        .sort((a, b) => {
            if(a.type != b.type) return genreDic[b.type] - genreDic[a.type]
            if(a.cnt != b.cnt) return b.cnt - a.cnt
            return a.idx - b.idx
        })
        .filter(t => {
            if(cntType[t.type] == 2) return false
            cntType[t.type] = (cntType[t.type] | 0) + 1
            return true
            
        })
        .map(t => t.idx)
}

Array.prototype.reduce()

  • reduce((previousValue, currentValue, currentIndex, array) => { / ... / }, initialValue)
    • 초기값(initialValue) 없으면 배열의 첫번째 요소가 previousValue가 됨

Array.prototype.findIndex()

  • 조건에 맞는 첫번째 요소 값의 index를 반환
const array1 = [5, 12, 8, 130, 44];
array1.findIndex((element) => element > 13) // 3

Array.prototype.map()

  • map((element, index, array) => { / ... / })
  • 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환

Array.prototype.slice()

  • 배열의 begin부터 end(미포함)까지에 대한 얕은 복사본을 새 배열 반환
  • 원본은 변경되지 않음
  • arr.slice(start, end)
    • arr.slice()는 객체 복사 (얕은 복사)
    • 예를 들어, arr.slice(1,4) 는 index 1,2,3에 해당하는 요소 추출하여 새 배열 반환

Array.prototype.splice()

  • 배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경
  • array.splice(start, deleteCount, item1, item2..)
    • deleteCount (optional) 생략하면 start 부터 모든 요소 제거
    • items (optional) 추가할 요소. 생략하면 제거만 함

Object.values()

  • 객체의 value 들만 뽑아서 배열로 반환
const obj = { foo: 'bar', baz: 42 };
console.log(Object.values(obj)); // ['bar', 42]
const solution = (clothes) => {
  const cntPerCloth = Object.values(
    clothes.reduce((obj, t) => {
      obj[t[1]] = (obj[t[1]] | 0) + 1;
      return obj;
    } , {})
  )
  const ways = cntPerCloth.reduce((p, c) => p*(c+1), 1)
  return ways - 1;
}
  • (n(옷 개수) + 1(착용하지 않는 경우)) * c(누적 계산)) - 1(모두 착용하지 않는 경우)

Queue

function solution(bridge_length, weight, truck_weights) {
    let sec = 0
    const qu = [{position: 0, weight: 0}]
    let weightOnBridge = 0
    
    while(true) {
        if(truck_weights.length === 0) {
            sec += bridge_length
            break;
        }
        
        if(qu[0].position === sec) {
            const truck = qu.shift()
            weightOnBridge -= truck.weight
        }
        
        if(weightOnBridge + truck_weights[0] <= weight) {
            const newTruckWeight = truck_weights.shift()
            weightOnBridge += newTruckWeight
            qu.push({ position: bridge_length + sec, weight: newTruckWeight })
        } else {
          	// 다음 트럭이 못 올라오는 상황이면 얼른 큐의
         	// 첫번째 트럭이 빠지도록 그 시간으로 점프한다.
         	// * 참고: if 밖에서 1 더하기 때문에 -1 해줌
          	if (qu[0]) sec = qu[0].position - 1;
        }
        
        sec++
    }
    
    return sec
}

스택 (Stack)

  • LIFO(Last In First Out)
  • 데이터를 집어넣는 push, 데이터를 추출하는 pop
  • 맨 나중에 집어넣은 데이터를 확인하는 peek

Number.prototype.toString()

  • 인자로 radix 를 받음 (optional)
(4).toString(2); // '100'
profile
to be frontend engineer

0개의 댓글