View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  /*
19   * This is not the original file distributed by the Apache Software Foundation
20   * It has been modified by the Hipparchus project
21   */
22  package org.hipparchus.util;
23  
24  import org.hipparchus.exception.MathIllegalArgumentException;
25  import org.junit.jupiter.api.Test;
26  
27  import java.lang.reflect.Constructor;
28  import java.lang.reflect.InvocationTargetException;
29  import java.lang.reflect.Method;
30  import java.util.Comparator;
31  import java.util.Iterator;
32  import java.util.NoSuchElementException;
33  
34  import static org.junit.jupiter.api.Assertions.assertEquals;
35  import static org.junit.jupiter.api.Assertions.assertFalse;
36  import static org.junit.jupiter.api.Assertions.assertInstanceOf;
37  import static org.junit.jupiter.api.Assertions.assertThrows;
38  import static org.junit.jupiter.api.Assertions.assertTrue;
39  import static org.junit.jupiter.api.Assertions.fail;
40  
41  /**
42   * Tests for the {@link Combinations} class.
43   */
44  class CombinationsTest {
45      @Test
46      void testAccessor1() {
47          final int n = 5;
48          final int k = 3;
49          assertEquals(n, new Combinations(n, k).getN());
50      }
51  
52      @Test
53      void testAccessor2() {
54          final int n = 5;
55          final int k = 3;
56          assertEquals(k, new Combinations(n, k).getK());
57      }
58  
59      @Test
60      void testLexicographicIterator() {
61          checkLexicographicIterator(new Combinations(5, 3));
62          checkLexicographicIterator(new Combinations(6, 4));
63          checkLexicographicIterator(new Combinations(8, 2));
64          checkLexicographicIterator(new Combinations(6, 1));
65          checkLexicographicIterator(new Combinations(3, 3));
66          checkLexicographicIterator(new Combinations(1, 1));
67          checkLexicographicIterator(new Combinations(1, 0));
68          checkLexicographicIterator(new Combinations(0, 0));
69          checkLexicographicIterator(new Combinations(4, 2));
70          checkLexicographicIterator(new Combinations(123, 2));
71      }
72  
73      @Test
74      void testLexicographicComparatorWrongIterate1() {
75          assertThrows(MathIllegalArgumentException.class, () -> {
76              final int n = 5;
77              final int k = 3;
78              final Comparator<int[]> comp = new Combinations(n, k).comparator();
79              comp.compare(new int[]{1}, new int[]{0, 1, 2});
80          });
81      }
82  
83      @Test
84      void testLexicographicComparatorWrongIterate2() {
85          assertThrows(MathIllegalArgumentException.class, () -> {
86              final int n = 5;
87              final int k = 3;
88              final Comparator<int[]> comp = new Combinations(n, k).comparator();
89              comp.compare(new int[]{0, 1, 2}, new int[]{0, 1, 2, 3});
90          });
91      }
92  
93      @Test
94      void testLexicographicComparatorWrongIterate3() {
95          assertThrows(MathIllegalArgumentException.class, () -> {
96              final int n = 5;
97              final int k = 3;
98              final Comparator<int[]> comp = new Combinations(n, k).comparator();
99              comp.compare(new int[]{1, 2, 5}, new int[]{0, 1, 2});
100         });
101     }
102 
103     @Test
104     void testLexicographicComparatorWrongIterate4() {
105         assertThrows(MathIllegalArgumentException.class, () -> {
106             final int n = 5;
107             final int k = 3;
108             final Comparator<int[]> comp = new Combinations(n, k).comparator();
109             comp.compare(new int[]{1, 2, 4}, new int[]{-1, 1, 2});
110         });
111     }
112 
113     @Test
114     void testLexicographicComparator() {
115         final int n = 5;
116         final int k = 3;
117         final Comparator<int[]> comp = new Combinations(n, k).comparator();
118         assertEquals(1, comp.compare(new int[] {1, 2, 4},
119                                             new int[] {1, 2, 3}));
120         assertEquals(-1, comp.compare(new int[] {0, 1, 4},
121                                              new int[] {0, 2, 4}));
122         assertEquals(0, comp.compare(new int[] {1, 3, 4},
123                                             new int[] {1, 3, 4}));
124     }
125 
126     /**
127      * Check that iterates can be passed unsorted.
128      */
129     @Test
130     void testLexicographicComparatorUnsorted() {
131         final int n = 5;
132         final int k = 3;
133         final Comparator<int[]> comp = new Combinations(n, k).comparator();
134         assertEquals(1, comp.compare(new int[] {1, 4, 2},
135                                             new int[] {1, 3, 2}));
136         assertEquals(-1, comp.compare(new int[] {0, 4, 1},
137                                              new int[] {0, 4, 2}));
138         assertEquals(0, comp.compare(new int[] {1, 4, 3},
139                                             new int[] {1, 3, 4}));
140     }
141 
142     @Test
143     void testEmptyCombination() {
144         final Iterator<int[]> iter = new Combinations(12345, 0).iterator();
145         assertTrue(iter.hasNext());
146         final int[] c = iter.next();
147         assertEquals(0, c.length);
148         assertFalse(iter.hasNext());
149     }
150 
151     @Test
152     void testFullSetCombination() {
153         final int n = 67;
154         final Iterator<int[]> iter = new Combinations(n, n).iterator();
155         assertTrue(iter.hasNext());
156         final int[] c = iter.next();
157         assertEquals(n, c.length);
158 
159         for (int i = 0; i < n; i++) {
160             assertEquals(i, c[i]);
161         }
162 
163         assertFalse(iter.hasNext());
164     }
165 
166     /**
167      * Verifies that the iterator generates a lexicographically
168      * increasing sequence of b(n,k) arrays, each having length k
169      * and each array itself increasing.
170      *
171      * @param c Combinations.
172      */
173     private void checkLexicographicIterator(Combinations c) {
174         final Comparator<int[]> comp = c.comparator();
175         final int n = c.getN();
176         final int k = c.getK();
177 
178         int[] lastIterate = null;
179 
180         long numIterates = 0;
181         for (int[] iterate : c) {
182             assertEquals(k, iterate.length);
183 
184             // Check that the sequence of iterates is ordered.
185             if (lastIterate != null) {
186                 assertEquals(1, comp.compare(iterate, lastIterate));
187             }
188 
189             // Check that each iterate is ordered.
190             for (int i = 1; i < iterate.length; i++) {
191                 assertTrue(iterate[i] > iterate[i - 1]);
192             }
193 
194             lastIterate = iterate;
195             ++numIterates;
196         }
197 
198         // Check the number of iterates.
199         assertEquals(CombinatoricsUtils.binomialCoefficient(n, k),
200                             numIterates);
201     }
202 
203     @Test
204     void testCombinationsIteratorFail() {
205         try {
206             new Combinations(4, 5).iterator();
207             fail("expecting MathIllegalArgumentException");
208         } catch (MathIllegalArgumentException ex) {
209             // ignored
210         }
211 
212         try {
213             new Combinations(-1, -2).iterator();
214             fail("expecting MathIllegalArgumentException");
215         } catch (MathIllegalArgumentException ex) {
216             // ignored
217         }
218     }
219 
220     @Test
221     void testLexicographicIteratorUnreachable() {
222         // this tests things that could really never happen,
223         // as the conditions are tested in the enclosing class before
224         // the lexicographic iterator is built
225         try {
226             Class<?> lexicographicIteratorClass = null;
227             for (Class<?> c : Combinations.class.getDeclaredClasses()) {
228                 if (c.getCanonicalName().endsWith(".LexicographicIterator")) {
229                     lexicographicIteratorClass = c;
230                 }
231             }
232             Constructor<?> ctr = lexicographicIteratorClass.getDeclaredConstructor(Integer.TYPE, Integer.TYPE);
233             Method hasNext = lexicographicIteratorClass.getDeclaredMethod("hasNext");
234             Method next = lexicographicIteratorClass.getDeclaredMethod("next");
235             Method remove = lexicographicIteratorClass.getDeclaredMethod("remove");
236             assertFalse((Boolean) hasNext.invoke(ctr.newInstance(3, 0)));
237             assertFalse((Boolean) hasNext.invoke(ctr.newInstance(3, 3)));
238             assertTrue((Boolean) hasNext.invoke(ctr.newInstance(3, 2)));
239             try {
240                 next.invoke(ctr.newInstance(3, 0));
241                 fail("an exception should have been thrown");
242             } catch (InvocationTargetException ite) {
243                 assertInstanceOf(NoSuchElementException.class, ite.getCause());
244             }
245             try {
246                 remove.invoke(ctr.newInstance(3, 2));
247                 fail("an exception should have been thrown");
248             } catch (InvocationTargetException ite) {
249                 assertInstanceOf(UnsupportedOperationException.class, ite.getCause());
250             }
251         } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException |
252                  InvocationTargetException | InstantiationException e) {
253             fail(e.getLocalizedMessage());
254         }
255     }
256 
257     @Test
258     void testSingletonIteratorUnreachable() {
259         // this tests things that could really never happen,
260         try {
261             Class<?> singletonIteratorClass = null;
262             for (Class<?> c : Combinations.class.getDeclaredClasses()) {
263                 if (c.getCanonicalName().endsWith(".SingletonIterator")) {
264                     singletonIteratorClass = c;
265                 }
266             }
267             Constructor<?> ctr = singletonIteratorClass.getDeclaredConstructor(Integer.TYPE);
268             Method hasNext = singletonIteratorClass.getDeclaredMethod("hasNext");
269             Method next = singletonIteratorClass.getDeclaredMethod("next");
270             Method remove = singletonIteratorClass.getDeclaredMethod("remove");
271             Object iterator = ctr.newInstance(3);
272             assertTrue((Boolean) hasNext.invoke(iterator));
273             int[] ret = (int[]) next.invoke(iterator);
274             assertEquals(3, ret.length);
275             assertEquals(0, ret[0]);
276             assertEquals(1, ret[1]);
277             assertEquals(2, ret[2]);
278             assertFalse((Boolean) hasNext.invoke(iterator));
279             try {
280                 next.invoke(iterator);
281                 fail("an exception should have been thrown");
282             } catch (InvocationTargetException ite) {
283                 assertInstanceOf(NoSuchElementException.class, ite.getCause());
284             }
285             try {
286                 remove.invoke(iterator);
287                 fail("an exception should have been thrown");
288             } catch (InvocationTargetException ite) {
289                 assertInstanceOf(UnsupportedOperationException.class, ite.getCause());
290             }
291         } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException |
292                  InvocationTargetException | InstantiationException e) {
293             fail(e.getLocalizedMessage());
294         }
295     }
296 
297 }