JavaScript - CodeKata #11 ๐Ÿ“Œ

devmoonshยท2020๋…„ 9์›” 28์ผ
0

JavaScript

๋ชฉ๋ก ๋ณด๊ธฐ
36/48
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๊ฐœ์˜ ๋Œ“๊ธ€