Recommended: Sing it, brah! 5 fabulous songs for developers
JW's Top 5
Hi!
I'm new and wanted to show a class i use to randomize arrays.
import java.lang.reflect.Array;
/**
* Free use;
* @author maseljj
*/
public final class Randomizer {
private Randomizer() {
}
/**
* Randomly returnes one of two states: True or false;
* @return boolean;
*/
public static boolean rndState() {
//generate random hash number;
short s = (short) ((int) new Randomizer().hashCode() % 2);
if (s == 1) {
return true;
}
return false;
}
/**
* Returnes random value from input;
* @param fromRange
* @param toRange
* @return random int from to;
*/
public static int getRndValue(int fromRange, int toRange) {
int rndResult = 0;
int mapSize = (toRange - fromRange);
int mapCurrentVal = fromRange;
int rndNmb = 0;
int champion = 0;
for (int i = 0; i <= mapSize; i++) {
rndNmb = new Randomizer().hashCode();
if (!Randomizer.isFirstValGreatest(champion, rndNmb)) {
champion = rndNmb;
rndResult = mapCurrentVal;
}
mapCurrentVal++;
}
return rndResult;
}
/**
* Randomize whole array;
* @param o
* @return randomized array;
*/
public static Object[] rndomizeArray(Object[] o) {
if (o == null) {
return o;
}
int inObjLen = Array.getLength(o);
Object[] retArray = new Object[inObjLen];
boolean[] ocupiedFields = new boolean[inObjLen];
for (int i = 0; i < inObjLen; i++) {
Object tmpO = o[i];
boolean ocupied = true;
int rndVal = 0;
while (ocupied) {
rndVal = Randomizer.getRndValue(0, (inObjLen - 1));
if (!ocupiedFields[rndVal]) {
ocupied = false;
ocupiedFields[rndVal] = true;
}
}
retArray[rndVal] = tmpO;
}
return retArray;
}
/**
* Randomize whole array;
* @param o
* @return randomized array;
*/
public static int[] rndomizeArray(int o[]) {
if (o == null) {
return o;
}
int inObjLen = Array.getLength(o);
int[] retArray = new int[inObjLen];
boolean[] ocupiedFields = new boolean[inObjLen];
for (int i = 0; i < inObjLen; i++) {
int tmpO = o[i];
boolean ocupied = true;
int rndVal = 0;
while (ocupied) {
rndVal = Randomizer.getRndValue(0, (inObjLen - 1));
if (!ocupiedFields[rndVal]) {
ocupied = false;
ocupiedFields[rndVal] = true;
}
}
retArray[rndVal] = tmpO;
}
return retArray;
}
/**
* Returnes random value from array;
* @param o
* @return random array value;
*/
public static Object getRndArrayVal(Object[] o) {
if ((o != null) && (Array.getLength(o) > 0)) {
return o[Randomizer.getRndValue(0, (Array.getLength(o) - 1))];
}
return o;
}
/**
* If first input value is larger than second value, returns true,
* otherweise false;
* @param c1
* @param c2
* @return boolean according to input;
*/
private static boolean isFirstValGreatest(int c1, int c2) {
if (c1 < c2) {
return false;
}
return true;
}
}Comments are welcome. Stay cool.