给定数组a[1,2,3],用a里面的元素来生成一个长度为5的数组,打印出其排列组合

给定数组a[1,2,3],用a里面的元素来生成一个长度为5的数组,打印出其排列组合

ruby代码:

def all_possible_arr arr, length = 5
    ret = []
    length.times do
        if ret.empty?
            ret = arr.map {|i| [i]}      
        else
            new_ret = []
            ret.each do |r|
                arr.each do |e|
                    new_ret << r.clone.unshift(e)
                end
            end      
            ret = new_ret
        end
    end
    ret
end

p all_possible_arr [1, 2, 3] 

JAVA代码:

package com.test;

import java.util.ArrayList;

public class TestEmu {

    @SuppressWarnings("unchecked")
    public ArrayList<ArrayList<Integer>> getArray(ArrayList<Integer> ll, int len) {
        ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
        for (int i = 0; i < len; i++) {
            if (list.size() == 0) {
                for (int j = 0; j < ll.size(); j++) {
                    ArrayList<Integer> temp = new ArrayList<Integer>();
                    temp.add(ll.get(j));
                    list.add(temp);
                }
            } else {
                ArrayList<ArrayList<Integer>> temp = new ArrayList<ArrayList<Integer>>();
                for (ArrayList<Integer> l : list) {
                    for (int m : ll) {
                        ArrayList<Integer> t = (ArrayList<Integer>) l.clone();
                        t.add(m);
                        temp.add(t);
                    }
                }
                list = temp;
            }
        }
        return list;
    }

    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(2);
        list.add(3);
        TestEmu te = new TestEmu();
        ArrayList<ArrayList<Integer>> ll = te.getArray(list, 5);
        for(ArrayList<Integer> l:ll){
            for(int i:l){
                System.out.print(i+" ");
            }
            System.out.println();
        }        
    }

}

 

你可能感兴趣的:(数组)