/*
* 网上看到一道题,挺有意思。记录下来。
*/
package array;
public class RandomArray<T> {
private T[] array;
private Object[] result;
private Integer count = 0;
private T[] getArray() {
return array;
}
private void setArray(T[] array) {
this.array = array;
Integer size = 1;
for (Integer i = array.length; i >= 1; i --) {
size *= i;
}
System.out.println("result size = " + size);
this.result = new Object[size];
}
private Object[] getResult() {
return result;
}
private void putElementToResult(T[] array) {
result[count] = array;
}
private RandomArray (T[] array) {
this.setArray(array);
}
private void exchange (Integer originalIndex, Integer destinationIndex) {
if (originalIndex.compareTo(destinationIndex) == 0) {
return;
}
T[] array = this.getArray();
T temp = array[originalIndex];
array[originalIndex] = array[destinationIndex];
array[destinationIndex] = temp;
}
private Object[] copyArray(T[] array) {
Object[] objs = new Object[array.length];
for (Integer i = 0; i < array.length; i++) {
objs[i] = array[i];
}
return objs;
}
private void arrayHandler (Integer startIndex, Integer endIndex) {
if (startIndex.compareTo(endIndex) != 0) {
for(Integer i = startIndex; i <= endIndex; i ++ ) {
exchange(startIndex, i);
arrayHandler(startIndex + 1, endIndex);
exchange(i, startIndex);
}
} else {
@SuppressWarnings("unchecked")
T[] param = (T[]) copyArray(array);
this.putElementToResult(param);
this.count ++;
}
}
private Integer getRandomNumber() {
Integer countLength = count.toString().length();
while(true) {
Long currentMillis = System.currentTimeMillis();
String compareVal = currentMillis.toString().substring(currentMillis.toString().length() - countLength);
Integer number = getValidNumber(compareVal);
if (number <= count) {
return number;
}
}
}
private Integer getValidNumber(String compareVal) {
if ("0".equals(compareVal)) {
return 0;
} else if(compareVal.startsWith("0")) {
compareVal = compareVal.replaceFirst("0", "");
return getValidNumber(compareVal);
} else {
return Integer.valueOf(compareVal);
}
}
@SuppressWarnings("unchecked")
private T[] convertObjectArrayToGenericArray(Object[] data, T[] container) {
for(Integer i = 0; i < data.length; i ++) {
container[i] = (T) data[i];
}
return container;
}
public T[] getRandomArray(T[] container) {
arrayHandler(0,this.getArray().length - 1);
Object[] _this = this.getResult();
Integer indexNumber = getRandomNumber();
Object[] objs = (Object[]) _this[indexNumber];
return convertObjectArrayToGenericArray(objs, container);
}
public static void main(String[] args) {
/*
*test
*/
String[] array = {"1","2","3"};
RandomArray<String> ran = new RandomArray<String>(array);
String[] randomArray = ran.getRandomArray(new String[3]);
for (String str: randomArray) {
System.out.print(str + " ");
}
}
}