因此,我创建了一个长度为8的怪物数组。我想选择两个要消灭的随机怪物。我该如何做到这一点而又不可能两次选择相同的怪物?
答案 0 :(得分:1)
这将在数组中找到两个随机项,然后从数组中删除它们:
Exception in thread "main" java.io.IOException: Cannot run program "lp": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at com.test.utd.Test.main(Test.java:12)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
... 5 more
这是RemoveAt扩展方法的作用:
string[] items = new string[] { "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eigth"};
var rnd = new Random();
var firstRemove = rnd.Next(0, items.Length);
var secondRemove = rnd.Next(0, items.Length);
// If they are the same index, keep looking for a different one
while (firstRemove == secondRemove)
{
secondRemove = rnd.Next(0, items.Length);
}
Console.WriteLine("Removing number " + (firstRemove + 1));
Console.WriteLine("Removing number " + (secondRemove + 1));
// Remove the greatest index first, otherwise the indexes will be thrown off as one is removed
if (firstRemove > secondRemove)
{
items = items.RemoveAt(firstRemove);
items = items.RemoveAt(secondRemove);
}
else
{
items = items.RemoveAt(secondRemove);
items = items.RemoveAt(firstRemove);
}
Console.WriteLine(string.Join(", ", items));