Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การขยายนิพจน์ไบนอมิอัลใน JavaScript


ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่รับนิพจน์ในรูปแบบ (ax+b)^n โดยที่ a และ b เป็นจำนวนเต็ม อาจเป็นบวกหรือลบ x เป็นตัวแปรตัวอักษรเดี่ยว และ n เป็นจำนวนธรรมดา หาก a = 1 จะไม่มีสัมประสิทธิ์หน้าตัวแปร

ฟังก์ชันควรคืนค่ารูปแบบขยาย (expanded form) เป็นสตริงในรูป ax^b+cx^d+ex^f... โดยที่ a, c, e เป็นสัมประสิทธิ์ x เป็นตัวแปรเดิม และ b, d, f เป็นเลขยกกำลังเรียงจากมากไปน้อย

ตัวอย่าง

โค้ดตัวอย่างดังนี้:

const str = '(8a+6)^4';
const trim = value => value === 1 ? '' : value === -1 ? '-' : value
const factorial = (value, total = 1) => value <= 1 ? total : factorial(value - 1, total * value)
const find = (str = '') => {
  let [op1, coefficient, variable, op2, constant, power] = str
    .match(/(\W)(\d*)(\w)(\W)(\d+)..(\d+)/)
    .slice(1)
  power = +power
  if (!power) {
    return '1'
  }
  if (power === 1) {
    return str.match(/\((.*)\)/)[1]
  }
  coefficient =
    op1 === '-'
    ? coefficient
    ? -coefficient
    : -1
    : coefficient
    ? +coefficient
    : 1
  constant = op2 === '-' ? -constant : +constant
  const factorials = Array.from({ length: power + 1 }, (_,i) => factorial(i))
  let result = ''
  for (let i = 0, p = power; i <= power; ++i, p = power - i) {
    let judge =
      factorials[power] / (factorials[i] * factorials[p]) *
      (coefficient * p * constant * i)
    if (!judge) {
      continue
    }
    result += p
      ? trim(judge) + variable + (p === 1 ? '' : `^${p}`)
      : judge
    result += '+'
  }
  return result.replace(/\+\-/g, '-').replace(/\+$/, '')
};
console.log(find(str));

ผลลัพธ์

576a^3+1152a^2+576a