How to insert the probability of randomizing a specific number in pascal

187 views Asked by At

I've been trying lately to write a program(a text based game) but I only know some commands and don't understand every command very well.

What I am trying to do is a hit chance. Lets say that I want the program to have

  • 90% chance of choosing number 1 (which means hit) and
  • 10% to choose number 0 (which means miss).

I saw the same question Here but I don't understand the commands because I've never used them (I'm talking about set.seed and sample). Could someone explain to me how do they work? Is there another way (easier to understand? I don't mind if it consumes more resource)

2

There are 2 answers

0
Abstract type On BEST ANSWER
program Project1;
{$ASSERTIONS ON}

function getProb(aProbability: Integer): boolean;
begin
  result := aProbability > (100 - random(100));
end;

procedure miss;
begin
  writeln('miss');
end;

procedure hit;
begin
  writeln('hit');
end;

var
  i, success, probability, errorMarge: Integer;
const
  combat: array[boolean] of procedure = (@miss, @hit);

begin

  // show that getProb() is reliable
  errorMarge := 4;
  success := 0;
  probability := 80;
  for i in [0..99] do
    Inc(success, Byte(getProb(probability)));
  assert(success >= probability - errorMarge);

  success := 0;
  probability := 50;
  for i in [0..99] do
    Inc(success, Byte(getProb(probability)));
  assert(success >= probability - errorMarge);

  // example usage
  combat[getProb(20)];
  combat[getProb(80)];
  combat[getProb(90)];

  readln;
end.
0
Scott Hunter On

Not knowing what "commands" you know, this is hard to answer w/o generalizing.

If you only need to choose between two values, then generate a random value in whatever range you know how to, and compute the dividing line based on your probability. So, for your example, if you can generate a value between 0 and 1, if it is <= 0.9, hit.

This can be extended to multiple values by adding the successive probabilities. So if you have 4 values to choose between, each with 25% probability, get you random value between 0 and 1: if it is less than 0.25, choose 0 else if less than 0.5, choose 1 else if less than 0.75 choose 2 otherwise choose 3.