What is wrong with my recursion to create permutations of a string? - java

It is printing out a few permutations but the rest are null and I'm not sure why. I need to but all the permutations into String[] and I can't import any other package except for util.Arrays. Please help!
import java.util.Arrays;
public class DIE
{
public static String[] printPermutations(String s)
{
int l = s.length();
int f = factorial(l);
int count = 0;
String[] array = new String[f];
permute("", s, array, 0);
Arrays.sort(array);
return array;
}
private static String[] permute(String x, String s, String [] array, int count)
{
int l = s.length();
if (l == 0)
{
array[count] = (x + s);
}
for (int i = 0; i < l; i++)
{
permute(x + s.charAt(i), s.substring(0, i) +
s.substring(i +1, s.length()), array, count);
count++;
}
return array;
}
public static int factorial(int l)
{
if (l == 1)
{
return 1;
}
else
{
int result = l * factorial(l - 1);
return result;
}
}
/*
Do not edit anything below this comment.
*/
public static void main(String[] args)
{
String[] permutations = printPermutations(args[0]);
for(String p : permutations)
{
System.out.println(p);
}
}
}

Your count variable is wrong. Within the outermost call to permute("", "abc", ...) it is incremented only by one, even though the call to the next level permute("a", "bc", ...) creates two permutations!
There are two possible solutions:
Instead of a String[] to collect your result use a List<String>. Then you don't need to manually count the number of permutations.
let permute return the new count (instead of the result array, that one is never used anyway)
For permute to return the new count the method would look like this:
private static int permute(String x, String s, String [] array, int count)
{
int l = s.length();
if (l == 0)
{
array[count++] = x;
}
for (int i = 0; i < l; i++)
{
count = permute(x + s.charAt(i), s.substring(0, i) +
s.substring(i +1, s.length()), array, count);
}
return count;
}
Using a List<String> would need some more changes, but the permute function would be smaller:
public static List<String> printPermutations(String s)
{
int l = s.length();
int f = factorial(l);
List<String> result = new ArrayList<>(f);
permute("", s, result);
Collections.sort(result);
return result;
}
private static void permute(String x, String s, List<String> result)
{
int l = s.length();
if (l == 0)
{
result.add(x);
}
for (int i = 0; i < l; i++)
{
permute(x + s.charAt(i), s.substring(0, i) +
s.substring(i +1, s.length()), result);
}
}
And some small changes in the main method due to the changed result of printPermutations (IMHO a very bad named method: it prints out nothing, it creates the permutations together with a helper method)

Related

Remove static int counter from this recursive solution

I have this recursive code for counting the number of permutations a string can have
public class Permutation {
static int counter = 0;
public static int perms(String s, int level,int length) {
if(level == length-1) {
counter++;
}
else {
for (int i = 0; i < s.length(); i++) {
String newString = s.substring(0, i) + s.substring(i + 1);
perms(newString,level + 1, length);
}
}
return counter;
}
public static void main(String[] args) {
System.out.println(perms("plot", 0, 4));
}
}
I was wondering how I can rewrite it so that it doesn't use static int counter = 0? Thanks!
NOTE: Yes, I know I can just use the permutation formula for this haha
Without the need for a static counter or passing a counter value to each method call. Note that your implementation counts all permutations and not unique permutations (String "aab" returns 6, not 3).
public static int permsRedone(String s, int level,int length){
int count = 0;
if(level == length-1){
return 1;
}
else {
for (int i = 0; i < s.length(); i++) {
String newString = s.substring(0,i)+s.substring(i+1);
count += permsRedone(newString,level+1,length);
}
}
return count;
}
You can pass the counter as the fourth argument (using 0 as the initial value). Return it from perms and set it to the value returned from the inner call.
public static int perms2(String s, int level,int length, int count){
if(level == length-1){
count++;
}
else {
for (int i = 0; i < s.length(); i++) {
String newString = s.substring(0,i)+s.substring(i+1);
count = perms2(newString,level+1,length, count);
}
}
return count;
}

dynamic programming dictionary exercise bottom-up approach in java

Here is the problem i want to solve:
You are given a dictionary, i.e. a set S of m strings, and a separate string t. You are required to output the minimum number of substrings that t can be broken up to, such that the union of these substrings is t and all the substrings belong to the dictionary.
Example:
Input:
5
0 1 11 1101 000
1111001000
Output:
6
I have solved it using the top-down with memoization approach (in java):
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
String[] s = new String[m];
for(int i = 0; i < m; ++i){
s[i] = sc.next();
}
String t = sc.next();
System.out.println(topDown(m, s, t));
}
public static int topDown(int m, String[] s, String t) {
int r[] = new int[m + 1];
for (int i = 0; i <= m; ++i) {
r[i] = Integer.MAX_VALUE - 3;
}
return memo(m, s, t, r);
}
public static int memo(int m, String[] s, String t, int[] r) {
int best = Integer.MAX_VALUE - 3;
for (int i = 0; i < m; ++i) {
if (t.equals(s[i])) {
r[m] = 1;
return 1;
}
}
if (m == 0) {
best = 0;
} else {
int a;
for (String str : s) {
if (t.endsWith(str)) {
a = 1 + memo(m, s, replaceLast(t, str, ""), r);
if (best > a)
best = a;
}
}
}
r[m] = best;
return best;
}
public static String replaceLast(String string, String substring,
String replacement) {
int index = string.lastIndexOf(substring);
if (index == -1)
return string;
return string.substring(0, index) + replacement
+ string.substring(index + substring.length());
}
}
I can't seem to find the way to solve this problem using the bottom-up approach... If someone could show me how to solve it with bottom-up it would be great

