0

I'm creating a random book catalogue in Java and I intend to split a randomly generated price value of a book package into TWO separate values (representing the individual packages for two books).

For eg. A randomly generated book package 42 costs $80 and the individual prices of the two books in that package cost $X and $Y. Here's an excerpt of my code:

public class MultiAgent {

int maxBookID = 50;
int maxBookPrice = 100;
int maxNumItems = 50;

void buildCatalogue() {

    int numItems = rand.nextInt(maxNumItems);
    while (bookCatalogue.size() < numItems) {
        int ranID = rand.nextInt(maxBookID);
        bookCatalogue.put(String.valueOf(ranID), rand.nextInt(maxBookPrice));

    }

    for (Object key : bookCatalogue.keySet()) {

System.out.println("Package ID: " + (String) key + "; price value: " + bookCatalogue.get(key)); //The individual values of the two books should print here
    }

}
}

How do I split the generated price value into two random values?

Azaan
  • 25
  • 1
  • 1
  • 5

1 Answers1

3

Generate a random float between 0.0 and 1.0:

float r = rand.nextFloat();

Use that to split your value:

float priceBook1 = packagePrice * r;
float priceBook2 = packagePrice * (1-r);

Example / explanation

Let's say packagePrice is 100 and r ends up being 0.4:

priceBook1 = 100 * 0.4;      // 40
priceBook2 = 100 * (1-0.4);  // 60 

Note, however, that one of the books could end up costing nothing (in the case of r being 0.0). If you want to prevent that, just check out one of the several available questions/answers to the problem, for example "Generating a random double number of a certain range in Java".

Community
  • 1
  • 1
domsson
  • 4,553
  • 2
  • 22
  • 40
  • But in this case, I have bookCatalogue.get(key) representing as my randomised package price value, how do I go with that? The value is an object. – Azaan Apr 17 '17 at 01:37
  • 1
    @Azaan The general strategy in this answer should work for you. Your code isn't completely clear. – Tim Biegeleisen Apr 17 '17 at 01:45
  • If your package price is in `bookCatalogue.get(key)`, then just replace `packagePrice` with that. As @TimBiegeleisen pointed out: I gave you somewhat of a general recipe, you should be able to adapt that to your specific case. – domsson Apr 17 '17 at 01:55
  • No worries, I got it. Thank you so much! – Azaan Apr 17 '17 at 01:55