알고리즘
-
[프로그래머스 level.1] 내림차순정렬, 아스키코드 변환알고리즘 2023. 6. 21. 10:36
문자열내림차순 배열하기 function solution(s) { var answer = ''; let arr = [...s]; let newArr = arr.map(e => e.charCodeAt()).sort((a, b) => b - a) let listArr = newArr.map(e => String.fromCharCode(e)).join("") return listArr; } 내림차순 정렬은 오름차순정렬과는 a, b의 위치만 달라지면 된다 전에는 함수선언문? 으로 되어있었나 그래서 쓸 데 없이 길었는데 화살표 함수로 가독성 좀 높여봤음 아스키코드 변환은 계속해서 사용이 자주 되는데 헷갈림 왔다 갔다 다 좀 기억해두자 아니 근데 남의 풀이보니까 굳이 아스키코드 변환안해도 문자열 자체가 정렬했을 때 ..
-
[프로그래머스 level.1] slice 스파르타 예습알고리즘 2023. 6. 20. 11:33
문자열 내맘대로 정렬하기 function solution(strings, n) { var answer = []; for (let i = 0; i < strings.length; i++) { strings[i] = strings[i][n] + strings[i] } strings.sort() for (let i = 0; i < strings.length; i++) { strings[i] = strings[i].slice(1) } return strings; } 문자열 자르는 메서드를 slice()를 썼는데 substr() , subString() 얘네들도 slice()랑 똑같이 작용하고 인자도 똑같은 모습으로 받는것 같아서 slice() 하나만 기억하려고 한다. 스파르타에서 풀었던 문제라서 양심에 찔린다...
-
[프로그래머스 level.1] filter , includes알고리즘 2023. 6. 20. 11:22
로또의 순위 function solution(lottos, win_nums) { let countZero = lottos.filter(x => x===0).length; //0의개수 let sameNum = lottos.filter(x => win_nums.includes(x)).length; //같은 개수 let num1 = 7 - (sameNum + countZero === 0 ? 1 : sameNum + countZero); let num2 = 7 - (sameNum === 0? 1 : sameNum); let answer = [num1, num2] return answer; } 쓰면서 생각이 든건데 변수명 작명을 좀 못하는 것 같다 나중에 다시 볼때 가독성을 높이기 위해서 조금은 고민하고 변수를 ..
-
[프로그래머스 level.1] 이중반복문, 중복제거, 정렬알고리즘 2023. 6. 20. 11:18
두개를 뽑아서 더하기 function solution(numbers) { let answer = []; for (let i = 0; i < numbers.length; i++) { for(let j = i + 1; j < numbers.length; j++) { answer.push(numbers[i] + numbers[j]); } } let result = [...new Set(answer)].sort(function(a, b) {return a - b;}); return result; } set을 활용하는것에 대해 선언을 간단하게 저렇게도 할 수 있다는 것을 알게 되었음 객체를 변수에 꼭 저장하지 않아도 호출만으로도 사용하는 법이 있구나 싶었음 sort() 관련되서는 항상 헷갈림 안에 수 정의를 하는..