'Stop permutations function after certain number of permutations are generated

I am using this script below to generate all possible permutations of a length of 15 from a list of 20 amino acids.

test <- permutations(20, 15, all.amino.acids)

There are soooo many different permutations, so I am trying to figure out a way to stop this function once its generated a certain number of outputs. Nothing I've tried works, any ideas?



Solution 1:[1]

For this problem I tried a different way, by using ArrayList<String> to look for duplicate lines. The code searches for duplicate lines and writes them to the output file.

public static void main(String[] args) throws FileNotFoundException, IOException {

    String input = ("C:\\Users\\Tyler\\Desktop\\Java Projects\\COMP1231\\"
            + "Assignment 3\\BookTitles.inp");
    String output = "C:\\Users\\Tyler\\Desktop\\Java Projects\\COMP1231\\"
            + "Assignment 3\\DuplicatesBook.inp";
    
    try {
        BufferedWriter bw = new BufferedWriter(new FileWriter(output));
        BufferedReader br = new BufferedReader(new FileReader(input));
        
        ArrayList<String> lines = new ArrayList<>();
        ArrayList<String> duplicates = new ArrayList<>();
        
        String s;
        while ((s = br.readLine()) != null) {
            lines.add(s);
        }
        
        for(String main : lines) {
            if(duplicates.contains(main)) {
                // Skip this line, because we already figured out that it's duplicate
                continue;
            }
            int count = 0;
            for(String sub : lines) {
                if(sub.equals(main)) {
                    // The lines are equal
                    // increase the counter
                    count++;
                }
            } 
            // If the line appears more then once
            // Add it to the duplicate list
            if(count > 1) {
                duplicates.add(main);
            }
        }
        
        // Write all duplicate lines to the BufferedOutputWriter
        for(String duplicate : duplicates) {
            bw.write(duplicate+"\n");
        }
        
        // Don't forget to flush..
        bw.flush();
        
        // Close all inputs and outputs
        bw.close();
        br.close();
        
        System.out.println("All files saved.");
    }
    catch (Exception e) {
        return;
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Log4JExploit