クイズアプリやってます。このアプリの質問は重複を生成しません。そのため、int value=random.nextInt(10-1)+1 のようなコードを使用しています。回答を送信すると、乱数が新しく生成されるため、重複が生成されます。以前のランダム値と新しいランダム値を毎回比較するにはどうすればよいですか?
4 に答える
- 1から10まで生成してリストに格納
 - 生成された数字のリストをシャッフルする
 リストから削除し続ける
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);
等々...
これも確認してください:Java - 特定の番号のランダムな範囲をそれらの番号の重複なしに生成する - 方法は?
また、 HashMap に保存してチェックすることは、他の回答が言うようにスマートな方法です。ただし、HashMap に複製を追加しようとするたびに失敗し、新しいものを再度生成する必要があるため、これにより多くの衝突が発生する可能性があります。しかし、一度にすべてを生成してシャッフルしても、これは発生しません。しかし、入力セットが小さい (10) ため、この衝突はあまり発生しない可能性があり (ランダム性に応じて、または発生しすぎる可能性がありますか?)、比較のためのマップ要素への O(1) アクセスが役立ちます。
値をハッシュマップに格納し、それが既に存在するかどうかを確認します。再ロールがある場合。
これが私のプロジェクトで使用していたコードです。完全なソースコードは こちら
 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;
        }           
    }
    }
    このクラスのメインプロパティで「HashSet」クラスを使用すると、異なる値のセットが含まれているため、値が繰り返されないことを意味します......したがって、ランダムな番号を生成できます。このようにセットに追加します
Random r = new Random();
int i = r.nextInt(100);
HashSet<int> s = new HashSet<int>();
s.add(i);
乱数を生成し、それをハッシュセットに追加して使用します.... 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() + " ");  
          }