01 /*
02 * Java Genetic Algorithm Library (jenetics-3.5.0).
03 * Copyright (c) 2007-2016 Franz Wilhelmstötter
04 *
05 * Licensed under the Apache License, Version 2.0 (the "License");
06 * you may not use this file except in compliance with the License.
07 * You may obtain a copy of the License at
08 *
09 * http://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 * Author:
18 * Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
19 */
20 package org.jenetics.internal.util;
21
22 import java.util.Random;
23
24 import org.jenetics.util.RandomRegistry;
25
26 /**
27 * Helper class which contains array helper methods.
28 *
29 * @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
30 * @since 3.0
31 * @version 3.0
32 */
33 public final class array {
34 private array() {require.noInstance();}
35
36 public static void swap(final int[] array, final int i, final int j) {
37 final int temp = array[i];
38 array[i] = array[j];
39 array[j] = temp;
40 }
41
42 public static void swap(final double[] array, final int i, final int j) {
43 final double temp = array[i];
44 array[i] = array[j];
45 array[j] = temp;
46 }
47
48 public static int[] revert(final int[] array) {
49 for (int i = 0, j = array.length - 1; i < j; ++i, --j) {
50 swap(array, i, j);
51 }
52
53 return array;
54 }
55
56 public static double[] revert(final double[] array) {
57 for (int i = 0, j = array.length - 1; i < j; ++i, --j) {
58 swap(array, i, j);
59 }
60
61 return array;
62 }
63
64 /**
65 * Randomize the {@code array} using the given {@link Random} object. The used
66 * shuffling algorithm is from D. Knuth TAOCP, Seminumerical Algorithms,
67 * Third edition, page 142, Algorithm S (Selection sampling technique).
68 *
69 * @param array the array to shuffle
70 * @param random the PRNG
71 */
72 public static double[] shuffle(final double[] array, final Random random) {
73 for (int j = array.length - 1; j > 0; --j) {
74 swap(array, j, random.nextInt(j + 1));
75 }
76 return array;
77 }
78
79 public static double[] shuffle(final double[] array) {
80 return shuffle(array, RandomRegistry.getRandom());
81 }
82
83 public static int[] shuffle(final int[] array, final Random random) {
84 for (int j = array.length - 1; j > 0; --j) {
85 swap(array, j, random.nextInt(j + 1));
86 }
87 return array;
88 }
89
90 public static int[] shuffle(final int[] array) {
91 return shuffle(array, RandomRegistry.getRandom());
92 }
93
94 }
|