【问题标题】:adding items to arrays alternatively或者将项目添加到数组
【发布时间】:2012-02-10 17:50:48
【问题描述】:

我想要一个可以将生成的随机数(唯一不重复)交替添加到 2 个数组的程序... 这是我到目前为止所做的:

int n = 56,m=0;
 int e=0,f=0;
 int[] deck1 = new int[n];
 int[] deck2 = new int[m];
        Random rng = new Random(); 
List<Integer> generated = new ArrayList<Integer>();
for(int i=1;i<=53;i++)
{
    while(true)
    {
        next = rng.nextInt(53) + 1;
        if (!generated.contains(next))
        {
            generated.add(next);
            break;
        } 
    }
   for(int t = 2;t<=i;t++)
   if(t%2==0)
   {deck1[e]=next;e++;}
    else
   {deck2[f]=next;f++;}

    }

但我没有得到结果。请帮忙。 谢谢。

【问题讨论】:

  • “我没有得到结果”在诊断上并不是特别有用。与您的预期相比,正在发生什么?请阅读tinyurl.com/so-hints
  • 应该m 等于零吗?看来您正在将deck2 初始化为一个空数组。

标签: java arrays random add


【解决方案1】:

您可以通过忘记内部的for 循环(迭代t)来解决您的直接问题,而是使用i 进行计算:

if ( i % 2 == 0 ) {
    deck1[e] = next;
    e++;
} else {
    //...

问题是目前在循环的每次迭代中,您将元素多次添加到每个数组中(最多 i 次)。

其他一些建议:

  • Make 生成了一个Set&lt;Integer&gt; (HashSet&lt;Integer&gt;),它更适合这个任务
  • 更好的算法是构造一个包含数字 1 到 53 的 List&lt;Integer&gt; 并随机播放(例如,使用 Collections.shuffle())。然后您可以将列表的前半部分添加到deck1,将后半部分添加到deck2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-16
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多