Kosal Ang
Fri Jan 06 2023
Photo by: Ivana Cajina
Generate all permutations of string and filter unique string by using JavaScript
An example of permutations of string would be this:
So we’ve figured out what a permutation is, and established that (depending on the length of the string) we may be looking for a lot of them.
Below is the function to generate permutations:
1const findPermutation = (num) => { 2 const results = [] 3 const num_data = num.split('') 4 function permute(arr, mem) { 5 let cur 6 const tmp = mem || [] 7 8 for (var i = 0; i < arr.length; i++) { 9 cur = arr.splice(i, 1) 10 if (arr.length === 0) { 11 results.push(tmp.concat(cur)) 12 } 13 permute(arr.slice(), tmp.concat(cur)) 14 arr.splice(i, 0, cur[0]) 15 } 16 17 return results 18 } 19 return permute(num_data) 20 .map((t) => t.join('')) 21 .filter((value, index, self) => self.indexOf(value) === index) 22} 23
Example:
1findPermutation('123'); 2[ '123', '132', '213', '231', '312', '321' ] 3 4findPermutation('abcd'); 5[ 6 'abcd', 'abdc', 'acbd', 7 'acdb', 'adbc', 'adcb', 8 'bacd', 'badc', 'bcad', 9 'bcda', 'bdac', 'bdca', 10 'cabd', 'cadb', 'cbad', 11 'cbda', 'cdab', 'cdba', 12 'dabc', 'dacb', 'dbac', 13 'dbca', 'dcab', 'dcba' 14] 15 16findPermutation('aabc'); 17[ 18 'aabc', 'aacb', 19 'abac', 'abca', 20 'acab', 'acba', 21 'baac', 'baca', 22 'bcaa', 'caab', 23 'caba', 'cbaa' 24] 25
Hope this article can help you.
Creating a beautiful menu bar using HTML, CSS, and JavaScript involves creating the structure with HTML
JavaScript uses asynchronous programming. Promises and `async`/`await` are two powerful features that facilitate asynchronous operations in JavaScript
JavaScript's closures and scope are fundamental concepts that significantly impact how code behaves
If you're looking to build a responsive sidebar with icons and expandable menus, this HTML and CSS template can serve as a great starting point
Arrays and objects in JavaScript is fundamental for managing and manipulating data
ECMAScript 6, also known as ES6 or ECMAScript 2015, introduced several powerful features that significantly enhanced the capabilities of JavaScript
To get the Monday and Sunday of the week, use the setDate() method to set the day of the month of a date to the Monday and Sunday
JavaScript is a versatile scripting language primarily used for client-side web development. It enables interactivity and dynamic content on web pages.
Dropdowns are a feature common to many websites. It's very useful, as they make it easy to show additional data only when it is needed.
TailwindCSS is a popular CSS framework that can help you create nice user interfaces quickly with pre-made CSS classes.