Answer the question
In order to leave comments, you need to log in
Random how to generate random numbers but with a certain probability of falling out?
how to generate random numbers but with a certain probability. For example, numbers from 1 to 5, but 1 should fall out with a probability of 35%, 2-25%, 3-25%, 4-10%, 5-5%
Answer the question
In order to leave comments, you need to log in
This elementary task is called "generation of discrete random variables with a given distribution law". solved in the classical way.
First, we break our range from 1 to 100 into the following intervals:
1-35.36-60.61-85.86-95.96-100.
Then we generate a number evenly distributed in the range from 1 to 100. The number of the interval in which this number falls gives your generated numbers - from 1 to 5, and they are distributed exactly according to your distribution table.
I do not guarantee that this is the best option, just the first thing that came to mind:
1. Fill an array of 100 elements with 35 ones, 25 twos, 25 triples, 10 fours, 5 fives.
2. Generate a random number from 0 to 99 and extract the value from the array by index.
Everything is ready, everything worked out. Might be useful for someone
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.Serializable;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button cmak = (Button)findViewById(R.id.knopka);
final TextView ocko = (TextView)findViewById(R.id.okno);
cmak.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ocko.setText(String.valueOf(foo()));
}
private Serializable foo(){
ArrayList<Integer> foo = new ArrayList<>();
for (int i = 0; i< 2; i++) {
double random = Math.floor(Math.random() * 100) + 1;
if (random < 36) {
foo.add(1);
} else if (random < 61) {
foo.add(2);
} else if (random < 81) {
foo.add(3);
} else if (random < 96) {
foo.add(4);
} else if (random < 98) {
foo.add(5);
}
}
return foo;
}
});
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question