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

การตรวจสอบตัวเลข Pandigital (ครบ 0-9) ใน JavaScript

ภาพรวม

Pandigital Number คือตัวเลขที่มีตัวเลข 0-9 ครบทุกตัวอย่างน้อย 1 ครั้ง

ตัวอย่าง

'47458892414'     -> false (ขาด 0, 3, 6)
'53657687691428890' -> true (ครบ 0-9)

การนำไปใช้

const isPandigital = (numStr) => {
  let legend = ['0','1','2','3','4','5','6','7','8','9'];
  
  for (let i = 0; i < numStr.length; i++) {
    const idx = legend.indexOf(numStr[i]);
    if (idx !== -1) {
      legend.splice(idx, 1); // ลบออกจากรายการที่ต้องหา
    }
  }
  return legend.length === 0;
};

console.log(isPandigital('47458892414'));      // false
console.log(isPandigital('53657687691428890')); // true

ผลลัพธ์

false true

วิธีการทันสมัยและมีประสิทธิภาพมากกว่า

// ใช้ Set (O(n))
const isPandigitalSet = (numStr) => 
  new Set(numStr).size === 10 && /^[0-9]+$/.test(numStr);

// ใช้ Bitmask (O(n), O(1) Space)
const isPandigitalBitmask = (numStr) => {
  let mask = 0;
  for (const char of numStr) {
    const digit = char.charCodeAt(0) - 48;
    if (digit < 0 || digit > 9) return false; // Non-digit
    mask |= 1 << digit;
  }
  return mask === 0x3FF; // 0b1111111111 = 1023
};

// Regex + Set (สั้นที่สุด)
const isPandigitalShort = (numStr) => 
  /^\d+$/.test(numStr) && new Set(numStr).size === 10;

Pandigital Numbers ที่น่าสนใจ

  • 1023456789 - 10-digit pandigital น้อยที่สุด
  • 9876543210 - 10-digit pandigital มากที่สุด
  • Pandigital Primes: ไม่มี 10-digit pandigital prime (Sum of digits = 45 หาร 3 ลงตัว)
  • Pandigital Multiples: 123456789 × 2 = 246913578 (Pandigital Pair)

การประยุกต์ใช้

  • Recreational Mathematics
  • Puzzle Solving (Project Euler #38, #41)
  • Cryptography: Key Space Analysis
  • Testing: Generate Test Data

ข้อควรระวัง

  • Leading Zeros: '0123456789' เป็น Pandigital แต่ไม่ใช่ Valid Number Representation
  • Duplicate Digits: ยอมรับได้ (At Least Once)
  • Non-digit Characters: ต้อง Return False