Generating Random Numbers with Weights in Java

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:

Here is the 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.");
    }
}
  • Weights: Each item is assigned a weight. Higher weights mean the item is more likely to be selected.
  • Total Weight: Sum of all weights is calculated.
  • Random Value: A random number is generated between 0 and the total weight.
  • Selection: The method iterates through the items and subtracts their weights from the random value until it finds the selected item.

 

admin

Share
Published by
admin
Tags: java

Recent Posts

Build Simple Water System Calculator in Java Using Swing

If you're just beginning to learn Java GUI programming creating an Water System Calculator is a fantastic project for…

1 week ago

GitHub Copilot vs Microsoft Copilot Best AI Tool to Use in 2025

GitHub is a powerful tool used by teams and developers around the globe. This guide is…

2 weeks ago

Chat with Claude AI Free – Your Super-Smart AI Buddy

It's like having a super-smart buddy that is always there to help you write stories,…

3 weeks ago

Best Festivals UK 2025 [Free Guide Included]

The UK is known for its rich history, diverse culture, and most of all  its…

3 weeks ago

Bank Holidays 2025 UK – Plan Your Perfect Long Weekends

Do you have a plan for your next holiday? Being aware of the Bank Holidays within the…

3 weeks ago

Master Cursor AI Full Guide for Students & Creators

The world is rapidly changing of software development AI-assisted tools for coding have become the main focus. As…

3 weeks ago