Daniel Oliveira
Daniel Oliveira

Reputation: 1290

How to generate a random number between two values with preference for numbers closer to the limits

I am implementing an AI system that basically plays the Battle Ships game. A part of this AI consists in placing the Ships on the board. This should be a random process but however statistics says that you are more likely to win the game if you place your ships near to the edge of the board.

Something like this: enter image description here

So, saying the ship can be at any position X (between 0 and 9) and Y (between 0 and 9) I would like to implement an algorithm that can generate a random integer between 0 and 9 with more probability of returning numbers closer to 0 or closer to 9 (being 4 and 5 the numbers less likely to be returned). This would be a javascript algorithm but any intuition using pseudo-code is appreciated.

Any suggestions?

Thanks!

Upvotes: 1

Views: 389

Answers (2)

Keith
Keith

Reputation: 24181

Basically all you do is sum up the probabilities of all the cells, then pick a random number & multiply by this sum.

Now loop your probability matrix and subtract from the random number total until less than equal to 0. This then will be the one you want.

Below is a simple example, it's a 3 x 3 matrix, with cell 4 (middle one) with a probability half of the rest, so cell 4 should get selected half as many times as the rest.

ps. Cell 4 as in 0-8,.. Not 1-9, as arrays are zero based.

const squaresProb = [
  2, 2, 2,
  2, 1, 2,
  2, 2, 2
];

const maxProb = squaresProb.reduce((a, v) => a +v);

function pickRandomCell() {
  let r = Math.random() * maxProb;
  for (let c = 0; c < squaresProb.length; c ++) {
    r -= squaresProb[c];    
    if (r <= 0) return c;
  }
  return squaresProb.length -1;
}

const cellCounts = [0,0,0, 0,0,0, 0,0,0];

//test..  Pick 100,000 cells, 
//Cell 4 should be the smallest.

for (let l = 0; l < 100000; l ++) {
  cellCounts[pickRandomCell()] ++;
}

console.log(cellCounts);

Upvotes: 0

Mulan
Mulan

Reputation: 135207

So let's say you have some samples and a fair sampling function

// an equal distribution
const equalDistribution = 
  [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

// fair sampling function
sample (equalDistribution) // equal probability of 0 - 9

Simply adjust the samples to include more numbers that you want to appear more frequently - below, 0 and 9 have an increased probability (3/14) compared to before (1/10)

// 0 and 9 are more likely
const inequalDistribution =
  [ 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9 ]

// same fair sampling function
sample (inequalDistribution) // = 0 and 9 more likely

This gives you full control over which distribution of outcomes you'd like. Of course your job now is to make a function which takes equalDistribution and creates inequalDistribution based on some input. This is where you write a program, and if you get stuck, share it and ask for help.

Upvotes: 3

Related Questions