Algorithm - CodeKata #11 πŸ“Œ

devmoonshΒ·2020λ…„ 9μ›” 28일
0

Algorithm

λͺ©λ‘ 보기
14/37
post-thumbnail

1. Question

input으둜 받은 두 수λ₯Ό κ³±ν•΄μ„œ λ°˜ν™˜ν•΄μ£Όμ„Έμš”.
λ°˜ν™˜ν•˜λŠ” ν‘œν˜„λ„ λ³΅μ†Œμˆ˜ ν˜•νƒœμ˜ string 이어야 ν•©λ‹ˆλ‹€.

λ³΅μ†Œμˆ˜ μ •μ˜μ— μ˜ν•˜λ©΄ (i^2)λŠ” -1 μ΄λ―€λ‘œ (i^2) μΌλ•ŒλŠ” -1둜 κ³„μ‚°ν•΄μ£Όμ„Έμš”.

  • 제곱 ν‘œν˜„μ΄ μ•ˆ λ˜μ–΄ i의 2μ œκ³±μ„ (i^2)라고 ν‘œν˜„ν–ˆμŠ΅λ‹ˆλ‹€.

예제 1:
Input: "1+1i", "1+1i"
Output: "0+2i"
μ„€λͺ…:
(1 + i) * (1 + i) = 1 + i + i + i^2 = 2i
2iλ₯Ό λ³΅μ†Œμˆ˜ ν˜•νƒœλ‘œ λ°”κΎΈλ©΄ 0+2i.

예제 2:
Input: "1+-1i", "1+-1i"
Output: "0+-2i"
μ„€λͺ…:
(1 - i) * (1 - i) = 1 - i - i + i^2 = -2i,
-2iλ₯Ό λ³΅μ†Œμˆ˜ ν˜•νƒœλ‘œ λ°”κΎΈλ©΄ 0+-2i.

예제 3:
Input: "1+3i", "1+-2i"
Output: "7+1i"
μ„€λͺ…:
(1 + 3i) * (1 - 2i) = 1 - 2i + 3i -6(i^2) = 1 + i + 6,
7+iλ₯Ό λ³΅μ†Œμˆ˜ ν˜•νƒœλ‘œ λ°”κΎΈλ©΄ 7+1i.

κ°€μ •
input은 항상 a+bi ν˜•νƒœμž…λ‹ˆλ‹€.
output도 a+bi ν˜•νƒœλ‘œ λ‚˜μ™€μ•Ό ν•©λ‹ˆλ‹€.


2. Answer

const complexNumberMultiply = (a, b) => {
    let a_container = a.split(/[-,+]/);
    let b_container = b.split(/[-,+]/);
    if(a_container.indexOf('') > -1){
      const empty_a = a_container.indexOf('');
      a_container.splice(empty_a,1)
    } 
    if(b_container.indexOf('') > -1){
      const empty_b = b_container.indexOf('');
      b_container.splice(empty_b,1)
    }
    a_container[1] = a_container[1].slice(0,a_container[1].length-1)
    b_container[1] = b_container[1].slice(0,b_container[1].length-1)
    a_container = a_container.map(Number);
    b_container = b_container.map(Number);
    let a_operator = [];
    let b_operator = [];
    for(let i = 0; i < a.length; i++){
        if(a[i] === '+' || a[i] === '-'){
            a_operator.push(a[i])
        }   
    }
    for(let i = 0; i < b.length; i++){
        if(b[i] === '+' || b[i] === '-'){
            b_operator.push(b[i])
        }   
    }

    if(a_operator.length === 2){
        a_container[1] = -1 * a_container[1]
    }
    if(b_operator.length === 2){
        b_container[1] = -1 * b_container[1]
    }

    let container1 = []; // 첫번쨰: μ •μˆ˜λΌλ¦¬, λ‘λ²ˆμ§Έ: μ •μˆ˜*i, μ„Έλ²ˆμ§Έ: i의 제곱 1 + i + i + i^2 = 2i 
    container1[0] = a_container[0] * b_container[0]
    container1[1] = a_container[0] * b_container[1] + b_container[0] * a_container[1]
    container1[2] = a_container[1] * b_container[1]
    
    let result = [];
    result[0] = container1[0] - container1[2]
    result[1] = container1[1]
    
    console.log(result) // [-3, 4]
    return `${result[0]}+${result[1]}i`
}

console.log(complexNumberMultiply("1+2i", "1-2i")); // '-3+4i'

좜처

profile
Junior front-end developer

0개의 λŒ“κΈ€