Answer the question
In order to leave comments, you need to log in
Random numbers without repeats?
android studio. How to make the numbers displayed without simultaneous repetitions?
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;
}
});
}
}
Answer the question
In order to leave comments, you need to log in
Your question is not very clear. I can hardly guess that you want to ensure that your random does not give out the same numbers in a row, if I misunderstood, sorry.
You have a 35% chance of getting one, but at the same time you want it not to come up twice, i.e. when one drops out, at the next iteration the chance of its dropping out should be 0%
. In this case, the chance of other numbers needs to be increased. And thus replace the chances after each iteration.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question