User Name
Password
AppleNova Forums » Programmer's Nook »

Generate value based on the relative percentage of other values (Java)


Register Members List Calendar Search FAQ Posting Guidelines
Generate value based on the relative percentage of other values (Java)
Thread Tools
Kraetos
Lovable Bastard
 
Join Date: Dec 2005
Location: Boston-ish
 
2009-10-04, 13:45

Sorry about the vague/awkward thread title, but I didn't know how else to put it.

Basically, I need a method that takes in three values and then returns a value, which it calculates based on the relative percentages of the other values.

For a simple example, say it's going to generate either A, B, or C. The amount of A is 25, the amount of B is 30, and the amount of C is 55, so the method needs to return A 25 percent of the time, B 30 percent of the time, and C 55 percent of the time.

I feel like it's a pretty simple algorithm but I'm having trouble with it. Any advice?

Logic, logic, logic. Logic is the beginning of wisdom, Valeris, not the end.

Last edited by Kraetos : 2009-10-04 at 16:37.
  quote
Dave
Ninja Editor
 
Join Date: May 2004
Location: Bay Area, CA
 
2009-10-04, 14:02

In C, not Java, and assuming A, B, and C are ints...
Code:
int foo(int a, int b, int c) { float total = a + b + c; float aThreshold = a / total; float bThreshold = aThreshold + (b / total); float n = rand() / RAND_MAX; //don't know what this constant is called in Java if(n <= aThreshold) return a; if(n <= bThreshold) return b; return c; }
Test it to make sure the algorithm is correct before using it. I'm tired and not thinking straight.
  quote
Partial
Stallion
 
Join Date: Feb 2006
Location: Milwaukee
 
2009-10-04, 16:54

Generate a random number less than 100. If it's 0-rangeA, return A, else if rangeA+1 to RangeB, return B, else C. The 100 is just to make percentages easy.

...and calling/e-mailing/texting ex-girlfriends on the off-chance they'll invite you over for some "old time's sake" no-strings couch gymnastics...
  quote
Kraetos
Lovable Bastard
 
Join Date: Dec 2005
Location: Boston-ish
 
2009-10-04, 18:33

I figured it was something along these lines, but I thought there might be a better way to do it.

Here's the completed code:

Code:
public int runEvent() { double total = predators + competitors + food; double pThreshold = predators / total; double cThreshold = pThreshold + (competitors / total); double eventSeed = (Math.random()); if (eventSeed <= pThreshold) return 0; // predator if (eventSeed <= cThreshold) return 1; // competitor return 2; // food }
Thanks
  quote
Partial
Stallion
 
Join Date: Feb 2006
Location: Milwaukee
 
2009-10-04, 20:02

Always use open and close brackets for every if. It's a best practice.
  quote
Kraetos
Lovable Bastard
 
Join Date: Dec 2005
Location: Boston-ish
 
2009-10-04, 20:09

Quote:
Originally Posted by Partial View Post
Always use open and close brackets for every if. It's a best practice.
For one-liners? Why?

How is this:

Code:
if (foo) bar;
any less clear than this, which is ugly/awkward:

Code:
if (foo) { bar; }
or this, which is just a huge waste of space?

Code:
if (foo) { bar; }
Java lets bracketless one-liners slide for this reason.

Logic, logic, logic. Logic is the beginning of wisdom, Valeris, not the end.
  quote
Partial
Stallion
 
Join Date: Feb 2006
Location: Milwaukee
 
2009-10-04, 20:29

Code:
if ( foo ) { bar; }
This is a best practice. On a small project like yours, it probably doesn't matter, but it is much better to get into best practices when you're learning.

Trust me. I'm working on this awful, awful project with one 7000 line class, and probably a total of 50k lines of shitty code. It's awful. The worst part is in they rarely open or close ifs with brackets and then they don't do any indenting, so it's very difficult to follow whats going on.

Worst. Project. Ever.

One thing you could do to get into some really good habits is to look into the java coding standards and install the CheckStyle plugin into Eclipse.

Also, you should pass most of those values into your method instead of accessing as local variables that may or may not be set correctly at they time they're being called. Dependency injection is another practice I'm big on.

Not saying it's how you have to do it, but this is how I'd probably write the below code. I'm definitely making some assumptions about the requirements.

Code:
public int runEvent(double predators, double competitors, double food) { final int PREDATOR_VALUE = 0; final int COMPETITOR_VALUE = 1; final int FOOD_VALUE = 2; final double TOTAL = calcTotal( predators, competitors, food ); final double P_THRESHOLD = calcPredatorThreshold( predators, total ); final double C_THRESHOLD = calcCompetitorThreshold( P_THRESHOLD, TOTAL, competitors ); final double EVENT_SEED = Math.random(); if ( EVENT_SEED <= P_THRESHOLD){ return PREDATOR_VALUE; } else if ( EVENT_SEED <= C_THRESHOLD ){ return COMPETITOR_VALUE; } else{ return FOOD_VALUE; } }

...and calling/e-mailing/texting ex-girlfriends on the off-chance they'll invite you over for some "old time's sake" no-strings couch gymnastics...

Last edited by Partial : 2009-10-04 at 20:45.
  quote
Kickaha
Veteran Member
 
Join Date: May 2004
 
2009-10-04, 20:49

Quote:
Originally Posted by Kraetos View Post
For one-liners? Why?

How is this:

Code:
if (foo) bar;
any less clear than this, which is ugly/awkward:

Code:
if (foo) { bar; }
or this, which is just a huge waste of space?

Code:
if (foo) { bar; }
Java lets bracketless one-liners slide for this reason.
So does C, and it's a huge source of bugs. Consider the above, in your first example. Six months later another dev comes along and adds a second statement to the if block:

Code:
if (foo) bar; andThis;
BZZT. Bug. "But he made a mistake, and it's obvious!" Yup. It is. But it's not when you have several nested ifs, and a smattering if #ifdefs coursing through it. In such cases, the developer that leaves off those brackets deserves every bit of office supplies chucked at their head.

Try this one on, and this one is trivial:

Code:
if (foo) if (bar) if (g) baz; else notBar;
There's a bug there. See it?

Make all blocks explicit, all the time. "Waste of space" is a complete red herring... what, the two bytes on disk for the brackets? You're worried about *two bytes*? Really?
  quote
Brad
Selfish Heathen
 
Join Date: May 2004
Location: Zone of Pain
 
2009-10-04, 21:11

Quote:
Originally Posted by Kickaha View Post
Code:
if (foo) if (bar) if (g) baz; else notBar;
There's a bug there. See it?
Depends on the language, too. That block is interpreted very differently in Python as opposed to Java/C/PHP.
  quote
Kickaha
Veteran Member
 
Join Date: May 2004
 
2009-10-04, 21:15

Yes, we were discussing languages with non-whitespace defined blocks.

Python makes the situation better, IMO, but a lot of people hate it.
  quote
Banana
is the next Chiquita
 
Join Date: Feb 2005
 
2009-10-04, 21:39

Quote:
Originally Posted by Kickaha View Post
Python makes the situation better, IMO, but a lot of people hate it.
Whaaaa?

I fell in love when I learned about how Python handles whitespaces! What's to hate?!?
  quote
Partial
Stallion
 
Join Date: Feb 2006
Location: Milwaukee
 
2009-10-04, 21:56

Quote:
Originally Posted by Kickaha View Post
Yes, we were discussing languages with non-whitespace defined blocks.

Python makes the situation better, IMO, but a lot of people hate it.
Do you think this is a good practice for clean code? I'm not familiar with Python but from what I'm gathering it uses indentation to determine which "if" the "else" corresponds to in your example?

I'm all about indenting properly and using brackets to open and close ifs. I've had some really bad experiences as detailed above about the massive 7000 line class I inherited. It's been a nightmare.

...and calling/e-mailing/texting ex-girlfriends on the off-chance they'll invite you over for some "old time's sake" no-strings couch gymnastics...
  quote
Kickaha
Veteran Member
 
Join Date: May 2004
 
2009-10-04, 23:38

Quote:
Originally Posted by Partial View Post
Do you think this is a good practice for clean code? I'm not familiar with Python but from what I'm gathering it uses indentation to determine which "if" the "else" corresponds to in your example?
Yup. No brackets at all, *just* indentation as the determining factor for block edges. Pretty elegant, and it makes it damned near foolproof to figure out what goes with what... *except*...

Quote:
Originally Posted by Banana
I fell in love when I learned about how Python handles whitespaces! What's to hate?!?
When you're dealing with a text file where one person's editor inserts tabs, one inserts 4 spaces instead of tabs, one inserts 2 spaces instead of tabs, etc, etc, etc... it falls apart. If you have a standardized whitespace creation methodology across your editors and IDEs, then it works beautifully.

But getting developers to agree on whitespace is like getting them to agree on bracket placement. If you can enforce it for a group, however, it works very well and bugs like the one before are basically impossible.

I've been known to go bracketless in one case, and even then I feel wrong doing it: where the statement fits on the same line as the if:

Code:
if (foo) bar;
But if it needs to be below the if, then it needs brackets, every time.
  quote
Brad
Selfish Heathen
 
Join Date: May 2004
Location: Zone of Pain
 
2009-10-04, 23:55

Quote:
Originally Posted by Kickaha View Post
When you're dealing with a text file where one person's editor inserts tabs, one inserts 4 spaces instead of tabs, one inserts 2 spaces instead of tabs, etc, etc, etc... it falls apart. If you have a standardized whitespace creation methodology across your editors and IDEs, then it works beautifully.
It also becomes troublesome when working with version control software. Merging changes that alter indentation can be "painful" to say the least.
  quote
Banana
is the next Chiquita
 
Join Date: Feb 2005
 
2009-10-05, 00:34

Wasn't aware of those issues, but then again I've only played with python a bit and certainly not in a team project. That sucks, though. Surely they could come up with a macro to pre-format the indentation before loading it in IDE or compiler and do away with that annoyance.

But then, if it was that simple, they'd already have had fixed it long time ago...
  quote
Partial
Stallion
 
Join Date: Feb 2006
Location: Milwaukee
 
2009-10-05, 01:06

Another very informative thread. Thanks guys. Good to have so many developers around here.
  quote
ShadowOfGed
Travels via TARDIS
 
Join Date: Aug 2005
Location: Earthsea
 
2009-10-05, 01:41

Wait, nobody's going to suggest the generic solution?
  • Concatenate inputs into a list of numbers
  • Calculate sum of all values
  • Obtain random value (rand * sum)
  • Find greatest i where sum(list[0..i]) < value
  • Return i (your index)

That would work for more than 3! And in some ways, may better represent what's happening. Not saying it's *faster* at all.

Apparently I call the cops when I see people litter.
  quote
Kraetos
Lovable Bastard
 
Join Date: Dec 2005
Location: Boston-ish
 
2009-10-06, 10:54

You guys make good points, and I'd like to point out that on larger/collaborative projects, I obviously stick to the indentation style in use and I delineate all blocks with curlies.

But for something small (< 300 lines total) like this that nobody else will ever see, I just go with the style which is most readable to me.

Logic, logic, logic. Logic is the beginning of wisdom, Valeris, not the end.
  quote
tomoe
Veteran Member
 
Join Date: Nov 2006
 
2009-10-06, 11:28

Quote:
Originally Posted by ShadowOfGed View Post
Wait, nobody's going to suggest the generic solution?
  • Concatenate inputs into a list of numbers
  • Calculate sum of all values
  • Obtain random value (rand * sum)
  • Find greatest i where sum(list[0..i]) < value
  • Return i (your index)

That would work for more than 3! And in some ways, may better represent what's happening. Not saying it's *faster* at all.
That's exactly what I do when programming grid worlds. Much simpler and more general.
  quote
Posting Rules Navigation
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Post Reply

Forum Jump
Thread Tools
Similar Threads
Thread Thread Starter Forum Replies Last Post
Trimming Null Values from Strings (Java) Kraetos Programmer's Nook 6 2008-03-25 14:09
C++ in XCode -- relative paths? Wyatt Programmer's Nook 4 2007-05-05 22:41
'Weird' is a relative word! Freewell AppleOutsider 54 2007-01-27 20:20
Relative pricing on MBP's Mugge Apple Products 4 2006-04-02 03:22


« Previous Thread | Next Thread »

All times are GMT -5. The time now is 07:42.


Powered by vBulletin®
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Copyright ©2004 - 2024, AppleNova