프로그래밍 이름 궁합 찾기 알고리즘
이름 궁합 찾기: 각 획수를 주고 획수를 짝수개씩 묶어 더해나가고 최종적으로 두 개의 수만 남을 때까지 계산하는 방법
코드 (자바스크립트)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
function matchName(name1, name2) {
name1 = name1.split('').map(c => c.toUpperCase())
name2 = name2.split('').map(c => c.toUpperCase())
const nameLength = name1.length + name2.length
const minLen = Math.min(name1.length, name2.length)
const weight = [3, 2, 1, 2, 4, 3, 1, 3, 1, 1, 3, 1, 3, 2, 1, 2, 2, 2, 1, 2, 1, 1, 1, 2, 2, 1]
// 문자열 배열 생성
const nameArr = []
for(let i = 0; i < minLen; i++) {
nameArr.push(name1[i])
nameArr.push(name2[i])
}
const remainName = name1.slice(minLen)[0] != undefined ? name1 : name2
for(let c of remainName.slice(minLen)) {
nameArr.push(c)
}
// 최초 점수 배열 생성
const scoreArr = (_ => {
const array = []
for(let c of nameArr) {
array.push(weight[c.charCodeAt(0) - "A".charCodeAt(0)])
}
return array
})();
// 점수 계산
for(let i = 0; i < nameLength - 2; i++) {
for(let j = 0; j < nameLength - i - 1; j++) {
scoreArr[j] += scoreArr[j + 1]
// scoreArr[j] %= 10 // 여기에 넣지 않아도 최종 결과에서 한 번만 해당 자리수를 추출하면 됨
}
}
// 특정 자리수 추출 방법: 일의 자리는 % 10, 십의 자리는 나누기 10 해서 몫만 취한 후 % 10
return (scoreArr[0] % 10 * 10 + scoreArr[1] % 10) + "%"
}
1
2
3
4
console.log(matchName("LEESIYUN", "MIYAWAKISAKURA"))
console.log(matchName("AB", "CD"))
console.log(matchName("BOJ", "IN"))
console.log(matchName("ere", "gcx"))
계산 과정
This post is licensed under
CC BY 4.0
by the author.


