3737 * manipulate permutations in a variety of ways.
3838 *
3939 * @author <a href=https://www.cicirello.org/ target=_top>Vincent A. Cicirello</a>, <a href=https://www.cicirello.org/ target=_top>https://www.cicirello.org/</a>
40- * @version 1.19.5.20
40+ * @version 6.23.2019
4141 * @since 1.0
4242 */
4343public final class Permutation implements Serializable , Iterable <Permutation >
@@ -176,8 +176,7 @@ private Permutation(int[] p, boolean validate) {
176176 * @param p the given permutation.
177177 */
178178 public Permutation (Permutation p ) {
179- permutation = new int [p .permutation .length ];
180- System .arraycopy (p .permutation , 0 , permutation , 0 , p .permutation .length );
179+ permutation = p .permutation .clone ();
181180 }
182181
183182 /**
@@ -192,14 +191,18 @@ public Permutation(Permutation p) {
192191 * @param length size of new permutation
193192 */
194193 public Permutation (Permutation p , int length ) {
195- if (length > p .permutation .length ) length = p .permutation .length ;
196- else if (length < 0 ) length = 0 ;
197- permutation = new int [length ];
198- int k = 0 ;
199- for (int i = 0 ; i < p .permutation .length && k < length ; i ++) {
200- if (p .permutation [i ] < length ) {
201- permutation [k ] = p .permutation [i ];
202- k ++;
194+ if (length >= p .permutation .length ) {
195+ permutation = p .permutation .clone ();
196+ } else if (length <= 0 ) {
197+ permutation = new int [0 ];
198+ } else {
199+ permutation = new int [length ];
200+ int k = 0 ;
201+ for (int i = 0 ; i < p .permutation .length && k < length ; i ++) {
202+ if (p .permutation [i ] < length ) {
203+ permutation [k ] = p .permutation [i ];
204+ k ++;
205+ }
203206 }
204207 }
205208 }
@@ -567,6 +570,29 @@ public int[] toArray() {
567570 return permutation .clone ();
568571 }
569572
573+ /**
574+ * <p>Generates an array of int values from the interval [0, n) in the same order
575+ * that they occur in this Permutation. The array that is returned is independent of
576+ * the object state (i.e., changes to its contents will not affect the Permutation).</p>
577+ *
578+ * @param array An array to hold the result. If array is null or if array.length is
579+ * not equal to the length of the permutation, then this method will construct a new array
580+ * for the result.
581+ *
582+ * @return an int array containing the Permutation elements in the same order that they appear in
583+ * the Permutation.
584+ *
585+ * @since 1.5
586+ */
587+ public int [] toArray (int [] array ) {
588+ if (array == null || array .length != permutation .length ) {
589+ return permutation .clone ();
590+ } else {
591+ System .arraycopy (permutation , 0 , array , 0 , array .length );
592+ return array ;
593+ }
594+ }
595+
570596 /**
571597 * Retrieves the length of the permutation.
572598 * @return length of the permutation
0 commit comments