Random number generation with weighted probabilities is a common requirement in various programming scenarios, such as game development, statistical sampling, and machine learning algorithms. Java provides several approaches to accomplish this task efficiently.
in this tutorial To generate random values with weights in Java, you can use a weighted random selection technique. Here’s a simple example:
import java.util.HashMap; import java.util.Map; import java.util.Random; public class Ex1 { public static void main(String[] args) { // Define items and their weights Map<String, Integer> items = new HashMap<>(); items.put("Apple", 5); // Weight for Apple items.put("Banana", 1); // Weight for Banana items.put("Cherry", 3); // Weight for Cherry // Generate weighted random selections for (int i = 0; i < 10; i++) { String randomItem = getRandomItem(items); System.out.println(randomItem); } } public static String getRandomItem(Map<String, Integer> items) { // Calculate the total weight int totalWeight = items.values().stream().mapToInt(Integer::intValue).sum(); // Generate a random number in the range of 0 to totalWeight int randomValue = new Random().nextInt(totalWeight); // Iterate through the items and subtract weights to find the selected item for (Map.Entry<String, Integer> entry : items.entrySet()) { randomValue -= entry.getValue(); if (randomValue < 0) { return entry.getKey(); } } throw new RuntimeException("Should never reach here if weights are correctly defined."); } }
Introduction In this section, we will guide you step by step in the development of an image upload registration system in Java using MySQL and JDBC. In the application, users register…
The Touchable Shop POS (Point of Sale) system is a sophisticated software solution developed using…
Creating a responsive login form is a crucial skill for any web developer. In this…
In this tutorial will teach Laravel 12 CRUD API by step. Laravel 10 CRUD Application …
In this lesson we talk about laravel 12 image uploading and display the image step…
In this tutorial will teach Laravel 12 CRUD Application step by step. Laravel 12 CRUD…