Home Java Java Console Application Projects How to generate random with weight java

How to generate random with weight java

3 min read
0
0
5

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.

 

Load More Related Articles
Load More By admin
  • Banking Application FD Rate Calculation using Java

    In this tutorials i am to teach Banking Application FD Rate Calculation using Java. Input …
  • Java Scanner Class

    Scanner class in use to read the input from the user. nextLine() method which used read li…
  • Scanner class in Java

    Scanner class in java which is assume to input the data and read the data. Example  1…
Load More In Java Console Application Projects

Leave a Reply

Your email address will not be published. Required fields are marked *

Check Also

Is Java Hard to Learn?

Is Java Hard to Learn is it True? Java is one of the most popular programming languages in…