JavaScript - CodeKata #11 ๐

devmoonshยท2020๋ 9์ 28์ผ
0

๋ชฉ๋ก ๋ณด๊ธฐ
36/48

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 ํํ๋ก ๋์์ผ ํฉ๋๋ค.

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'

์ถ์ฒ

Junior front-end developer