开发者

Divide sequence elements into pairs

开发者 https://www.devze.com 2023-01-02 18:04 出处:网络
I have a sequence of 16 elements: 1,2,3,..., 16 ( or 2*n elements). Sequence elements always goes from 1 to length(sequence) that is sequence of 4 elements is 1,2,3,4.

I have a sequence of 16 elements: 1,2,3,..., 16 ( or 2*n elements). Sequence elements always goes from 1 to length(sequence) that is sequence of 4 elements is 1,2,3,4.

Edit: first 开发者_如何学JAVAsequence element is always = 1, second sequence element = 2, third sequence element = 3 and so on. It's for a game "find a pair pictures".

I want to write an algorithm which divide elements into pairs. For Example, 1-15 2-16 3-13 4-9 5-14 6-10 7-11 8-12

PS: no linq please :) vs2005

Edit: As I can see, my question is so simple so no one can answer it :) Or everybody afraid something ?


Without a selection criteria, just take every other one.....

var result = new List<Tuple<int,int>>();

for (int i = 1; i < size; i+=2 )
{
   var pair = new Tuple.Create(i,i+1);
   result.Add(pair);   
}


What about this?

class Program
{
    static void Main(string[] args)
    {
        int size = 8;

        List<int> tmpList = new List<int>();

        for (int i = size; i <= size * 2; i++)
        {
            tmpList.Add(i);
        }

        List<Pair> result = new List<Pair>();

        Random r = new Random();

        for (int i = 1; i <= size; i++)
        {
            Pair pair = new Pair() { a = i, b = PopRandom(r, tmpList) };
            result.Add(pair);
        }

        foreach (Pair p in result)
        {
            Console.WriteLine("{0} - {1}", p.a, p.b);
        }
    }

    static private int PopRandom(Random r, List<int> list)
    {
        int i = r.Next(0, list.Count);
        int result = list[i];

        list.RemoveAt(i);

        return result;
    }

    struct Pair
    {
        public int a;
        public int b;
    }
}

UPD: this was compiled successfully for .net 2.0 target platform UPD 2: Random instance moved out from PopRandom()

0

精彩评论

暂无评论...
验证码 换一张
取 消