Random without repetition

Asked

Viewed 915 times

3

Well, I have a question that’s been killing me for a long time, and I can’t fix it. PS: I’m a beginner on Android.

I am developing an application of raffle, but I am not able to generate a Random without repeating the numbers already drawn, I tried everything, but still it repeats the number.

Follows the Code:

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);     
    setContentView(R.layout.activity_main); 

    final NumberPicker InicialNP = (NumberPicker) findViewById(R.id.inicialID);

        InicialNP.setMinValue(0);       
        InicialNP.setMaxValue(700);     
        InicialNP.setWrapSelectorWheel(true);

        InicialNP.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
 public void onValueChange(NumberPicker picker, int oldVal, int newVal){

            }
        });

    final NumberPicker FinalID = (NumberPicker) findViewById(R.id.finalID);

        FinalID.setMinValue(0);       
        FinalID.setMaxValue(700);       
        FinalID.setWrapSelectorWheel(true);

        FinalID.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
        @Override
 public void onValueChange(NumberPicker picker, int oldVal, int newVal){

           }
        });

        EditText Nomesorteio = (EditText) findViewById(R.id.nomesorteioID);
        EditText Resultado = (EditText) findViewById(R.id.resultadoID);
        Button Sortear = (Button) findViewById(R.id.btnsortear);            
        Sortear.setOnClickListener(new View.OnClickListener() {     


    private int mostrarresultado() {    

          inicial = InicialNP.getValue();
          finall = FinalID.getValue();
          Random Random = new Random();
          int Resultado = Random.nextInt(finall + 1 - inicial) + inicial;  

          return  Resultado;                      
        }


    private void verifyRepeated(int removeValue) {

          int getParams = removeValue;
          Random random = new Random();
          getParams = random.nextInt(finall + 1 - inicial) + inicial;   

            while(true)
                    {
                if(!repeat_list.contains(getParams))
                    break;
                else                        
                    getParams = random.nextInt(finall + 1 - inicial) + inicial;
            }

            repeat_list.add(getParams);
            Toast.makeText(MainActivity.this, "O valor sorteado foi: " + Integer.toString(removeValue), Toast.LENGTH_LONG).show();
        }


        @Override
        public void onClick(View v) {     
            list.clear();
            click = MediaPlayer.create (MainActivity.this, R.raw.click); 
            click.start ();
            Toast.makeText(MainActivity.this, "Sorteando", Toast.LENGTH_LONG).show();               
            int Resultado = mostrarresultado();

            verifyRepeated(Resultado);

        } 

    });

}

}

3 answers

6

Try to store your values in one Set<Integer>. The type of data Set is a list that does not store repeated values. With this you will ensure that the stored values do not repeat.

PS: Integer is a primitive type wrapper class int.

  • That’s the best answer. In a college job, I needed to generate a very large amount of random numbers. By listing, duplicate queries took a long time because they were(n). After I switched to a Set, which is always (1), the program took off..

  • Can you give me an example of how I do it?

  • @J.Silva you need to create a data collection of the type Set<int> which is a Collection as well as List<>, and in this collection you add call returns to your method mostrarresultado(). This ensures that returns do not recur, not to mention that the implementation and even the complexity of your algorithm will be much simpler. Example: Set<int> resultados = new HashSet<int>(); resultados.add(mostrarresultado());

  • Set<Integer> and not Set<int> - primitive types cannot be used as generics in Java.

  • @Victorstafusa is. I didn’t pay attention to this detail.

3

You must use the command Collections.shuffle(), this way will always be a random number and will not repeat, example:

ArrayList<Integer> number = new ArrayList<Integer>();
for (int i = inicial; i <= finall; ++i){
    number.add(i);
}
Collections.shuffle(number);

1


Do it that way:

private static ArrayList<Integer> repeat_list = new ArrayList();

private int inicial;
private int finall;

private int mostrarresultado() {                    
    inicial = editTextInicial.getValue();
    finall = editTextFinal.getValue();
    Random Random = new Random();
    int Resultado = Random.nextInt(finall + 1 - inicial) + inicial;  

    return  Resultado;                      
}


private void verifyRepeated(int removeValue)
{
    int getParams = removeValue;
    while(true)
    {
        if(!repeat_list.contains(getParams))
            break;
        else
            getParams = Random.nextInt(finall + 1 - inicial) + inicial;
    }

    repeat_list.add(getParams);
    Toast.makeText(MainActivity.this, "O valor sorteado foi: " + removeValue.toString(), Toast.LENGTH_LONG).show();

}


@Override
public void onClick(View v) {     
    list.clear();
    click = MediaPlayer.create (MainActivity.this, R.raw.click); 
    click.start ();
    Toast.makeText(MainActivity.this, "Sorteando", Toast.LENGTH_LONG).show();               
    int Resultado = mostrarresultado();

    verifyRepeated(Resultado);

} 
  • That’s exactly what I was looking for, thank you very much! , but, just to put it like this: Private Arraylist<Integer> list = new Arraylist(); E keeps repeating the numbers, but now I already have a great base to try to solve, thank you very much!

  • Did it work out ? @J.Silva

  • I had forgotten to limapr the list every time the function is called hehe

  • I don’t know if the problem is here -> private Arraylist<Integer> list = new Arraylist(); why I can’t use Static, but it’s still repeating

  • So type.. in this case you would have to separate the place where you will do the Random and the place where you will add the entries

  • You just have to keep in mind, that the value you have drawn has to be removed from the list every time after being randomized

  • Still not getting =/ is there something wrong with my onClick? Only using: private Arraylist<Integer> list = new Arraylist(); But still repeats numbers. @Override public void onClick(View v) ' click = Mediaplayer.create (Mainactivity.this, R.raw.click); click.start(); Toast.makeText(Mainactivity.this, "Drawing", Toast.LENGTH_LONG). show(); int Result = show result(); resultado1.setText(Integer.toString(Result)); } }); }

  • Edit your code up there with your onClick button

  • I edited from a glance

  • Okay 1 minute....

  • Sorry for all this work, it’s my first Android application, look how it looks: https://uploaddeimagens.com.br/imagens/foto2-png-28

  • I reedited from a look

  • Success, that’s right, thank you very much!

  • Somehow you’re still repeating, is there something wrong with my Activity? PS: I edited the code

  • Edit your question upstairs, and post your code

  • I’m having trouble posting the code :(

  • Put up there, rephrasing the "YOUR" question...

  • All right. Take a little peek, please.

  • Dude I’ll ask you a studied before in object orientation and clean code, your code is very messy...

  • I’m going to clean it up exactly today, I’ve been days trying to solve this repeat problem so I can clear all the code.

  • Quiet I’ll be waiting =)

  • I improved the code. It got better?

  • Please avoid long discussions in the comments; your talk was moved to the chat

Show 19 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.