数组排列组合

public class Test {

    public static void main(String[] args) {
        String[][] dataArray = {{"zhong","chong"},{"qing"},{"hai","huan"},{"ri"}};
        combine(dataArray, 4);
    }
    public static void combine(String[][] data, int n){
        if (n > data.length) {n = data.length;}
        int[] idx = new int[data.length];
        for (int i=0; i<data.length; i++) {
            if (i<data.length-n) {idx[i]=0;}
            else {idx[i]=1;}
        }
        List<String> list = new ArrayList<>();
        while (idx[0] < 2) {
            int cnt=0, dig=0;
            int[] gp = new int[n];
            for (int i=0; i<idx.length; i++) {
                if (idx[i] == 1) {
                    if (i<n) {dig++;}
                    if (cnt<n) {gp[cnt] = i;}
                    cnt++;
                }
            }
            if (n == cnt) {
                int[] subIdx = new int[n];
                Arrays.fill(subIdx, 0);
                while (subIdx[0] < data[gp[0]].length) {
                    StringBuilder sb = new StringBuilder();
                    for (int i=0; i<n; i++) {
                        sb.append(data[gp[i]][data[gp[i]].length-subIdx[i]-1]);
                    }
                    list.add(0, sb.toString());

                    subIdx[n-1]++;
                    for (int i=n-1; i>0; i--) {
                        if (subIdx[i] == data[gp[i]].length) {
                            subIdx[i] = 0;
                            subIdx[i-1]++;
                        } else {
                            break;
                        }
                    }
                }
            }
            if (dig == n) {break;}

            idx[data.length-1]++;
            for (int i=data.length-1; i>0; i--) {
                if (idx[i] == 2) {
                    idx[i] = 0;
                    idx[i-1]++;
                } else {
                    break;
                }
            }

        }

        int count = 0;
        for (String s : list) {
            System.out.printf("%s", s);
            System.out.println();
            count++;
            if (count%10 == 0) {System.out.println();}
        }
        System.out.printf("\ncount=%d\n", count);
    }
}

运行结果:

zhongqinghairi

zhongqinghuanri

chongqinghairi

chongqinghuanri

count=4

分类:Web 时间:2014-11-21 人气:2
本文关键词: 组合 排列组合
分享到:

相关文章

iOS 开发

Android 开发

Python 开发

JAVA 开发

开发语言

PHP 开发

Ruby 开发

搜索

前端开发

数据库

开发工具

开放平台

Javascript 开发

.NET 开发

云计算

服务器

Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 闽ICP备15018612号

processed in 0.031 (s). 10 q(s)