C# ew随机(种子); } 返回(rng);; } } 公共静态IEnumerable Shuffle(此IEnumerable项) { return items.OrderBy(i=>rng.Next()); } }
如果您不介意使用两个C# ew随机(种子); } 返回(rng);; } } 公共静态IEnumerable Shuffle(此IEnumerable项) { return items.OrderBy(i=>rng.Next()); } },c#,generic-list,C#,Generic List,如果您不介意使用两个列表,那么这可能是最简单的方法,但可能不是最有效或最不可预测的方法: List<int> xList = new List<int>() { 1, 2, 3, 4, 5 }; List<int> deck = new List<int>(); foreach (int xInt in xList) deck.Insert(random.Next(0, deck.Count + 1), xInt); List xLis
列表,那么这可能是最简单的方法,但可能不是最有效或最不可预测的方法:
List<int> xList = new List<int>() { 1, 2, 3, 4, 5 };
List<int> deck = new List<int>();
foreach (int xInt in xList)
deck.Insert(random.Next(0, deck.Count + 1), xInt);
List xList=newlist(){1,2,3,4,5};
列表组=新列表();
foreach(xList中的int xInt)
deck.Insert(random.Next(0,deck.Count+1),xInt);
我对这里所有这个简单算法的笨拙版本感到有点惊讶。Fisher Yates(或Knuth shuffle)有点棘手,但非常紧凑。为什么很棘手?因为您需要注意随机数生成器r(a,b)
是否返回b
包含或排除的值。我也编辑过,这样人们就不会盲目地使用伪代码,从而产生难以检测的bug。对于.Net,Random.Next(a,b)
返回不包含b的数字
,因此无需进一步讨论,下面介绍如何在C#/.Net中实现它:
publicstaticvoidshuffle(此IList列表,随机rnd)
{
对于(var i=list.Count;i>0;i--)
交换(0,rnd.Next(0,i));
}
公共静态无效交换(此IList列表,int i,int j)
{
var temp=列表[i];
列表[i]=列表[j];
列表[j]=温度;
}
.公共甲板(IEnumerable initialCards)
{
卡片=新列表(初始卡片);
公开无效洗牌()
}
{
List NewCards=新列表();
而(cards.Count>0)
{
int CardToMove=random.Next(cards.Count);
新增卡片。添加(卡片[CardToMove]);
cards.RemoveAt(CardToMove);
}
卡片=新卡片;
}
公共IEnumerable GetCardNames()
{
string[]CardNames=新字符串[cards.Count];
对于(int i=0;i=0)
如果(deck2.Count>0){
deck1.Add(deck2.Deal(listBox2.SelectedIndex));
}
重绘甲板(1);
重绘甲板(2);
}
使用这个简单的扩展方法可以实现这一点
public static class IEnumerableExtensions
{
public static IEnumerable<t> Randomize<t>(this IEnumerable<t> target)
{
Random r = new Random();
return target.OrderBy(x=>(r.Next()));
}
}
公共静态类IEnumerableExtensions
{
公共静态IEnumerable随机化(此IEnumerable目标)
{
随机r=新随机();
返回target.OrderBy(x=>(r.Next());
}
}
您可以通过执行以下操作来使用它
// use this on any collection that implements IEnumerable!
// List, Array, HashSet, Collection, etc
List<string> myList = new List<string> { "hello", "random", "world", "foo", "bar", "bat", "baz" };
foreach (string s in myList.Randomize())
{
Console.WriteLine(s);
}
//在任何实现IEnumerable的集合上使用此选项!
//列表、数组、哈希集、集合等
List myList=新列表{“你好”、“随机”、“世界”、“foo”、“bar”、“bat”、“baz”};
foreach(myList.Randomize()中的字符串s)
{
控制台。写入线(s);
}
当然是老帖子,但我只使用GUID
Items = Items.OrderBy(o => Guid.NewGuid().ToString()).ToList();
GUID始终是唯一的,并且由于每次结果更改时都会重新生成GUID 当希望不修改原始文件时,这是我首选的洗牌方法。它是的一个变体,适用于任何可枚举序列(源代码的长度不需要从一开始就知道)
生成随机双精度(0到1之间)的要点是用于缩放到整数解。如果您需要从基于随机双精度x
的列表中选择某个对象,那么它总是0一个简单的修改,它返回一个新列表,而不是原地工作,并像许多其他Linq方法一样接受更通用的IEnumerable
private static Random rng = new Random();
/// <summary>
/// Returns a new list where the elements are randomly shuffled.
/// Based on the Fisher-Yates shuffle, which has O(n) complexity.
/// </summary>
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> list) {
var source = list.ToList();
int n = source.Count;
var shuffled = new List<T>(n);
shuffled.AddRange(source);
while (n > 1) {
n--;
int k = rng.Next(n + 1);
T value = shuffled[k];
shuffled[k] = shuffled[n];
shuffled[n] = value;
}
return shuffled;
}
private static Random rng=new Random();
///
///返回一个新列表,其中元素被随机洗牌。
///基于Fisher-Yates洗牌,它具有O(n)复杂度。
///
公共静态IEnumerable Shuffle(此IEnumerable列表){
var source=list.ToList();
int n=源。计数;
var shuffled=新列表(n);
shuffled.AddRange(源);
而(n>1){
n--;
int k=下一个(n+1);
T值=混洗[k];
洗牌[k]=洗牌[n];
洗牌[n]=值;
}
换位;
}
思想是获取带有项目和随机顺序的匿名对象,然后按此顺序和返回值对项目重新排序:
var result = items.Select(x => new { value = x, order = rnd.Next() })
.OrderBy(x => x.order).Select(x => x.value).ToList()
List OriginalList=new List();
列表模板列表=新建列表();
随机=新随机();
int length=原始列表计数;
int TempIndex=0;
而(长度>0){
TempIndex=random.Next(0,长度);//获取0和原始长度之间的随机值
Add(OriginalList[TempIndex]);//添加到临时列表
OriginalList.RemoveAt(TempIndex);//从原始列表中删除
length=OriginalList.Count;//获取新列表长度。
}
OriginalList=新列表();
原始列表=圣堂武士;//将临时列表中的所有项目复制到原始列表中。
我在网上找到了一个有趣的解决方案
礼节:
var shuffled=myList.OrderBy(x=>Guid.NewGuid()).ToList() 这里是Fisher-Yates shuffle的一个实现,它允许指定返回的元素数量;因此,在获取所需数量的元素之前,无需首先对整个集合进行排序
交换元素的顺序与de相反
using System;
using System.Collections.Generic;
using System.Threading;
namespace SimpleLottery
{
class Program
{
private static void Main(string[] args)
{
var numbers = new List<int>(Enumerable.Range(1, 75));
numbers.Shuffle();
Console.WriteLine("The winning numbers are: {0}", string.Join(", ", numbers.GetRange(0, 5)));
}
}
public static class ThreadSafeRandom
{
[ThreadStatic] private static Random Local;
public static Random ThisThreadsRandom
{
get { return Local ?? (Local = new Random(unchecked(Environment.TickCount * 31 + Thread.CurrentThread.ManagedThreadId))); }
}
}
static class MyExtensions
{
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1)
{
n--;
int k = ThreadSafeRandom.ThisThreadsRandom.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
}
public static IEnumerable<T> Randomize<T>(this IEnumerable<T> source)
{
Random rnd = new Random();
return source.OrderBy<T, int>((item) => rnd.Next());
}
var shuffledcards = cards.OrderBy(a => Guid.NewGuid()).ToList();
private static Random rng = new Random();
...
var shuffledcards = cards.OrderBy(a => rng.Next()).ToList();
public static IEnumerable<T> Shuffle<T>(
this IEnumerable<T> source,
Random generator = null)
{
if (generator == null)
{
generator = new Random();
}
var elements = source.ToArray();
for (var i = elements.Length - 1; i >= 0; i--)
{
var swapIndex = generator.Next(i + 1);
yield return elements[swapIndex];
elements[swapIndex] = elements[i];
}
}
public static IEnumerable<T> Shuffle<T>(this IList<T> list)
{
var choices = Enumerable.Range(0, list.Count).ToList();
var rng = new Random();
for(int n = choices.Count; n > 1; n--)
{
int k = rng.Next(n);
yield return list[choices[k]];
choices.RemoveAt(k);
}
yield return list[choices[0]];
}
public byte[] Shuffle(byte[] array, int start, int count)
{
int n = array.Length - start;
byte[] shuffled = new byte[count];
for(int i = 0; i < count; i++, start++)
{
int k = UniformRandomGenerator.Next(n--) + start;
shuffled[i] = array[k];
array[k] = array[start];
array[start] = shuffled[i];
}
return shuffled;
}
public static class EnumerableExtension
{
private static Random globalRng = new Random();
[ThreadStatic]
private static Random _rng;
private static Random rng
{
get
{
if (_rng == null)
{
int seed;
lock (globalRng)
{
seed = globalRng.Next();
}
_rng = new Random(seed);
}
return _rng;
}
}
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> items)
{
return items.OrderBy (i => rng.Next());
}
}
List<int> xList = new List<int>() { 1, 2, 3, 4, 5 };
List<int> deck = new List<int>();
foreach (int xInt in xList)
deck.Insert(random.Next(0, deck.Count + 1), xInt);
public static void Shuffle<T>(this IList<T> list, Random rnd)
{
for(var i=list.Count; i > 0; i--)
list.Swap(0, rnd.Next(0, i));
}
public static void Swap<T>(this IList<T> list, int i, int j)
{
var temp = list[i];
list[i] = list[j];
list[j] = temp;
}
public Deck(IEnumerable<Card> initialCards)
{
cards = new List<Card>(initialCards);
public void Shuffle()
}
{
List<Card> NewCards = new List<Card>();
while (cards.Count > 0)
{
int CardToMove = random.Next(cards.Count);
NewCards.Add(cards[CardToMove]);
cards.RemoveAt(CardToMove);
}
cards = NewCards;
}
public IEnumerable<string> GetCardNames()
{
string[] CardNames = new string[cards.Count];
for (int i = 0; i < cards.Count; i++)
CardNames[i] = cards[i].Name;
return CardNames;
}
Deck deck1;
Deck deck2;
Random random = new Random();
public Form1()
{
InitializeComponent();
ResetDeck(1);
ResetDeck(2);
RedrawDeck(1);
RedrawDeck(2);
}
private void ResetDeck(int deckNumber)
{
if (deckNumber == 1)
{
int numberOfCards = random.Next(1, 11);
deck1 = new Deck(new Card[] { });
for (int i = 0; i < numberOfCards; i++)
deck1.Add(new Card((Suits)random.Next(4),(Values)random.Next(1, 14)));
deck1.Sort();
}
else
deck2 = new Deck();
}
private void reset1_Click(object sender, EventArgs e) {
ResetDeck(1);
RedrawDeck(1);
}
private void shuffle1_Click(object sender, EventArgs e)
{
deck1.Shuffle();
RedrawDeck(1);
}
private void moveToDeck1_Click(object sender, EventArgs e)
{
if (listBox2.SelectedIndex >= 0)
if (deck2.Count > 0) {
deck1.Add(deck2.Deal(listBox2.SelectedIndex));
}
RedrawDeck(1);
RedrawDeck(2);
}
public static class IEnumerableExtensions
{
public static IEnumerable<t> Randomize<t>(this IEnumerable<t> target)
{
Random r = new Random();
return target.OrderBy(x=>(r.Next()));
}
}
// use this on any collection that implements IEnumerable!
// List, Array, HashSet, Collection, etc
List<string> myList = new List<string> { "hello", "random", "world", "foo", "bar", "bat", "baz" };
foreach (string s in myList.Randomize())
{
Console.WriteLine(s);
}
Items = Items.OrderBy(o => Guid.NewGuid().ToString()).ToList();
public static IList<T> NextList<T>(this Random r, IEnumerable<T> source)
{
var list = new List<T>();
foreach (var item in source)
{
var i = r.Next(list.Count + 1);
if (i == list.Count)
{
list.Add(item);
}
else
{
var temp = list[i];
list[i] = item;
list.Add(temp);
}
}
return list;
}
var bytes = new byte[8];
_secureRng.GetBytes(bytes);
var v = BitConverter.ToUInt64(bytes, 0);
return (double)v / ((double)ulong.MaxValue + 1);
return list[(int)(x * list.Count)];
private static Random rng = new Random();
/// <summary>
/// Returns a new list where the elements are randomly shuffled.
/// Based on the Fisher-Yates shuffle, which has O(n) complexity.
/// </summary>
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> list) {
var source = list.ToList();
int n = source.Count;
var shuffled = new List<T>(n);
shuffled.AddRange(source);
while (n > 1) {
n--;
int k = rng.Next(n + 1);
T value = shuffled[k];
shuffled[k] = shuffled[n];
shuffled[n] = value;
}
return shuffled;
}
var result = items.Select(x => new { value = x, order = rnd.Next() })
.OrderBy(x => x.order).Select(x => x.value).ToList()
List<T> OriginalList = new List<T>();
List<T> TempList = new List<T>();
Random random = new Random();
int length = OriginalList.Count;
int TempIndex = 0;
while (length > 0) {
TempIndex = random.Next(0, length); // get random value between 0 and original length
TempList.Add(OriginalList[TempIndex]); // add to temp list
OriginalList.RemoveAt(TempIndex); // remove from original list
length = OriginalList.Count; // get new list <T> length.
}
OriginalList = new List<T>();
OriginalList = TempList; // copy all items from temp list to original list.
collection.TakeRandom(5).SequenceEqual(collection.Shuffle().Take(5)); // true
public static IList<T> TakeRandom<T>(this IEnumerable<T> collection, int count, Random random) => shuffle(collection, count, random);
public static IList<T> Shuffle<T>(this IEnumerable<T> collection, Random random) => shuffle(collection, null, random);
private static IList<T> shuffle<T>(IEnumerable<T> collection, int? take, Random random)
{
var a = collection.ToArray();
var n = a.Length;
if (take <= 0 || take > n) throw new ArgumentException("Invalid number of elements to return.");
var end = take ?? n;
for (int i = 0; i < end; i++)
{
var j = random.Next(i, n);
(a[i], a[j]) = (a[j], a[i]);
}
if (take.HasValue) return new ArraySegment<T>(a, 0, take.Value);
return a;
}
public static void Shuffle<T>(this IList<T> list, Random rnd)
{
for (var i = list.Count-1; i > 0; i--)
{
var randomIndex = rnd.Next(i + 1); //maxValue (i + 1) is EXCLUSIVE
list.Swap(i, randomIndex);
}
}
public static void Swap<T>(this IList<T> list, int indexA, int indexB)
{
var temp = list[indexA];
list[indexA] = list[indexB];
list[indexB] = temp;
}
public class RandomIntComparer : IComparer<int>
{
private readonly Random _random = new Random();
public int Compare(int x, int y)
{
return _random.Next(-1, 2);
}
}
list.Sort(new RandomIntComparer());
using MoreLinq;
...
var randomized = list.Shuffle();
private List<GameObject> ShuffleList(List<GameObject> ActualList) {
List<GameObject> newList = ActualList;
List<GameObject> outList = new List<GameObject>();
int count = newList.Count;
while (newList.Count > 0) {
int rando = Random.Range(0, newList.Count);
outList.Add(newList[rando]);
newList.RemoveAt(rando);
}
return (outList);
}
List<GameObject> GetShuffle = ShuffleList(ActualList);