如何生成单个随机值而不重复?

时间:2013-07-18 06:29:24

标签: android random

我在做quize app。在这个应用程序中,问题不会产生重复。所以我使用的代码如int value = random.nextInt(10-1)+ 1.当我提交答案时,随机数将重新生成,因此生成重复项。如何每次比较先前的随机值和新的随机值?

4 个答案:

答案 0 :(得分:3)

  1. 从1到10生成并存储在列表中
  2. 随机播放生成的数字列表
  3. 继续从列表中删除

    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);
    
  4. 依旧......

    另请检查:Java - generate Random range of specific numbers without duplication of those numbers - how to?

    同样存储在HashMap中并检查是一种聪明的方式,就像其他答案所说的那样。但是这会导致更多的冲突,因为每次尝试向HashMap添加副本时都会失败并且您必须再次生成新的冲突。但是同时产生所有并且改组并不会导致这种情况。但由于输入集很小(10),这种碰撞可能不会发生太多(取决于随机性,或者可能发生太多?)并且O(1)访问地图元素进行比较将有所帮助。

答案 1 :(得分:2)

将值存储在散列映射中,然后检查它是否已存在。如果有重新滚动。

答案 2 :(得分:0)

在这个类的main属性中使用'HashSet'类它们包含一组不同的值意味着没有重复的值...... 所以你可以随机生成no。并将其添加到像这样的集合

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

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

generat random number并将其添加到inti hashset并使用它.... 在nextInt参数中必须给出最大值。范围...

示例代码如下:

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() + " ");  
          }

答案 3 :(得分:0)

这是我在我的项目中使用的代码。完整的源代码是 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;
        }           
    }
    }