I solved the problem presented here: https://www.youtube.com/watch?v=PJCgFbb_qWA&list=PLoij6udfBncjOlB-3LfW9kVPAjr1-fqx9&index=4 with help in the comments))))) I do not fully understand what is happening. Please explain. The task was to add the code so that it correctly compiled the "Anagrams", saving the idea. I do not understand how this line (decision) saved the situation, why and how this is explained by the fact that the movement is going back along the stack.
Source:
import java.util.Arrays; public class Permutator { public static void permute (int[] arr, int size){ if( size < 2){ System.out.println(Arrays.toString(arr)); } else { for (int k = 0; k < size; k++){ swap(arr, k, size-1); permute(arr, size-1); } } } private static void swap(int [] arr, int index0, int index1 ){ int tmp = arr[index0]; arr[index0] = arr[index1]; arr[index1] = tmp; } } Total (with source array [1, 2, 3]):
[2, 3, 1]
[2, 3, 1]
[1, 2, 3]
[1, 2, 3]
[2, 1, 3]
[2, 1, 3]
Code (the one with the comment is the solution):
package chapterfirst; import java.util.Arrays; public class Permutator { public static void permute (int[] arr, int size){ if( size < 2){ System.out.println(Arrays.toString(arr)); } else { for (int k = 0; k < size; k++){ swap(arr, k, size-1); permute(arr, size-1); swap(arr, k, size-1); //решение } } } private static void swap(int [] arr, int index0, int index1 ){ int tmp = arr[index0]; arr[index0] = arr[index1]; arr[index1] = tmp; } } Result (with source array [1, 2, 3]):
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]
[1, 3, 2]
[2, 1, 3]
[1, 2, 3]