Skip to content

Instantly share code, notes, and snippets.

@truongngoclinh
Last active December 25, 2015 10:47
Show Gist options
  • Save truongngoclinh/ee1ea2e21907b99dcf15 to your computer and use it in GitHub Desktop.
Save truongngoclinh/ee1ea2e21907b99dcf15 to your computer and use it in GitHub Desktop.
Random value from 0 to MAX
/**
* Make an int random array with value from 0 to max
* @param size: size = max + 1
* @return result: an int array
*/
private int[] makeRandomArray(int size) {
int result[] = new int[size];
List<Integer> ascesdingArray = new ArrayList<>();
for (int i = 0; i < size; i++) {
ascesdingArray.add(i);
}
for (int i = 0; i < size; i++) {
int randomValue = random(ascesdingArray);
result[i] = randomValue;
}
return result;
}
/**
* Get random value in input array
* @param ascesdingArray
* @return randomValue: random element from input array
*/
private int random(List<Integer> ascesdingArray) {
int max = ascesdingArray.size() - 1;
int randomValue = 0;
if (max > 0) {
// get random index and it's value
int index = new Random().nextInt(max);
randomValue = ascesdingArray.get(index);
// remove value got from array so it will not be duplicated
ascesdingArray.remove(index);
} else if (max == 0) {
randomValue = ascesdingArray.get(0);
}
return randomValue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment