@@ -105,6 +105,8 @@ public Permutation(int n, int value) {
105105 /**
106106 * Initializes a permutation of n integers to be identical to the elements of an array.
107107 * @param p An array of integers. Each of the integers in the interval [0, p.length) must occur exactly one time each.
108+ * @throws IllegalArgumentException if p either contains duplicates, or contains any negative elements,
109+ * or contains any elements equal or greater than p.length.
108110 */
109111 public Permutation (int [] p ) {
110112 boolean [] inP = new boolean [p .length ];
@@ -127,16 +129,27 @@ public Permutation(Permutation p) {
127129 }
128130
129131 /**
130- * Initializes a permutation of integers to be identical to a subset of a given
131- * permutation. Note: if the desired length is less than the source permutation,
132- * then the resulting permutation will not contain all of the integers in [0,n).
133- * @param p the given permutation.
134- * @param length size of sub-permutation
132+ * Initializes a permutation of the integers in the interval [0, length) based on their relative order
133+ * in a permutation p. If length is greater than or equal to p.length, then this constructor generates a copy of p.
134+ * If length is less than p.length, then the new permutation contains the integers, 0, 1, 2, ..., (length - 1), in the
135+ * order that those elements appear in p. For example, if p is the permutation [ 5, 3, 7, 2, 6, 1, 0, 8, 4] and if length
136+ * is 4, this constructor will generate the permutation [3, 2, 1, 0] since 3 appears prior to 2, 2 appears prior to 1, and 1
137+ * appears prior to 0 in permutation p.
138+ *
139+ * @param p the source permutation.
140+ * @param length size of new permutation
135141 */
136142 public Permutation (Permutation p , int length ) {
137143 if (length > p .permutation .length ) length = p .permutation .length ;
144+ else if (length < 0 ) length = 0 ;
138145 permutation = new int [length ];
139- System .arraycopy (p .permutation , 0 , permutation , 0 , length );
146+ int k = 0 ;
147+ for (int i = 0 ; i < p .permutation .length && k < length ; i ++) {
148+ if (p .permutation [i ] < length ) {
149+ permutation [k ] = p .permutation [i ];
150+ k ++;
151+ }
152+ }
140153 }
141154
142155
0 commit comments