- for循环+随机数 实现相同位置的元素交换
public <T> void shuffle(List<T> list) {
int size = list.size();
Random random = new Random();
for(int i = 0; i < size; i++) {
int randomPos = random.nextInt(size);
T temp = list.get(i);
list.set(i, list.get(randomPos));
list.set(randomPos, temp);
}
}
Collections.swap实现
public <T> void shuffle(List<T> list) {
int size = list.size();
Random random = new Random();
for(int i = 0; i < size; i++) {
int randomPos = random.nextInt(size);
Collections.swap(list, i, randomPos);
}
}
Collections.shuffle实现
public <T> void shuffle(List<T> list) {
Collections.shuffle(list);
}
List<int> list = new List<int>();
int x;
private void Start()
{
for (int i = 0; i < 10; i++)
{
x = (int)(Random.Range(0,11));
if (list.IndexOf(x)==-1)
{
list.Add(x);
}
}
foreach (var item in list)
{
Debug.Log(item);
}
}
List<int> list = new List<int>();
int x;
private void Start()
{
for (int i = 0; i < 100; i++)
{
list.Add(i);
}
list= ListRandom(list);
foreach (var item in list)
{
Debug.Log(item);
}
}
/// <summary>
/// 随机排列数组元素
/// </summary>
/// <param name="myList"></param>
/// <returns></returns>
private List<int> ListRandom(List<int> myList)
{
System.Random ran = new System.Random();
List<int> newList = new List<int>();
int index = 0;
int temp = 0;
for (int i = 0; i < myList.Count; i++)
{
index = ran.Next(0, myList.Count - 1);
if (index != i)
{
temp = myList[i];
myList[i] = myList[index];
myList[index] = temp;
}
}
return myList;
}