天天看点

java 笛卡尔积_笛卡尔乘积-java代码

好久没摸过程序了,重新捡起java写了个笛卡尔乘积算法。自我感觉非常精简通用,这算是码力不减,码刀不老?

package my.table;

import java.util.Arrays;

public class Descates {

int[] sizes;

int[] indexs;

public Descates(int[] sizes) {

this.sizes = sizes;

this.indexs = new int[sizes.length];

for (int i=0; i

indexs[i] = 0;

}

}

public int[] first() {

for (int i=0; i

int index = indexs[i] ;

int size = sizes[i];

if (index < size) return indexs;

}

return null;

}

public int[] next() {

for (int i = sizes.length-1; i>=0; i--) {

int index = indexs[i] ;

int size = sizes[i];

if (index < size-1) {

indexs[i] ++;

return indexs;

}

indexs[i] = 0;

}

return null;

}

public static void main(String args[]) {

int x[] = { 2, 2, 3};

System.out.println(Arrays.toString(x));

System.out.println("===========");

Descates it = new Descates(x);

int y[] = it.first();

while (y != null) {

System.out.println(Arrays.toString(y));

y = it.next();

}

}

}

测试结果:

[2, 2, 3]

===========

[0, 0, 0]

[0, 0, 1]

[0, 0, 2]

[0, 1, 0]

[0, 1, 1]

[0, 1, 2]

[1, 0, 0]

[1, 0, 1]

[1, 0, 2]

[1, 1, 0]

[1, 1, 1]

[1, 1, 2]