How to Generate Single Random value without Duplicate?

I am doing quize app. In this app questions wont be generate duplicates. so I am using code like int value=random.nextInt(10-1)+1.When i submit the answer random number will generate newly so generating duplicates.How can i compare previous random value with new random values every time ?

Upvotes: 0

Views: 2329

Answers (4)

Rahul
Rahul

Reputation: 41

use 'HashSet' class in the main property of this class is they contain set of different values mean no value is repeated in it...... so u can generate random no. and add it in set like this

Random r = new Random();
int i = r.nextInt(100);

HashSet<int> s = new HashSet<int>();
s.add(i);

generat random number and add it inti hashset and use it.... an in nextInt parameter have to give maximum no. range...

example code as follows:

Random r = new Random();
        //declare a hash set
        HashSet set = new HashSet();


        for(int i=0;i<50;i++)
        {
            set.add(r.nextInt(100));
        }


         // create an iterator
          Iterator iterator = set.iterator(); 

          // check values
          while (iterator.hasNext()){
             System.out.println("Value: "+iterator.next() + " ");  
          }

Upvotes: 0

Shiba Prasad J.
Shiba Prasad J.

Reputation: 387

Here is code which i was using at my project. Full source code is here

 package com.banglardin.test_code;

import android.app.*;
import android.content.*;
import android.content.res.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import com.banglardin.test_code.*;
import java.util.*;

public class MainActivity extends Activity {    

protected SharedPreferences preference;
protected Questions questionObject;
protected TextView textView;
protected Button buttonView, cleanButton;
protected ArrayList<String> ques_array;
protected final String KEY="Key124";
protected int i=0;


/** Called when the activity is first created. */
@Override
     public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);

//intilized Question and preference
questionObject = new Questions();   
preference = getSharedPreferences(KEY,Context.MODE_WORLD_WRITEABLE);
   // get array from question object
try{    
ques_array= questionObject.getQestions(getApplicationContext());
}catch(Exception e){
    e.printStackTrace();
    }

// intilized views
textView = (TextView)findViewById (R.id.question);
buttonView = (Button) findViewById (R.id.button);
cleanButton = (Button) findViewById (R.id.button_clean);

textView.setTextSize(18.33f);
buttonView.setTextSize(18.00f); 
cleanButton.setTextSize(18.00f);


// set onclickListener on button view
    buttonView.setOnClickListener(new View.OnClickListener(){
    public void onClick(View v) {

    int set = 0;
    if(i < 6){
     while(set == 0){
      String history = getString(KEY); // <0>    
      Random r = new Random();
      int id = r.nextInt(ques_array.size());
      String s_id= "<"+ String.valueOf(id) + ">"; // ex : <0>



      if( !history.contains(s_id)){
          textView.setText(ques_array.get(id));
          setString(KEY, (history + s_id)); // ex : <0> + <3> = <0><3>;
          set = 67;
          i++;
          }          
          }
          }



     else if(i>=6){
          textView.setText(getResources().getString(R.string.e2));        
          Toast.makeText(MainActivity.this,"Questions are not available any more",2).show();
          }           
      }         
      }
      );


// set onclickListener on button view
   cleanButton.setOnClickListener(new View.OnClickListener(){
    public void onClick(View v) {
            setString(KEY, "<-0>");

        }
        }
        );

        }


  @Override
  public void onBackPressed(){
if(preference != null){
    setString(KEY, ("<-0>"));       
    finish();
}   
super.onBackPressed();
}

  /** Get String value from preference */
   private String getString(String KEY){
   if(preference != null){
  return  preference.getString(KEY,"<-33>");  
  }
  else{
      return null;
      }
      }

   /** Put String value to preference */
    private void setString(String KEY, String value){   
if(preference != null){
    SharedPreferences.Editor edit = preference.edit();
    edit.putString(KEY, value);
    edit.commit();  
    }
    }


     /** Class that gives us all questions */
     class Questions{
protected ArrayList<String> data;
public ArrayList<String> getQestions(Context c) throws Exception{
    data = new ArrayList<String>();
    Resources res= c.getResources();

    String qes[] ={
    res.getString(R.string.q1)      , //0
    res.getString(R.string.q2)      , //1
    res.getString(R.string.q3)  , //2
    res.getString(R.string.q4)  , //3
    res.getString(R.string.q5)  , //4
    res.getString(R.string.q6)  , //5
    res.getString(R.string.q7)      , //6
    };

   // add all the strings one by one
    for(String i : qes){
    data.add(i);        
    }
    return data;
        }           
    }
    }

Upvotes: 0

Vrashabh Irde
Vrashabh Irde

Reputation: 14367

  1. Generate from 1 to 10 and store in a list
  2. Shuffle the list of generated numbers
  3. Keep removing from the list

    List<Integer> list = new LinkedList<Integer>();

    for (int i = 1; i <= 10; i++) {
        list.add(i)
    }
    
    Collections.shuffle(list);
    
    int value= list.remove(0);
    .......
    
    value= list.remove(0);
    

and so on...

Check this also : Java - generate Random range of specific numbers without duplication of those numbers - how to?

Also storing in a HashMap and checking is a smart way like the other answer says. But this can cause a lot more clashes, since everytime you try to add a duplicate to the HashMap you fail and you have to generate a new one again. But generating all at once and shuffling doesnt cause this. But since the input set is small(10) this collision might not happen too much(depending on the randomness, or maybe it happens too much?) and the O(1) access to the map elements for comparison will help.

Upvotes: 3

Warpzit
Warpzit

Reputation: 28152

Store value in a hashmap and then check if it's already there. If there reroll.

Upvotes: 2

Related Questions