获取给定字母的所有4个字符的组合 [英] Get all 4-character combinations of a given alphabet

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

问题描述

假设alphabet = "abcd1234" 我想要所有具有4位数字的组合. 我不想遍历所有排列,只选择长度为4个字符的排列,因为字母可能很大.

let's say alphabet = "abcd1234" I would want all combinations that have 4 digits. I dont want to go through all permutations and choose only those which are 4 characters long Since the alphabet could be big.

这是我到目前为止所拥有的

this is what I have so far

String alpha = "abcdefg"; 

        for (int i = 0 ; i < alpha.length() ; i++) {
            for (int j = i ; j < alpha.length()-i ; j++) 
                    System.out.println(String.valueOf(alpha.charAt(i)) + String.valueOf(alpha.charAt(j))   );   
        }

不幸的是,我只得到一个2个字符的单词.而且我无法使用相同的循环结构来打印4个字符的单词.

Unfortunately I get only a 2 character word. And I cant get it to print 4 character words using the same structure of loops.

推荐答案

如果我正确理解了该问题-aaaa至4444的所有组合-则可以使用.它是可伸缩的"-不需要每个字符嵌套循环.

If I understand the problem correctly - all combinations aaaa through to 4444 - then this will work. It is "scalable" - doesn't require a nested loop per character.

String alpha = "abcd1234";
char[] seq = alpha.toCharArray();

int length = 4;
StringBuilder builder = new StringBuilder("    ");

int[] pos = new int[length];
int total = (int) Math.pow(alpha.length(), length);
for (int i = 0; i < total; i++) {
    for (int x = 0; x < length; x++) {
        if (pos[x] == seq.length) {
            pos[x] = 0;
            if (x + 1 < length) {
                pos[x + 1]++;
            }
        }
        builder.setCharAt(x, seq[pos[x]]);
    }
    pos[0]++;

    System.out.println(builder.toString());
}

这篇关于获取给定字母的所有4个字符的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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