Cartesian product: java code

created at 07-09-2021 views: 1

I haven't touched the program for a long time, and picked up Java again and wrote a Cartesian product algorithm. I feel very streamlined and universal. Here is the code:

code

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<sizes.length; i++) {
            indexs[i] = 0;
        }       
    }

    public int[] first() {
        for (int i=0; i<sizes.length; 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();
        }
    }
}

Test Results

[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]
Please log in to leave a comment.