Skip to content

Commit

Permalink
[COLLECTIONS-858] CartesianProductIterator
Browse files Browse the repository at this point in the history
  • Loading branch information
alexey-pelykh committed Jun 25, 2024
1 parent b20e348 commit a5e554d
Show file tree
Hide file tree
Showing 2 changed files with 216 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.collections4.iterators;

import java.util.*;

/**
* This iterator creates a Cartesian product of the input enumerables,
* equivalent to nested for-loops.
* <p>
* The {@code remove()} operation is not supported, and will throw an
* {@code UnsupportedOperationException}.
*
* @param <E> the type of the objects being permuted
*/
public class CartesianProductIterator<E> implements Iterator<List<E>> {

/**
* The iterables to create the Cartesian product from.
*/
private final List<Iterable<? extends E>> iterables;

/**
* The iterators to generate the Cartesian product tuple from.
*/
private final List<Iterator<? extends E>> iterators;

/**
* The previous generated tuple of elements.
*/
private List<E> previousTuple;

/**
* Standard constructor for this class.
*
* @param iterables the iterables to create the Cartesian product from
* @throws NullPointerException if any of the iterables is null
*/
public CartesianProductIterator(final Iterable<? extends E>... iterables) {
Objects.requireNonNull(iterables, "iterables");
this.iterables = Arrays.asList(iterables);
this.iterators = new ArrayList<>(iterables.length);
for (final Iterable<? extends E> iterable : iterables) {
Objects.requireNonNull(iterable, "iterable");
final Iterator<? extends E> iterator = iterable.iterator();
if (iterator.hasNext()) {
iterators.add(iterator);
} else {
iterators.clear();
break;
}
}
}

/**
* Indicates if there are more tuples to return.
* @return true if there are more tuples, otherwise false
*/
@Override
public boolean hasNext() {
for (final Iterator<? extends E> iterator : iterators) {
if (iterator.hasNext()) {
return true;
}
}
return false;
}

/**
* Returns the next tuple of the input iterables.
* @return a list of the input iterables' elements
* @throws NoSuchElementException if there are no more tuples
*/
@Override
public List<E> next() {
if (!hasNext()) {
throw new NoSuchElementException();
}

if (previousTuple == null) {
final List<E> tuple = new ArrayList<>(iterables.size());
for (final Iterator<? extends E> iterator : iterators) {
tuple.add(iterator.next());
}
previousTuple = tuple;
return new ArrayList<>(tuple);
}

for (
int iteratorIndex = iterators.size() - 1;
iteratorIndex >= 0;
iteratorIndex--
) {
Iterator<? extends E> iterator = iterators.get(iteratorIndex);
if (iterator.hasNext()) {
previousTuple.set(iteratorIndex, iterator.next());
return new ArrayList<>(previousTuple);
}
iterator = iterables.get(iteratorIndex).iterator();
iterators.set(iteratorIndex, iterator);
previousTuple.set(iteratorIndex, iterator.next());
}
return new ArrayList<>(previousTuple);
}

@Override
public void remove() {
throw new UnsupportedOperationException("remove() is not supported");
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.collections4.iterators;

import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

/**
* Test class for CartesianProductIterator.
*/
public class CartesianProductIteratorTest extends AbstractIteratorTest<List<Character>> {

protected List<Character> letters;
protected List<Character> numbers;
protected List<Character> empty;

public CartesianProductIteratorTest() {
super(CartesianProductIteratorTest.class.getSimpleName());
}

@Override
public CartesianProductIterator<Character> makeEmptyIterator() {
return new CartesianProductIterator<>();
}

@Override
public CartesianProductIterator<Character> makeObject() {
return new CartesianProductIterator<>(letters, numbers);
}

@BeforeEach
public void setUp() {
letters = new ArrayList<>();
letters.add('A');
letters.add('B');
letters.add('C');
numbers = new ArrayList<>();
numbers.add('1');
numbers.add('2');
numbers.add('3');
empty = new ArrayList<>();
}

@Override
public boolean supportsRemove() {
return false;
}

@Test
public void testEmptyCollection() {
final CartesianProductIterator<Character> it = new CartesianProductIterator<>(letters, empty);
assertFalse(it.hasNext());
}

/**
* test checking that all the tuples are returned
*/
@Test
public void testCartesianProductExhaustivity() {
final List<List<Character>> resultsList = new ArrayList<>();

final CartesianProductIterator<Character> it = makeObject();
while (it.hasNext()) {
final List<Character> tuple = it.next();
resultsList.add(tuple);
}
assertThrows(NoSuchElementException.class, () -> it.next());
assertEquals(9, resultsList.size());
}

}

0 comments on commit a5e554d

Please sign in to comment.