简体   繁体   English

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

[英]Getting different random strings from string array

Hi well i have a string array with like 50 strings and i want it to select only 10 randon results and display them on a table layout i get everything right except it only shows one result. 嗨,我有一个包含50个字符串的字符串数组,我希望它仅选择10个randon结果并将它们显示在表格布局上,我一切都正确,除了它只显示一个结果。 heres my code: 这是我的代码:

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

whats wrong? 怎么了?

Quite simple by using a set, that will take care about avoiding duplicates: 使用集合非常简单,它将避免重复:

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

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

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

  ..
}

This is called "random sampling". 这称为“随机采样”。 Two common techniques are: 两种常用技术是:

  • simply shuffle the entire list/array, making sure you use a fair shuffling algorithm such as that offered by Collections.shuffle(), then take the first n elements; 只需对整个列表/数组进行混洗,确保使用公平的混洗算法(例如Collections.shuffle()提供的算法),然后采用前n个元素;
  • go through the list, each time deciding whether to include the next item based on whether a random number exceeds a threshold representing number of items still needed/number of items left. 遍历该列表,每次根据随机数是否超过表示仍需要的项目数/剩余的项目数的阈值来决定是否包括下一个项目。

If you go for the first method, just make sure that your shuffle is genuinely a fair algorithm. 如果您选择第一种方法,只需确保随机播放确实是一种公平的算法即可。 Many programmers if asked to write a shuffle algorithm from scratch get it wrong. 许多程序员如果被要求从头开始编写洗牌算法,则会出错。 Java's Collections.shuffle() is an example of how to do it. Java的Collections.shuffle()是如何执行此操作的示例。

You may also be interested in an article about random sampling in Java that I wrote a while ago which includes example skeleton code for the second case. 您可能还对我不久前写的有关Java随机采样的文章感兴趣,其中包括第二种情况的示例框架代码。

For the sake of knowledge, you may also wish to research something called "reservoir sampling", although it is overkill for selecting 10 items from a possible 50. 为了知识起见,您可能还希望研究一种称为“储层采样”的方法,尽管从可能的50种中选择10种是过分的。

Thats what I came up with.. 那就是我想出的。

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

    }
}

The reason you only get one answer is you get the string outside of your loop so you only get it once. 您只能得到一个答案的原因是,您在循环之外获得了字符串,因此只能获得一次。 It should look more like it is below. 它看起来应该更像下面的样子。

Also if you want to avoid duplicates you are going to have to do something to take care of that. 同样,如果您想避免重复,您将不得不采取一些措施来解决这一问题。 java.util.Collections.shuffle() might be good for your purposes, then you just take the first 10 items. 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