Algorithm(중)

Jeong Yeongmin·2022년 9월 26일
0

Algorithm

목록 보기
6/9

function solution(n) {
  let arr = [];
  let remainder,quotient=0,dividend=n;

  while (dividend > 0){
    arr.push(dividend % 3);
    dividend = Math.trunc(dividend/3);  
  }
  arr.reverse();
  let temp =  0;
  for (let i=0; i<arr.length; i++){
     temp = temp + arr[i]*Math.pow(3,i);
  }
  return temp;
}

// alternative
function solution(n){
  return parseInt([...n.toString(3)]
  .reverse().join(""),3);
}

feedback: For number objects, toString(radix : in the range 2 through 36)을 사용하면 returns a string representation of the object in the specified radix. parseInt(string_value, radix) method parses a string and returns its value as an integer number(evaluating the string_value based on the mathematical numeral system specified by the optional radix parameter). toString과 parseInt method에 대해 더 구체적으로 알 수 있었던 문제.

function solution(sizes){
  const [max_x,max_y] = sizes.reduce(([h1,v1],[a,b]) => [Math.max(h1,Math.max(a,b)), Math.max(v1,Math.min(a,b))], [0,0]);
  return max_x*max_y;
}

feedback: 처음에 for loop 사용해서 썼다가 가독성이 안 좋아서 한 줄로 변경.

function solution(numbers) {
  var answer = [];
  for (let i=0; i<numbers.length; i++){
    for (let j=i+1; j<numbers.length; j++){
      if(!answer.includes(numbers[i]+numbers[j])){
        answer.push(numbers[i]+numbers[j]);
    }
  }
}

  answer.sort((a,b) => a-b);
  return answer;
}

// alternative
function solution(numbers) {
  var answer = [];
  var temp = [];
  for (let i=0; i<numbers.length; i++){
    for (let j=i+1; j<numbers.length; j++){
        temp.push(numbers[i]+numbers[j]);
    }
  }

  answer = [...new Set(temp)]
  return answer.sort((a,b)=>a-b);
}

feedback: Set()을 이용한 방법도 있었다. Set 객체는 ES6에서 등장한 중복을 제거한 값들의 집합이다. Set(temp)를 하면 temp내에 중복된 값들을 제거해준다. Set에도 여러 methods들이 많으니 필요할 때마다 찾아가면서 공부하기.

function solution(strings, n) {
  //var answer = [];
  return strings.sort((a,b) => 
  { 
    if (a[n] > b[n]) return 1;
    else if (a[n] < b[n])  return -1;
    else{
      // b,a 순으로 되어야 함으로 comparefunction이 return 하는 값이 0보다 커야 함.
      if (a>b)  return 1;
      // a,b 순으로 되어야 함으로 comparefunction이 return 하는 값이 0보다 작아야 함.
      else if (a<b) return -1;
      else  return 0; 
    }
  });
}

// alternative
return strings.sort((s1,s2) => s1[n]===s2[n] ?s1.localeCompare(s2):s1[n].localeCompare(s2[n]));

feedback: sort(compareFn(a,b)=>a-b): compareFn에 아무것도 안 주어지면 입력값들이 모두 string으로 변환되어 유니코드 표준으로 정렬(오름차순). array.sort((a,b) => a-b)로 오름차순 정렬 가능. If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first. If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. If compareFunction(a, b) is greater than 0, sort b to a lower index than a. localeCompare function 은 문자열과 문자열을 비교하며 비교 결과에 따른 숫자를 반환. Ex) string.localecCompare('c')에서 string이 c보다 사전적으로 앞에 있다면 음수의 값을 return, 사전적으로 뒤에 있다면 양수의 값을 return.

  • 주의) string에서 (sort(a,b) => a-b)를 사용하게 되면 a-b 연산에서 문자열을 ASCII에 맞게 숫자열로 바꿔 비교하기 때문에 문자열을 sort하는 게 목적이라면 a>b와 같은 비교를 사용하자.

0개의 댓글

Powered by GraphCDN, the GraphQL CDN