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

11th Jan 2019, 4:58 PM
Da Vinci
Da Vinci - avatar
4 odpowiedzi
+ 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
12th Jan 2019, 8:44 PM
ODLNT
ODLNT - avatar
+ 3
Thank you very much ODLNT
12th Jan 2019, 9:34 PM
Da Vinci
Da Vinci - avatar
+ 1
YOU WILL USE (TITLE)
6th Feb 2019, 3:01 PM
Ryne Maras
0
YOU ARE WELL COME FROM THE RAY
6th Feb 2019, 3:53 PM
Ryne Maras