1

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)

Rohit Gupta
  • 4,022
  • 20
  • 31
  • 41
  • So here is without any commands: Create an array of nine ones and one zero, an then shuffle uniformly numbers from 1 to 10, and use this number as an index for that array. This way you will have 9/10 chances to get 1 and only 1/10 chance to get 0 – Eugene Sh. Nov 24 '14 at 20:28
  • Hey, thanks for the answer. It really helped me a lot. Also I could use a case of, right? random(10); case random of 0:miss 1:hit 2:hit . . . 10:hit – RoLeagueGamers Nov 24 '14 at 21:45

2 Answers2

1
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.
Abstract type
  • 1,901
  • 2
  • 15
  • 26
0

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.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101