কম্পিউটার টিউটোরিয়াল

জাভাস্ক্রিপ্টে জাম্বলড নাম্বার নেম থেকে সংখ্যা বের করা


সমস্যা

মনে করুন নিচের নম্বর নামের স্ট্রিং:

const str = 'TOWNE';

এই স্ট্রিংটি পুনর্বিন্যাস করলে আমরা দুটি নম্বর নাম পাই: ২ (TWO) এবং ১ (ONE)। তাই আউটপুট হবে ২১।

আমাদের একটি জাভাস্ক্রিপ্ট ফাংশন লিখতে হবে যা এমন একটি স্ট্রিং নেবে এবং স্ট্রিংয়ে থাকা সংখ্যাগুলো ফেরত দেবে।

উদাহরণ

নিচে কোডটি দেওয়া হলো:

const str = 'TOWNE';
const findNumber = (str = '') => {
  function stringPermutations(str) {
    const res = [];
    if (str.length == 1) return [str];
    if (str.length == 2) return [str, str[1]+str[0]];
    str.split('').forEach((chr, ind, arr) => {
      let sub = [].concat(arr);
      sub.splice(ind, 1);
      stringPermutations(sub.join('')).forEach(function (perm) {
        res.push(chr+perm);
      });
    });
    return res;
  }
  const legend = {
    'ONE': 1, 'TWO': 2, 'THREE': 3, 'FOUR': 4,
    'FIVE': 5, 'SIX': 6, 'SEVEN': 7, 'EIGHT': 8,
    'NINE': 9, 'ZERO': 0
  };
  const keys = Object.keys(legend);
  const res = {};
  const resArr = [];
  let result = '';
  keys.forEach(key => {
    const match = stringPermutations(key).find(el => el.split('').every(char => str.includes(char)));
    if(match){
      const index = str.indexOf(match[0]);
      if(!res.hasOwnProperty(key)){
        res[key] = [index];
      }else if(!res[key].includes(index)){
        res[key].push(index);
      }
    }
  });
  Object.keys(res).forEach(word => {
    resArr.push([word, ...res[word]]);
  });
  resArr.sort((a, b) => a[1] - b[1]);
  resArr.forEach(sub => {
    result = result + String(legend[sub[0]]).repeat(sub.length - 1);
  });
  return +result;
};
console.log(findNumber(str));

আউটপুট

কনসোল আউটপুট:

21

  1. জাভাস্ক্রিপ্টে দশমিক সংখ্যা ভ্যালিডেশন

  2. জাভাস্ক্রিপ্টে রেঞ্জে আর্মস্ট্রอง নম্বর বের করা

  3. জাভাস্ক্রিপ্টে জাম্বলড নাম্বার নেম থেকে সংখ্যা বের করা

  4. জাভাস্ক্রিপ্টে ১ থেকে n পর্যন্ত সব সংখ্যা দিয়ে বিভাজ্য সবচেয়ে ছোট সংখ্যা