Search code examples
javapermutationstring-length

I have a code for generating permutation of a string of a particular length, its not working for abcdefghijklmnopqrstuvwxyz and input of 7


I am getting this error for the below input, please suggest any other code.

abcdefghijklmnopqrstuvwxyz
7

Error:

Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
at java.lang.StringBuilder.toString(Unknown Source)
at aaa.c.generateCombination(c.java:24)
at aaa.c.generateCombination(c.java:24)
at aaa.c.generateCombination(c.java:24)
at aaa.c.generateCombination(c.java:24)
at aaa.c.generateCombination(c.java:24)
at aaa.c.generateCombination(c.java:24)
at aaa.c.generateCombination(c.java:24)
at aaa.c.main(c.java:37)

it is working for:

abcdefghijklmnopqrstuvwxyz
5

package aaa;

import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

class c {
    static int c;
    List<String> permutations = new LinkedList<String>();
    Scanner sc=new Scanner(System.in); 
    String input =sc.nextLine();
    int conbinationSize = sc.nextInt();
    boolean[] isChoosed = new boolean[input.length()];
    public void generateCombination(String partialOutput) {
        if (partialOutput.length() == conbinationSize) {
            permutations.add(partialOutput);
            c++;
            return;
        }
        for (int i = 0; i < input.length(); ++i) {
            if (!isChoosed[i]) {
                isChoosed[i] = true;
                generateCombination(partialOutput + input.charAt(i));
                isChoosed[i] = false;      
            }
        }
    }

    void printCombination() {
        for (String c : permutations) {
            System.out.println(c);         
        }
    }
    public static void main(String[] args) {
        c dfs = new c();
        dfs.generateCombination("");
        dfs.printCombination();
        System.out.println(c);
    }
}

Solution

  • When run with a size of five, it puts 26*25*24*23*22=7 893 600 strings in your list.

    When run with a size of seven, it will try to put 26*25*24*23*22*21*20 = 3 315 312 000 strings in your list. Each string has an array of 7 characters so is around 34 bytes. Did you allocate 100GB to your java VM when you ran it?

    Realistically, you are better off using a generator/iterator to create combinations and permutations, passing in a function which does something to the combination rather than just storing it, or writing them to a stream rather than operating on them in memory.