Java使用数组完美shuffle

标签 java arrays shuffle

我需要创建一个程序,使用数组将一副牌重新排序。我应该将原来的 52 张牌切成两半,并通过交替放置任一堆牌中的牌将牌放入新的牌堆中。原始顺序 1,2,3,4....49,50,51,52 应按 1,27,2,28,3...26,52 的顺序出现。

 public static void main(String[] args)
  {
    int[] array = new int[52];
    int[] top = new int[26];
    int[] bottom = new int[26];

    for(int i=0; i < 52; i++)
    {
      array[i] = i+1;
    }
    for(int i = 0; i < 26; i++)
    {
      top[i] = array[i];
    }
    for(int i = 0; i < 26; i++)
    {
     bottom[i] = array[i+26];
    }

    System.out.println(shuffle(array, top, bottom));
  }

  public static int[] shuffle(int[] array, int[] top, int[] bottom)
  {
    for(int j = 0; j < top.length; j--)
    {
      array[j*2] = top[j];
      array[j*2-1] = bottom[j];
    }
    return array;
  }

我的问题是遇到越界异常。我不知道如何解决这个问题。即使我执行 array[j*2+1] 我仍然有这个问题。

最佳答案

for(int j = 0; j < top.length; j--)

从 0 开始,然后递减 j。所以第二次迭代将尝试访问索引-1。 事实上,即使是第一个也会,因为它尝试访问索引 j*2-1,当 j 为 0 时,该索引为 -1。

关于Java使用数组完美shuffle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20011599/

相关文章:

java - SWIG从String作为Java中的String数组获取returntype

javascript - replaceChild() 移动图像仅在 javascript 中运行一次

C# 长度为 1 的数组与单值、性能和内存开销

python - 请求 + : 'range' and 'list' 不支持的操作数类型

java - 查找两个矩阵之间的偏移量

java - 最后一个线程没有执行

c++ - 在 C++ 中,这是顺序访问二维数组的方式(内存块方式)

Javascript shuffle 没有按预期工作

javascript - 单词随机播放算法(PHP 或 javascript)

java - Twitter twitter4j 2.2.5 中的空指针异常