创建4个字母的所有排列 [英] Create all permutations of 4 letters

查看:97
本文介绍了创建4个字母的所有排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个由一系列4个字母组成的所有排列的数组(将4种核苷酸碱基称为A,C,G,T).程序应询问用户k的值,即排列的长度.我已经将其工作到可以得到排列的程度,但是它只显示没有重复的排列.这是程序,它现在给我的输出,以及我希望它给我的输出.

I want to create an array of all permutations of a series of 4 letters (Call them A,C,G,T for the 4 types of nucleotide bases). The program should ask the user for the value of k, the length of the permutation. I've got it working to the point where I can get the permutations, but it only shows the ones with no repeats. Here's the program, the output it's giving me right now, and the output I want it to give me.

import java.util.Arrays;
import TerminalIO.*;
public class Permute {
    static KeyboardReader reader= new KeyboardReader ();
    static int k= reader.readInt("Enter k-tuple");
    static void permute(int level, String permuted,
                        boolean[] used, String original) {

        if (level == k) {
            System.out.println(permuted);
        } else {
            for (int i = 0; i < 4; i++) {
                if (!used[i]) {
                    used[i] = true;
                    permute(level + 1, permuted + original.charAt(i), used, original);
                    used[i] = false;
                }
            }
        }
    }

    public static void main(String[] args) {
        String s = "ACGTACGTACGTACGTACGT";
        boolean used[] = new boolean[20];
        Arrays.fill(used, false);
        permute(0, "", used, s);
    }   
}

当我输入2的K值时,它会给我:

When I enter a K value of 2,it gives me:

  • AC
  • AG
  • AT
  • CA
  • CG
  • CT
  • GA
  • GC
  • GT
  • TA
  • TC
  • TG
  • AC
  • AG
  • AT
  • CA
  • CG
  • CT
  • GA
  • GC
  • GT
  • TA
  • TC
  • TG

理想情况下,它将打印:

Ideally, it would print:

  • AC
  • AG
  • AT
  • AA
  • CA
  • CC
  • CG
  • CT
  • GA
  • GG
  • GC
  • GT
  • TA
  • TC
  • TG
  • TT
  • AC
  • AG
  • AT
  • AA
  • CA
  • CC
  • CG
  • CT
  • GA
  • GG
  • GC
  • GT
  • TA
  • TC
  • TG
  • TT

推荐答案

public class Permute {

    static String s = "ACGT";

    static void permute(int level, String prefix) {

        if (level == 0) {
            System.out.println(prefix);
            return;
        }
        for (int i = 0; i < s.length(); i++)
            permute(level - 1, prefix + s.charAt(i));
    }

    public static void main(String[] args) {
        int k = 4;
        permute(k, "");
    }   

}

这篇关于创建4个字母的所有排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