31주차 알고리즘

이동규·2024년 10월 29일

코테

목록 보기
22/22

행렬의 곱셈

function solution(
  arr1 = [
    [1, 4],
    [3, 2],
    [4, 1],
  ],
  arr2 = [
    [3, 3],
    [3, 3],
  ]
) {
  const newArr = []; // 새로운 array

  for (let i = 0; i < arr1.length; i++) {
    // 3
    let result = [];
    for (let j = 0; j < arr2[0].length; j++) {
      //2
      let elem = 0;
      for (let k = 0; k < arr2.length; k++) {
        // 2
        elem += arr1[i][k] * arr2[k][j];
      }
      result.push(elem);
    }
    newArr.push(result);
  }
  return newArr;
}

H-index

function solution(citations = [3, 3, 3, 4]) {
  let answer = 0;
  citations.sort((a, b) => a - b);
  for (let index = 0; index < citations[citations.length - 1]; index++) {
    const newArr = citations.filter((e) => e >= index);
    if (newArr.length >= index) {
      answer = index;
    }
  }

  return answer;
}

[1차] 캐시

function solution(
  cacheSize = 3,
  cities = [
    'Jeju',
    'Pangyo',
    'Seoul',
    'NewYork',
    'LA',
    'Jeju',
    'Pangyo',
    'Seoul',
    'NewYork',
    'LA',
  ]
) {
  let answer = 0;
  let cache = [];

  cities.forEach((element) => {
    const converted = element.toLowerCase();
    if (cache.includes(converted)) {
      answer += 1;
      cache = cache.filter((value) => value !== converted);
    } else {
      answer += 5;
    }

    if (cacheSize !== 0 && cache.length === cacheSize) {
      cache.shift();
    }
    if (cacheSize !== 0) {
      cache.push(converted);
    }
  });
  return answer;
}

0개의 댓글