Java parfait aléatoire à l'aide de tableaux


J'ai besoin de créer un programme qui utilise des tableaux qui remue un deck dans l'ordre. Je suis censé couper le jeu original de 52 en deux et placer les cartes dans une nouvelle pile en plaçant alternativement les cartes de l'une ou l'autre pile. L'ordre original 1,2,3,4....49,50,51,52 devrait sortir dans l'ordre 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;
  }

Mon problème est que j'ai une exception hors limites. Je ne sais pas comment résoudre ce problème. Même si je fais un tableau[j * 2 + 1], j'ai toujours ce problème.

Author: Goran Štuc, 2013-11-16

3 answers

Changer shuffle à:

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

Appelez-le comme ceci:

System.out.println(print(shuffle(array, top, bottom)));
 2
Author: Goran Štuc, 2013-11-15 22:41:01
for(int j = 0; j < top.length; j--)

Vous commencez à partir de 0, puis décrémentez j. Ainsi, la deuxième itération essaiera d'accéder à l'index -1. Et en fait, même le premier le fera, car il essaie d'accéder à l'index j*2-1 qui est -1 quand j est 0.

 6
Author: JB Nizet, 2013-11-15 22:20:50

Lors de votre première itération lorsque j=0 array[j*2-1] devient array[-1] et entraîne une exception. Quoi qu'il en soit, toute la logique est incorrecte, il n'y a aucune raison de décrémenter j

 0
Author: user1339772, 2013-11-15 22:26:30