Random numbers without repetition of numbers in jsp or servlet?

1 answer

Answer

1021751

2026-04-12 05:00

+ Follow

The normal way of "generating" random numbers without repetition is to first define an array of all possible values, and then to randomize their order. You can then iterate over the array to get your "random" values.

// Returns an array containing the values in the range [start, end] in a random order.

static int[] getRandom(final int start, final int end) {

final int[] nums = new int[end - start + 1];

// Fill array

for (int i = 0; i < nums.length; ++i) {

nums[i] = start + i;

}

// Shuffle array

final Random rnd = new Random(System.currentTimeMillis());

for (int i = nums.length - 1; i > 0; --i) {

// Generate an index to swap with...

final int swapIndex = rnd.nextInt(i + 1);

// ...and swap

final int temp = nums[i];

nums[i] = nums[swapIndex];

nums[swapIndex] = temp;

}

return nums;

}

ReportLike(0ShareFavorite

Related Questions

Copyright © 2026 eLLeNow.com All Rights Reserved.