How can I return all possible permutations of a given array in Java?

Say I have the nested array
gridInterFT=[[1,2],[2,3],[3,4],[1,3],[1,4],[2,4]]
How would I write a function that takes this array as input and returns a 3d nested array containing all possible permutations of the array?
I.e. the returned array should look something like:
[[[1,2],[2,3],[3,4],[1,3],[1,4],[2,4]], [[1,3],[2,3],[3,4],[1,2],[1,4],[2,4]],
[[2,3],[1,2],[3,4],[1,3],[1,4],[2,4]]...]
Are there any libraries which contain functions that do this directly?
static <T> void swap(T[] a, int i, int j) {
T t = a[i];
a[i] = a[j];
a[j] = t;
}
static void permutation(int[][] perm, int n, List<int[][]> result) {
int size = perm.length;
if (n >= size)
result.add(Arrays.copyOf(perm, size));
else
for (int i = n; i < size; i++ ) {
swap(perm, n, i);
permutation(perm, n + 1, result);
swap(perm, n, i);
}
}
public static int[][][] permutation(int[][] perm) {
List<int[][]> result = new ArrayList<>();
permutation(perm, 0, result);
return result.toArray(new int[0][][]);
}
public static void main(String[] args) {
int[][] gridInterFT={{1,2},{2,3},{3,4},{1,3},{1,4},{2,4}};
int[][][] r = permutation(gridInterFT);
for (int[][] a : r) {
for (int i = 0; i < a.length; ++i)
System.out.print(Arrays.toString(a[i]));
System.out.println();
}
}

Explanation on Java Permutation program

this question might seem basic to some people but I've been analysing and dissecting this code without success as to how this permutation program by Robert Sedgewick prints the combination o f words or characters without using system.out.print in the methods perm1 and perm2. Any help or explanation for dummies is greatly appreciated. Thank you in advance.
This is the code under the link:
public class Permutations {
// print N! permutation of the characters of the string s (in order)
public static void perm1(String s) { perm1("", s); }
private static void perm1(String prefix, String s) {
int N = s.length();
if (N == 0) System.out.println(prefix);
else {
for (int i = 0; i < N; i++)
perm1(prefix + s.charAt(i), s.substring(0, i) + s.substring(i+1, N));
}
}
// print N! permutation of the elements of array a (not in order)
public static void perm2(String s) {
int N = s.length();
char[] a = new char[N];
for (int i = 0; i < N; i++)
a[i] = s.charAt(i);
perm2(a, N);
}
private static void perm2(char[] a, int n) {
if (n == 1) {
System.out.println(a);
return;
}
for (int i = 0; i < n; i++) {
swap(a, i, n-1);
perm2(a, n-1);
swap(a, i, n-1);
}
}
// swap the characters at indices i and j
private static void swap(char[] a, int i, int j) {
char c;
c = a[i]; a[i] = a[j]; a[j] = c;
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
String elements = alphabet.substring(0, N);
perm1(elements);
System.out.println();
perm2(elements);
}
}
It's right there:
if (N == 0) System.out.println(prefix);
System.out.print and System.out.println is basically the same, except the later prints a newline after the text.

Combinations of integers

I'd appreciate any help on the following problem. I have n integers from 0 to n-1, and I'm trying to generate a list of all possible combinations of length k (i.e. k concatenated integers) such that every pair of consecutive integers are not equal. So, for example, (1)(2)(3)(2) would be valid with k = 4, but (1)(2)(3)(3) would not be valid. Any ideas on how to approach this most efficiently? (I don't care much about length/degree of complexity of the code, just efficiency)
It is the code:
void Generate(int[] source, List<int[]> result, int[] build, int k, int num) {
if (num == k) {
int[] a = (int[])build.clone();
result.add(a);
return;
}
for (int i = 0; i < source.length; i++)
if (num == 0 || source[i] != build[num - 1])
{
build[num] = source[i];
Generate(source, result, build, k, num + 1);
}
}
How to call:
int k = 2;
List<int[]> a = new ArrayList<int[]>();
Generate(new int[]{1,2,3}, a, new int[k], k, 0);
public class Generator {
final int k = 2;
final char[] n = new char[]{'0','1','2','3','4','5','6','7','8','9'};
final char[] text = new char[k];
public void gen(int i, int not_n) {
if(i == k) {
System.out.println(text);
return;
}
for(int j = 0; j < n.length; j++) {
if(j == not_n) continue;
text[i] = n[j];
gen(i+1, j);
}
}
public static void main(String[] args) {
new Generator().gen(0, -1);
}
}
public static void recursiveOutput(Integer n, int k, int limit, String prints){
k++;
if(k>limit)
return;
String statePrints = prints;
//cycle through all available numbers
for(Integer i = 1; i<=n; i++)
{
statePrints = prints;
//First cycle
if(k==1){
statePrints+= "(" + i.toString() + ")";
recursiveOutput(n, k, limit, statePrints);
}
//check if predecessor is not the same
if(i != Integer.parseInt(statePrints.substring(statePrints.length()-2,statePrints.length()-1))){
statePrints += "(" + i.toString() + ")";
recursiveOutput(n, k, limit, statePrints);
}
}
//Check if the length matches the combination length
if(statePrints.length() == 3 * limit)
System.out.println(statePrints);
}
call :recursiveOutput(3,0,4,"");

Categories