洗牌列表< T>
问题说明
我发现这块的Java code在维基百科应该洗牌到位的数组:
I found this piece of Java code at Wikipedia that is supposed to shuffle an array in place:
public static void shuffle (int[] array)
{
Random rng = new Random();
int n = array.length;
while (n > 1)
{
n--;
int k = rng.nextInt(n 1);
int tmp = array[k];
array[k] = array[n];
array[n] = tmp;
}
}
虽然我没有测试code,它看起来像它应该只是罚款阵列。在我的C#项目中,我创建了一个 CardSet
类,并使用上述code在随机播放()
方法:
Though I didn't test the code, it looks like it should work just fine with an array. In my C# project I created a CardSet
class and used the above code in a Shuffle()
method:
public class CardSet
{
private List<Card> cards;
public Card this[int i]
{
get { return cards[i]; }
set { cards[i] = value; }
}
public void Shuffle()
{
Random rng = new Random();
int n = this.NumberOfCards;
while (n < 1)
{
n--;
int k = rng.Next(n 1);
Card tmp = this[k];
this[k] = this[n];
this[n] = tmp;
}
}
在我使用的方法,但是,没有洗牌发生的情况:
When I use the method, however, no shuffling happens:
CardSet cs = new CardSet();
cs.Shuffle();
foreach (Card c in cs)
{
Console.WriteLine(c.ToString());
}
我只是不明白,为什么它不工作。我认为,名单可能是自动分拣的对象,所以我试图改变它的价值之一,
I just can't figure out why it doesn't work. I thought that the List might be automatically sorting its objects, so I tried changing one of its values,
cs[8] = new Card(Suites.Hearts, Numbers.Two);
和卡
正是我放哪儿了。无论我做了一些简单的错误,或者我没有正确地写入洗牌算法。如果code我提供很好看,有人认为这个错误可能是其他地方在我的code,我可以提供我的code中的其余部分。
and that Card
was exactly where I put it. Either I made some simple mistake or I didn't write the shuffling algorithm correctly. If the code I supplied looks good and someone thinks the mistake might be somewhere else in my code, I can supply the rest of my code.
正确答案
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcaegfe
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20