繁体   English   中英

从字符串数组获取不同的随机字符串

[英]Getting different random strings from string array

嗨,我有一个包含50个字符串的字符串数组,我希望它仅选择10个randon结果并将它们显示在表格布局上,我一切都正确,除了它只显示一个结果。 这是我的代码:

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));
}

怎么了?

使用集合非常简单,它将避免重复:

Set<Integer> uniques = new HashSet<Integer>();

while (uniques.size() < 10)
  uniques.add(rgenerator.nextInt(list.length);

for (Integer i : uniques)
{
  String q = list[i];

  ..
}

这称为“随机采样”。 两种常用技术是:

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

如果您选择第一种方法,只需确保随机播放确实是一种公平的算法即可。 许多程序员如果被要求从头开始编写洗牌算法,则会出错。 Java的Collections.shuffle()是如何执行此操作的示例。

您可能还对我不久前写的有关Java随机采样的文章感兴趣,其中包括第二种情况的示例框架代码。

为了知识起见,您可能还希望研究一种称为“储层采样”的方法,尽管从可能的50种中选择10种是过分的。

那就是我想出的。

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);
            }

    }
}

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

同样,如果您想避免重复,您将不得不采取一些措施来解决这一问题。 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM