एनाग्राम
एनाग्राम वे स्ट्रिंग पेयर हैं, जिनमें से एक को एक निश्चित पैटर्न में रीऑर्डर करने पर दूसरा प्राप्त होता है।
उदाहरण के लिए:
'hello' और 'lolhe' एनाग्राम हैं क्योंकि हम 'lolhe' को रीऑर्डर करके 'hello' स्ट्रिंग बना सकते हैं या इसके विपरीत।
हमें एक JavaScript फ़ंक्शन लिखना है जो दो स्ट्रिंग्स लेता है, मान लीजिए str1 और str2। फ़ंक्शन को true लौटाना चाहिए यदि स्ट्रिंग्स एक-दूसरे की एनाग्राम हैं, अन्यथा false।
हम एक मैप बना सकते हैं जो प्रत्येक इनपुट स्ट्रिंग के लिए कैरेक्टर्स की संख्या गिनता है। फिर, हम मैप्स की तुलना करके देख सकते हैं कि वे समान हैं या नहीं।
उदाहरण
const str1 = 'hello'; const str2 = 'lolhe'; const charCount = string => { const table = {}; for (let char of string.replace(/\W/g, "").toLowerCase()) table[char] = table[char] + 1 || 1; return table; }; const anagrams = (stringA, stringB) => { const charCountA = charCount(stringA); const charCountB = charCount(stringB); if (Object.keys(charCountA).length !== Object.keys(charCountB).length) return false; for (let char in charCountA) if (charCountA[char] !== charCountB[char]) return false; return true; }; console.log(anagrams(str1, str2));आउटपुट
कंसोल में आउटपुट होगा:
true