जावा प्रोग्राम स्ट्रिंग के सभी क्रमपरिवर्तन की गणना करने के लिए

इस उदाहरण में, हम जावा में स्ट्रिंग के सभी क्रमपरिवर्तन की गणना करना सीखेंगे।

इस उदाहरण को समझने के लिए, आपको निम्नलिखित जावा प्रोग्रामिंग विषयों का ज्ञान होना चाहिए:

  • जावा स्ट्रिंग
  • जावा पुनर्मिलन
  • जावा स्कैनर क्लास

स्ट्रिंग के क्रमांकन का अर्थ है स्ट्रिंग के पात्रों की स्थिति को इंटरचेंज करके बनाए जा सकने वाले सभी संभावित नए तार। उदाहरण के लिए, स्ट्रिंग एबीसी में क्रमपरिवर्तन (एबीसी, एसीबी, बीएसी, बीसीए, सीएबी, सीबीए) हैं

उदाहरण: एक स्ट्रिंग के सभी क्रमचय प्राप्त करने के लिए जावा प्रोग्राम

 import java.util.HashSet; import java.util.Scanner; import java.util.Set; class Main ( public static Set getPermutation(String str) ( // create a set to avoid duplicate permutation Set permutations = new HashSet(); // check if string is null if (str == null) ( return null; ) else if (str.length() == 0) ( // terminating condition for recursion permutations.add(""); return permutations; ) // get the first character char first = str.charAt(0); // get the remaining substring String sub = str.substring(1); // make recursive call to getPermutation() Set words = getPermutation(sub); // access each element from words for (String strNew : words) ( for (int i = 0;i<=strNew.length();i++)( // insert the permutation to the set permutations.add(strNew.substring(0, i) + first + strNew.substring(i)); ) ) return permutations; ) public static void main(String() args) ( // create an object of scanner class Scanner input = new Scanner(System.in); // take input from users System.out.print("Enter the string: "); String data = input.nextLine(); System.out.println("Permutations of " + data + ": " + getPermutation(data)); ) )

आउटपुट

 स्ट्रिंग दर्ज करें: एबीसी के एबीसी क्रमांकन: (एसीबी, बीसीए, एबीसी, सीबीए, बीएसी, सीएबी)

जावा में, हमने स्ट्रिंग के सभी क्रमपरिवर्तन की गणना करने के लिए पुनरावर्तन का उपयोग किया है। यहां, हम एक सेट में क्रमचय को स्टोर करते हैं। तो, कोई डुप्लिकेट परमिट नहीं होगा।

दिलचस्प लेख...