【问题标题】:Not sure how to make this deck shuffle不知道如何让这副牌洗牌
【发布时间】:2015-08-25 16:46:00
【问题描述】:
import java.util.*;

public class shuffleDeck
{ 
  public static int shuffleDeck (int[] deck, int theNumber) 
  {
     int [] deck2 = new int [26];
     int [] deck3 = new int [26];
     return theNumber;
  }

  public static void main(String[] args)
  {
    int [] deck = new int [52];
    for(int i=0; i<52; i++)
    {
        deck[i]=i+1;
    }
    int count;
    count=1;
    int total=1;
    shuffleDeck(deck, count);
    System.out.println();
  }
}

在过去的一个小时里,我一直在尝试让这套牌洗牌,但没有运气。我将甲板分成两半,打算洗牌,计算洗牌的次数,然后在洗牌后打印出数组。我根本不确定如何添加第三个将它们全部洗牌的数组。但是,如果有人知道您是否介意告诉我,那就太好了。

【问题讨论】:

  • 你的意思是一个将deck、deck2和deck3打乱的数组吗?
  • 你为什么要把牌分成两半?目前尚不清楚它实现了什么......请参阅en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle 以获得良好的洗牌算法。
  • 是的,我正在尝试洗牌所有牌组
  • 你所说的“所有牌组”是什么意思?你肯定有一副由 52 张牌组成的副牌……
  • 但同样,您从 one 数组开始。您还没有解释为什么要创建两个较小的数组以开始...

标签: java arrays sorting


【解决方案1】:

我不知道你为什么将牌组分成两半,但如果你不需要,那么你可以使用Collections.shuffle()

// Create an array, fill it the way you want
Integer[] deck = new Integer[]{1, 2, 3, 4};

// Shuffle the elements in the array
Collections.shuffle(Arrays.asList(deck));

【讨论】:

  • 不再是正确答案了吗?发生了什么,需要更多帮助吗? :)
【解决方案2】:
public static void shuffle(int[] deck) {
    // the random number generator used to shuffle the deck
    Random random = new Random();
    for (int i = deck.length, j, tmp; i > 1; i--) {
        // get a random position between 0 and i-1
        j = random.nextInt(i); 
        // swap the current position (i-1) with the random one ...
        tmp = deck[i - 1];
        deck[i - 1] = deck[j];
        deck[j] = tmp;
    }
}

【讨论】:

  • 仅仅放下代码可能对 OP 没有多大帮助。至少,将 cmets 放入您的代码中,向 OP 解释它是如何工作的。如果您包含描述为什么 OP 的代码不起作用的文本,它将进一步改善您的答案。
  • 对不起,我教的很不言自明
猜你喜欢
  • 1970-01-01
  • 2012-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-24
相关资源
最近更新 更多