001
014
015 package com.liferay.portal.kernel.security;
016
017 import java.util.Random;
018
019
022 public class RandomUtil {
023
024 public static int nextInt(int n) {
025 return random.nextInt(n);
026 }
027
028 public static int[] nextInts(int n, int size) {
029 if (size > n) {
030 size = n;
031 }
032
033 int[] numbers = new int[n];
034
035 for (int i = 0; i < n; i++) {
036 numbers[i] = i;
037 }
038
039 shuffle(random, numbers);
040
041 if (size == n) {
042 return numbers;
043 }
044
045 int[] results = new int[size];
046
047 System.arraycopy(numbers, 0, results, 0, size);
048
049 return results;
050 }
051
052 public static void shuffle(Random random, int[] numbers) {
053 for (int i = numbers.length; i > 1; i--) {
054 int position = random.nextInt(i);
055
056 if (position != (i - 1)) {
057 int number = numbers[position];
058
059 numbers[position] = numbers[i - 1];
060 numbers[i - 1] = number;
061 }
062 }
063 }
064
065 public static String shuffle(Random random, String s) {
066 StringBuilder sb = new StringBuilder(s);
067
068 shuffle(random, sb);
069
070 return sb.toString();
071 }
072
073 public static void shuffle(Random random, StringBuilder sb) {
074 for (int i = sb.length(); i > 1; i--) {
075 int position = random.nextInt(i);
076
077 if (position != (i - 1)) {
078 char c = sb.charAt(position);
079
080 sb.setCharAt(position, sb.charAt(i - 1));
081 sb.setCharAt(i - 1, c);
082 }
083 }
084 }
085
086 public static String shuffle(String s) {
087 return shuffle(random, s);
088 }
089
090 protected static Random random = new Random();
091
092 }