How to determine value for single cell within cartesian product

Viewed 36

Say I have some set of arrays with variable size, e.g. [a, b, c] and [1, 2]

The cartesian product would be:

[
[a, 1],
[a, 2],
[b, 1],
[b, 2],
[c, 1],
[c, 2]
]

As the number of initial arrays increase the size of the cartesian product quickly gets very large.

Is it possible to figure out what value would be in a given cell (i, j), for any number of initial arrays without having to generate the whole truth table?

(In the truth table above (0, 0) => a, (0, 1) => 1 )

1 Answers

Thanks to @Sebastian and @Damien for answering the question in the comments.

Here's how I implemented the function in Java:

  public static class CartesianValueFactory {
    private final Object[][] dimensions;

    public CartesianValueFactory(Object[][] dimensions) {
      this.dimensions = dimensions;
    }

    public Object valueAt(long row, int column) {
      long index = row;
      for (int nextColumn = column + 1; nextColumn < dimensions.length; nextColumn++) {
        index = index / dimensions[nextColumn].length;
      }
      if (column == 0) {
        return dimensions[column][(int) index];
      } else {
        return dimensions[column][(int) index % dimensions[column].length];
      }
    }
  }

Related