Skip to content

Instantly share code, notes, and snippets.

@suzuki-hoge
Created March 21, 2018 12:36
Show Gist options
  • Save suzuki-hoge/8d8111270a6d24948787577c4e735dc6 to your computer and use it in GitHub Desktop.
Save suzuki-hoge/8d8111270a6d24948787577c4e735dc6 to your computer and use it in GitHub Desktop.
直積
@ToString(includeFieldNames = false)
@AllArgsConstructor
public class Cartesian<T> {
private final List<List<T>> selfTss;
public static <T> Cartesian of(List<T> ts) {
return new Cartesian<>(ts.stream().map(Collections::singletonList).collect(toList()));
}
public Cartesian multiply(List<T> ts) {
return new Cartesian<>(
selfTss.stream().flatMap(
selfTs -> ts.stream().map(t -> add(selfTs, t))
).collect(toList())
);
}
public List<List<T>> asList() {
return selfTss;
}
private static <T> List<T> add(List<T> ts, T t) {
return concat(ts.stream(), Stream.of(t)).collect(toList());
}
}
class CartesianTest extends Specification {
def test() {
expect:
def case1 = Cartesian.of([1, 2]) * [3, 4]
case1.asList() == [
[1, 3],
[1, 4],
[2, 3],
[2, 4]
]
def case2 = Cartesian.of([1, 2]) * [3, 4] * [5, 6]
case2.asList() == [
[1, 3, 5],
[1, 3, 6],
[1, 4, 5],
[1, 4, 6],
[2, 3, 5],
[2, 3, 6],
[2, 4, 5],
[2, 4, 6]
]
def case3 = Cartesian.of([1]) * [2, 3]
case3.asList() == [
[1, 2],
[1, 3]
]
def case4 = Cartesian.of([1, 2]) * [3]
case4.asList() == [
[1, 3],
[2, 3]
]
def case5 = Cartesian.of([1]) * [2]
case5.asList() == [
[1, 2]
]
def case6 = Cartesian.of([1]) * []
case6.asList() == [
]
def case7 = Cartesian.of([]) * [1]
case7.asList() == [
]
def case8 = Cartesian.of([]) * []
case8.asList() == [
]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment