3

If there is a for loop like

for ( int i = 0; i <= 10; i++ )
{
   //block of code
}

What I want to achieve is, after first iteration i value need not to be 1, it can be anything from 1 to 10, i should not be 0 again and similarly for other iterations.

4

3 に答える 3

7

Simple algorithm:

  • create an array containing numbers from 0 to 10
  • shuffle
  • iterate over that array and retrieve the corresponding index in the initial collection

In Java:

public static void main(String[] args) throws Exception {
    List<Integer> random = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    Collections.shuffle(random);

    List<String> someList = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k");

    for (int i : random) {
        System.out.print(someList.get(i));
    }
}

outputs:

ihfejkcadbg

EDIT

Now that I reread it, you could also simply shuffle the initial collection and loop:

public static void main(String[] args) throws Exception {
    List<String> someList = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j");

    //make a copy if you want the initial collection intact
    List<String> random = new ArrayList<> (someList);
    Collections.shuffle(random);

    for (String s : random) {
        System.out.print(s);
    }
}
于 2013-01-11T11:13:42.947 に答える
6

Yes, you can do that: first, create a random permutation of numbers 0..N-1, and then iterate like this:

int[] randomPerm = ... // One simple way is to use Fisher-Yates shuffle
for (int i in randomPerm) {
    ...
}

Link to Fisher-Yates shuffle.

于 2013-01-11T11:14:10.760 に答える
2

「シャッフル」アプローチがおそらく最も簡単ですが、ランダムな順序でそれらを引き出すことも機能します。これに関する主な問題は、RemoveAt比較的高価なことです。シャッフルはもっと安くなるでしょう。完全を期すために含まれています:

var list = new List<int>(Enumerable.Range(0, 10));
var rand = new Random();
while (list.Count > 0) {
    int idx = rand.Next(list.Count);
    Console.WriteLine(list[idx]);
    list.RemoveAt(idx);
}
于 2013-01-11T11:17:37.220 に答える