JS알고리즘 배열탐색 풀이2

dowon kim·2023년 9월 19일

나의풀이

function solution(n,arr1) {
  //arr1을 구조분해할당 하여 정렬한 arr2를 생성
  //arr1의 요소가 arr2의 몇번째 인덱스+1에 존재하는지에대한 배열을 리턴한다.
  let arr2 = [...arr1].sort((a, b) => b - a);
  return arr1.map((a) => arr2.indexOf(a) + 1);
}

나의풀이

function solution(n,arr1) {
  //행의합 : 0.0 0.1 0.2 0.3 ... 0.n
  //열의합 : 0.0 1.0 2.0 3.0 ... n.0
  //왼쪽대각선 : 0.0 1.1 2.2 3.3 ... n.n
  //오른쪽 대각선 : n.0 n-1.1 n-2.2 ... 0.n
  let arr = [0,0,0,0];//값을 누적해서 더해야 하기 때문에 0으로 인덱스값들 초기화
  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < n; j++) {
      switch (i){
        case 0:arr[i]+=arr1[0][j];
          break;
        case 1:arr[i]+=arr1[j][0];
          break;
        case 2:arr[i]+=arr1[j][j];
          break;
        case 3:arr[i]+=arr1[n-1-j][j];
          break;
      }
    }
  }
  return Math.max(...arr)
}

bestsolution

function solution(n, arr1) {
    let sums = [0, 0, 0, 0]; // 각 합을 저장할 배열

    // 행의 합
    for (let j = 0; j < n; j++) {
        sums[0] += arr1[0][j];
    }

    // 열의 합
    for (let i = 0; i < n; i++) {
        sums[1] += arr1[i][0];
    }

    // 대각선의 합 (왼쪽, 오른쪽 대각선)
    for (let i = 0; i < n; i++) {
        sums[2] += arr1[i][i];          // 왼쪽 대각선
        sums[3] += arr1[n-1-i][i];      // 오른쪽 대각선
    }

    return Math.max(...sums);
}

나의답변

function check(x, y, arr1, n) {
  let arr = [];
  if (x - 1 >= 0) arr.push(arr1[x - 1][y]);
  if (y - 1 >= 0) arr.push(arr1[x][y - 1]);
  if (x + 1 < n) arr.push(arr1[x + 1][y]);
  if (y + 1 < n) arr.push(arr1[x][y + 1]);

  return arr1[x][y] > Math.max(...arr) ? 1 : 0;
}

function solution(n, arr1) {
  //상하좌우 체크시 자신이 가장 큰값일때 cnt ++
  //상하좌우가 존재하는지 and 상하좌우값을 체크하는 메서드 생성
  //전체조회
  let cnt = 0;
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < n; j++) {
      cnt += check(i, j, arr1, n);
    }
  }
  return cnt;
}
profile
The pain is so persistent that it is like a snail, and the joy is so short that it is like a rabbit's tail running through the fields of autumn

0개의 댓글