To implement a random lottery in Java, we usually use theclass to generate random numbers and then select winners based on those random numbers. Several common implementations of random draws are given below, including drawing from arrays, drawing from lists, and weight-based draws.
1. Drawing from an array
import ;
public class LotteryFromArray {
public static void main(String[] args) {
String[] candidates = {"Alice", "Bob", "Charlie", "David", "Eva"};
Random random = new Random();
// Generate a0until (a time)-1Random numbers between
int index = ();
// Output Winners
("The winner is:" + candidates[index]);
}
}
2. Extraction from the list
utilizationArrayList
maybeLinkedList
Collection classes such as this can also be implemented for raffles, especially when candidates need to be added or removed dynamically.
import ;
import ;
import ;
public class LotteryFromList {
public static void main(String[] args) {
List<String> candidates = new ArrayList<>();
("Alice");
("Bob");
("Charlie");
("David");
("Eva");
Random random = new Random();
// Generate a0until (a time)()-1Random numbers between
int index = (());
// Output Winners
("The winner is:" + (index));
}
}
3. Weight-based lottery
In some cases, each candidate may have a different probability of winning the lottery, which requires the implementation of a weight-based lottery.
import ;
import ;
import ;
public class LotteryWithWeights {
static class Candidate {
String name;
int weight; // weights
public Candidate(String name, int weight) {
= name;
= weight;
}
}
public static void main(String[] args) {
List<Candidate> candidates = new ArrayList<>();
(new Candidate("Alice", 1));
(new Candidate("Bob", 3));
(new Candidate("Charlie", 1));
(new Candidate("David", 2));
(new Candidate("Eva", 3));
Random random = new Random();
int totalWeight = 0;
for (Candidate candidate : candidates) {
totalWeight += ;
}
int target = (totalWeight) + 1;
int sum = 0;
for (Candidate candidate : candidates) {
sum += ;
if (sum >= target) {
("The winner is:" + );
break;
}
}
}
}
In the weight-based lottery example above, we define aCandidate
class to store the names and weights of the candidates. The winner is then determined by accumulating the weights and generating a random number. Note that here we pass the(totalWeight) + 1
to ensure that the generated random number is between 1 and the total weight (inclusive), thus avoiding problems caused by 0 values. Finally, the first candidate greater than or equal to the random number is found as the winner by traversing the list of candidates and accumulating the weights.
The above three methods are applicable to different scenarios, so you can choose to use them according to the actual needs.