生成特定的随机字符串数组

时间:2016-12-08 12:36:29

标签: java arrays random

我知道,标题似乎有点奇怪,让我解释一下。

我想生成随机字符串数组,它必须由特定的给定元素组成。

让我们说这些元素是:面包,牛奶,谷物和咖啡。

Java代码应随机选择其中一个并将其放入数组中。

我取得了一些进展,并设法生成了10个数组,其中包含以下代码:

    String[] elements = new String[] {"Bread","Milk","Cereal","Coffee"};

    for (int i=0; i < 10; i++) {

        int random_number = ThreadLocalRandom.current().nextInt(2, 5);

        String[] list = new String[random_number];

        System.out.print("[");

        for (int j=0; j < random_number; j++) {

            int pos = ThreadLocalRandom.current().nextInt(0, 4);
            list[j] = elements[pos];
            System.out.print(list[j]+ ", ");
        }

        System.out.println("]");
        }

一个可能的输出如下:

[Coffee, Coffee, Coffee, Bread, ]
[Bread, Bread, Coffee, ]
[Coffee, Coffee, Cereal, ]
[Milk, Cereal, ]
[Cereal, Coffee, ]
[Coffee, Cereal, Bread, ]
[Cereal, Cereal, Milk, Milk, ]
[Milk, Bread, Milk, ]
[Bread, Coffee, ]
[Coffee, Bread, ]

有两个问题。

首先不是很重要,但在每个数组的最后一个元素之后没有,会很好。

第二个主要问题是:我不希望每个数组中都有重复的元素。

面包,牛奶,谷物,咖啡必须在每个阵列中不要超过一次。

因此,例如,[Coffee, Coffee, Coffee, Bread]是错误的。

换句话说,一个可能的正确输出是:

[Bread, Milk]
[Bread, Milk, Cereal, Coffee]
[Bread, Cereal, Coffee]
[Bread, Cereal]
[Bread, Coffee]
[Milk, Coffee]
[Milk, Cereal]
[Milk, Cereal, Coffee]
[Cereal, Coffee]

如果两个或多个阵列完全相同则没问题。

提前致谢。

3 个答案:

答案 0 :(得分:0)

您可以像这样使用using System; using System.Data; using System.Web.UI.WebControls; namespace Citizen.WebApp.Login { public partial class MasterDataTable : System.Web.UI.Page { RegistrationBLL m_RegistrationBLL = new RegistrationBLL(); protected void Page_Load(object sender, EventArgs e) { DataTable dt = null; dt = m_RegistrationBLL.GetList(); DataGridView.DataSource = dt; int i; for (i = 0; i < dt.Columns.Count; i++) { BoundField test = new BoundField(); test.DataField = dt.Columns[i].ToString(); test.HeaderText = dt.Columns[i].ToString(); DataGridView.Columns.Add(test); test = null; } DataGridView.DataBind(); } protected void DataGridView_PreRender(object sender, EventArgs e) { if (DataGridView.Rows.Count > 0) { DataGridView.UseAccessibleHeader = true; DataGridView.HeaderRow.TableSection = TableRowSection.TableHeader; DataGridView.FooterRow.TableSection = TableRowSection.TableFooter; } } } } Set

Random

答案 1 :(得分:0)

&lt; p&gt;首先,数组中没有a来自&lt; code&gt; System.out.print(list [j] +&#34;,&#34;);&lt; /代码&gt;,它与数组无关。&lt; / p&gt; &lt; p&gt;要避免重复,请替换&lt; code&gt; String&lt; / code&gt; &LT;代码&GT;阵列&LT; /代码&GT; &lt; code&gt; String [] list = new String [random_number];&lt; / code&gt;使用&lt; code&gt; Set&lt; / code&gt;,&lt; code&gt; Set&lt; String&gt; set = new HashSet();&lt; / code&gt;&lt; / p&gt;

答案 2 :(得分:0)

如果您不太关心效率,这将是一种方法

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class RandomArrays {
    public static void main(String[] args) {
        String[] elements = new String[]{"Bread", "Milk", "Cereal", "Coffee"};
        for (int i = 0; i < 15; i++) {
            final String[] array = generateRandomArrayFromElements(elements);
            System.out.println(Arrays.toString(array));
        }
    }

    private static String[] generateRandomArrayFromElements(String[] elements) {
        final List<String> list = Arrays.asList(elements);
        Collections.shuffle(list);
        return list.toArray(new String[list.size()]);
    }
}

或者如果你需要可变数量的元素,你可以这样做:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;

public class RandomArrays {
    public static void main(String[] args) {
        String[] elements = new String[]{"Bread", "Milk", "Cereal", "Coffee"};
        for (int i = 0; i < 15; i++) {
            final String[] array = generateRandomArrayFromElements(elements);
            System.out.println(Arrays.toString(array));
        }
    }

    private static String[] generateRandomArrayFromElements(String[] elements) {
        int size = ThreadLocalRandom.current().nextInt(0, elements.length) + 1;
        String[] array = new String[size];
        ArrayList<Integer> usedIndices = new ArrayList<>(size);
        for (int i = 0; i < array.length; i++) {
            int randomIndex = getUniqueRandomIndex(usedIndices, size);
            usedIndices.add(randomIndex);
            array[i] = elements[randomIndex];
        }
        return array;
    }

    private static int getUniqueRandomIndex(ArrayList<Integer> usedIndices, int max) {
        int randomIndex = ThreadLocalRandom.current().nextInt(0, max);
        final boolean contains = usedIndices.contains(randomIndex);
        if (contains)
            randomIndex = getUniqueRandomIndex(usedIndices, max);
        return randomIndex;
    }
}