Java perfect shuffle using arrays

喜欢而已 提交于 2021-01-29 16:25:35

问题


I need to create a program that uses arrays that shuffles a deck back into order. I am supposed to cut the original deck of 52 in half and place the cards in a new pile by alternately placing cards from either pile. The original order 1,2,3,4....49,50,51,52 should come out in the order 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;
  }

My problem is that I am having an out of bounds exception. I am not sure how to fix this. Even if I do array[j*2+1] I still have this issue.


回答1:


change shuffle to:

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

    public static String print(int[] array)
  {
String result="";
    for(int j = 0; j < array.length; j++)
    {
      result=result+top[j];
    }
    return result;
  }

call it like this:

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



回答2:


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

You start from 0, and then decrement j. So the second iteration will try to access index -1. And in fact, even the first one will, since it tries to access the index j*2-1 which is -1 when j is 0.




回答3:


On your first iteration when j=0 array[j*2-1] becomes array[-1] and results in exception. Anyways the whole logic is incorrect, there is no reason to decrement j



来源:https://stackoverflow.com/questions/20011599/java-perfect-shuffle-using-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!