+4

How can i get this code to write all the possible permutation in the created txt i only get GRB in the text file after run

import java.util.Formatter; import java.util.*; import java.io.*; class Permutation { public static void main(String[] args) { String str = "RBG"; int n = str.length(); Permutation permutation = new Permutation(); permutation.permute(str, 0, n-1); } //permutation function private void permute(String str, int l, int r) { if (l == r) { try { Formatter form=new Formatter("/sdcard/Download/new.txt"); form.format(str); form.close();} catch (Exception e) { System.out.println("Error");}} else { for (int i = l; i <= r; i++) { str = swap(str,l,i); permute(str, l+1, r); str = swap(str,l,i); }}} private String swap(String a, int i, int j) { char temp; char[] charArray = a.toCharArray(); temp = charArray[i] ; charArray[i] = charArray[j]; charArray[j] = temp; return String.valueOf(charArray); } }

1/11/2019 4:58:49 PM

Da Vinci

4 Answers

New Answer

+4

Jephthah I know this is a day late so if you have already solved your problem please ignore this reply. If not... The code you provided is overwriting the new.txt file every time permute() is called/ invoke with the current str passed to it. One way to remedy this is to use StringBuilder object, append str to said object and pass the object to form.fomat() method. import java.util.*; import java.io.*; class Permutation { // added stringbuilder to save and append to previous data store in text file private StringBuilder sb = new StringBuilder(); public static void main(String[] args) { String str = "RBG"; int n = str.length(); Permutation permutation = new Permutation(); permutation.permute(str, 0, n-1); } //permutation function private void permute(String str, int l, int r) { if (l == r) { try { sb.append(str); sb.append(" "); Formatter form=new Formatter("/sdcard/Download/new.txt"); form.format(sb.toString()); form.close();} catch (Exception e) { System.out.println("Error");}} else { for (int i = l; i <= r; i++) { str = swap(str,l,i); permute(str, l+1, r); str = swap(str,l,i); }}} private String swap(String a, int i, int j) { char temp; char[] charArray = a.toCharArray(); temp = charArray[i] ; charArray[i] = charArray[j]; charArray[j] = temp; return String.valueOf(charArray); } } When reviewing new.txt you should see all 6 permutations of RGB

+3

Thank you very much ODLNT

+1

YOU WILL USE (TITLE)

0

YOU ARE WELL COME FROM THE RAY