Jump to content
xisto Community
Sign in to follow this  
beeseven

Is It Possible To Weigh Random Numbers?

Recommended Posts

I'm making an RPG so I need to use a lot of random numbers. Right now I'm thinking about stat increases after level-ups. I want to write a method that does something like "return a random number from 0 to 4 inclusive, but make it most likely to be 1 or 2." Does anybody know how I could go about implementing something like that?

Share this post


Link to post
Share on other sites

I thought I did. I want something that will return a random number in a certain range that can be any number in that range but will usually be in a smaller range. For example, using the numbers above (0-5 inclusive but most likely 1 or 2), ten numbers returned might be:2, 1, 1, 3, 2, 0, 1, 5, 2, 1Seven of those are 1 or 2, and the other three are other numbers in the 0-5 range.

Share this post


Link to post
Share on other sites

Well one choice would be to generate a random number from say, 1 to 100. Then if you want a 75% chance of it being 1 or 2 then say that if the first number is less than 75, generate a random number from 1 to 2, otherwise, generate one from 3 to 4. Its probably not the most efficient way of doing it, but it should work.

Share this post


Link to post
Share on other sites

It's not that hard to make that! I'll explain it to you using a simple code:

var numarray = new Array(1, 1, 1, 2, 2, 2, 3, 4);/* This is the array of possible values. The more times you use a number, the more times it will return. */var rand = Math.round(Math.random()*(numarray.length-1));/* This code creates a random number between 0 and (numarray.length-1). */var num = numarray[rand];/* This piece will take a value out of the array, based on the random number of the second line of code. */

And this will always return one of the values you want! Of course, you speak of a function that returns a value, so it will be more like this:

function randomNumber(){var numarray = new Array(1, 1, 1, 2, 2, 2, 3, 4);var rand = Math.round(Math.random()*(numarray.length-1));var num = numarray[rand];return num;}

Edited by peroim (see edit history)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.