【问题标题】:Getting different random strings from string array从字符串数组中获取不同的随机字符串
【发布时间】:2012-06-09 02:17:58
【问题描述】:

您好,我有一个包含 50 个字符串的字符串数组,我希望它只选择 10 个随机结果并将它们显示在表格布局上,除了它只显示一个结果之外,我得到了所有正确的结果。这是我的代码:

private String[] list;
private static final Random rgenerator = new Random();


@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.layout1);

Resources res = getResources();
    list = res.getStringArray(R.array.names);
    String q = list[rgenerator.nextInt(list.length)];
int total = 10;

    for (int current = 0; current < total; current++) {
        // Create a TableRow and give it an ID
        TableRow tr = new TableRow(this);
        tr.setId(100 + current);
        tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));

        // Create a TextView to house the name of the province
        TextView labelTV = new TextView(this);
        labelTV.setId(200 + current);
        labelTV.setText(q);
        labelTV.setTextSize(14);
        labelTV.setGravity(Gravity.CENTER);
        labelTV.setTextColor(Color.WHITE);
        labelTV.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
        tr.addView(labelTV);

        tablelayout.addView(tr, new TableLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
}

怎么了?

【问题讨论】:

    标签: java android arrays string random


    【解决方案1】:

    使用集合非常简单,可以避免重复:

    Set<Integer> uniques = new HashSet<Integer>();
    
    while (uniques.size() < 10)
      uniques.add(rgenerator.nextInt(list.length);
    
    for (Integer i : uniques)
    {
      String q = list[i];
    
      ..
    }
    

    【讨论】:

    • 所以在 labelTV.setText();我要放q吗?
    • 您需要将list 中的所有Strings 连接成一个变量,例如text,然后调用labelTV.setText(text)
    【解决方案2】:

    这称为“随机抽样”。两种常见的技术是:

    • 只需打乱整个列表/数组,确保使用公平的打乱算法,例如 Collections.shuffle() 提供的算法,然后取前 n 个元素;
    • 遍历列表,每次根据随机数是否超过阈值来决定是否包含下一个项目,该阈值表示仍需要的项目数/剩余项目数。

    如果您选择第一种方法,请确保您的 shuffle 是真正公平的算法。如果要求许多程序员从头开始编写 shuffle 算法,就会出错。 Java 的 Collections.shuffle() 就是一个例子。

    您可能还对我不久前写的一篇关于random sampling in Java 的文章感兴趣,其中包括第二种情况的示例框架代码。

    为了了解知识,您可能还希望研究一种称为“水库抽样”的东西,尽管从可能的 50 个项目中选择 10 个项目是多余的。

    【讨论】:

      【解决方案3】:

      这就是我想出的..

      import java.util.*;
      public class RandomStringFromArray
      {
          public static void main(String[] args)
          {
              Random rnd = new Random();
              Scanner scan = new Scanner (System.in);
              System.out.println("Enter how many string in the array");
              int x = scan.nextInt();
              ArrayList<String> arraystr = new ArrayList<String>();
      
              for (int i=0; i < x ; i++)
                  {
                      System.out.println("Enter elements of the array");
                      arraystr.add(scan.next());
                  }
              System.out.println("\nI picked: ");
      
              for ( int t = 0; t < 3; t++) // 3 is how many elements you want to pick
                  {
      
                          int random = rnd.nextInt(x);
                          System.out.println(arraystr.get(random));
                          arraystr.remove(random);
                  }
      
          }
      }
      

      【讨论】:

        【解决方案4】:

        你只能得到一个答案的原因是你在循环之外得到了字符串,所以你只能得到一次。它应该看起来更像是在下面。

        此外,如果您想避免重复,您将不得不采取一些措施来解决这个问题。 java.util.Collections.shuffle() 可能适合您的目的,那么您只需获取前 10 个项目。

            int total = 10;
        
            for (int current = 0; current < total; current++) {
                String q = list[rgenerator.nextInt(list.length)];
                // Create a TableRow and give it an ID
        

        【讨论】:

          猜你喜欢
          • 2011-02-18
          • 2021-03-06
          • 1970-01-01
          • 2019-04-01
          • 2013-08-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多