我以前写过的代码,类似于这个希望对你有用,只需稍加改动一下。
java实现:从8个数中任取5个数,打印出所有组合结果。
for循环部分应该是用方法封装的,但是有些繁琐,就没去写了,
public static void main(String[] args) {
int [] ran = new int[8];
for (int i = 0; i < ran.length; i++)
{ ran[i]=i+1; }
Random random = new Random();
int loop = 5;
int[] save = new int[5];
int rc = 0;
while (loop > 0)
{ //随即抽取数组下标 int index = random.nextInt(ran.length);
int r = ran[index];
save[rc++] = r;
ran = remove(ran, r); loop--; } //随即选的5个数
for (int i = 0; i < save.length; i++)
{ System.out.print(save[i]+","); }
System.out.println("");
int count = 5*4*3*2;
String [] num = new String[count];
label: for (int i = 0; i < save.length; i++)
{ int [] a =remove(save, save[i]);
for (int j = 0; j < a.length; j++)
{ int [] b =remove(a, a[j]);
for (int k = 0; k < b.length; k++)
{ int [] c =remove(b, b[k]);
for (int m = 0; m < c.length; m++)
{ int [] d =remove(c, c[m]);
for (int n = 0; n < d.length; n++)
{ num[--count] = save[i]+""+a[j]+ ""+b[k]+""+c[m]+""+d[n];
if (count==0)
{ break; } } } } } }
for (int i = 0; i < num.length; i++)
{ if (!num[i].equals("")) { System.out.println(num[i]); } } } //去除已经产生的数,赋给新数组
static int[] remove (int[] n,int r){ int []m = new int[n.length-1];
for (int i = 0, k = 0; i < n.length; i++, k++) { if (n[i] != r) { m[k] = n[i]; } else { k--; } } return m; } |