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 ?
-
1http://stackoverflow.com/questions/5224877/java-generate-random-range-of-specific-numbers-without-duplication-of-those-nu I think this link will helps you – Ramz Jul 18 '13 at 06:33
4 Answers
- Generate from 1 to 10 and store in a list
- Shuffle the list of generated numbers
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.

- 1
- 1

- 14,129
- 6
- 51
- 103
-
Having to regenerate colliding values is a valid point. For very large lists you may want to retrieve the last element instead of the first to avoid unnecessary shifts (http://docs.oracle.com/javase/1.5.0/docs/api/java/util/List.html#remove%28int%29). Also using a LIFO stack like http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Stack.html might help with this. However for a list of 10 random numbers it's proably not that much of a difference. – Father Stack Jul 18 '13 at 07:00
-
here every time 10 random numbers are generating at a time.bt i need compare previous random numbers with new random nubers.how will i do? – Amarnathreddy Gangapuram Jul 18 '13 at 07:06
-
Why do you need to compare? Everytime you do remove, you'll get a new unique random number from your list of 10 generated numbers. So for instance one set of shuffled numbers might be 9,8,6,1,3,2,4,5,10,7 , so everytime you remove you get unique numbers from this list – Vrashabh Irde Jul 18 '13 at 07:28
Store value in a hashmap and then check if it's already there. If there reroll.

- 27,966
- 19
- 103
- 155
-
Storing in a HashMap and checking is a smart way. 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. – Vrashabh Irde Jul 18 '13 at 06:49
-
Shuffle would probably be the best way to go, I just thought of a quick way to solve the problem :) – Warpzit Jul 18 '13 at 07:36
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() + " ");
}

- 41
- 1
- 1
- 5
-
u are useing this code in wrong way.....i will give u the complete code copy paste it and run it and see no no. in the set will repeat again – Rahul Jul 18 '13 at 11:58
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;
}
}
}

- 387
- 2
- 7