Program w języku Java do obliczania wszystkich permutacji ciągu

W tym przykładzie nauczymy się obliczać wszystkie permutacje ciągu w Javie.

Aby zrozumieć ten przykład, należy znać następujące tematy dotyczące programowania w języku Java:

  • Ciąg Java
  • Rekursja Java
  • Klasa skanera Java

Permutacja ciągu oznacza wszystkie możliwe nowe ciągi, które można utworzyć przez zamianę pozycji znaków w ciągu. Na przykład ciąg ABC ma permutacje (ABC, ACB, BAC, BCA, CAB, CBA) .

Przykład: program w języku Java, aby uzyskać całą permutację ciągu

 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)); ) )

Wynik

 Wpisz ciąg: ABC Permutacje ABC: (ACB, BCA, ABC, CBA, BAC, CAB)

W Javie wykorzystaliśmy rekurencję do obliczenia wszystkich permutacji łańcucha. Tutaj przechowujemy permutację w zestawie. Więc nie będzie duplikatów permutacji.

Interesujące artykuły...