C # из массива создает несмежное подмножество - PullRequest
1 голос
/ 21 октября 2019

Я хочу создать подмножество из массива

array =[-2,1,3,-4,5]

Я хочу подмножество, как показано ниже.

[- 2, 3, 5] [-2, 3] [-2, -4] [-2, 5] [1, -4] [1,5] [3, 5]

    -before the elements should be skipped one element
    -2,3,5
     1 -4
     3.5
    -then for each element, one neighbor should be skipped and the others taken one by  one, forming pairs (without repeating the above)
    -2,3
    -2, -4
    -2.5
     1, -4 (do not take above have)
     3.5 ((we do not have above)
    -1.5

     //This is my code.
    static void Main(string[] args)
    {
        int[] kume = { -3, 4, 5, 6, 7};
        String[] altkume = new string[10];
        String s = "";
        for(int m = 0; m<7; m++)
        {
            int b = m;
            s += "[";
            for (int j = 0; j < kume.Length; j += 2)
            {                    
                if ((b & 1) == 0)
                {
                    s += kume[j].ToString() + ",";
                }
                b = b >> 1;                      
            }
            s += "]" + "\n";
            altkume[m] = s;

        }


        for(int i = 0; i<altkume.Length; i++)
        {


            Console.WriteLine(altkume[i]);
        }

        Console.ReadKey();
    }
Output: 
[-3,5,7,]
[5,7,]
[-3,7,]
[7,]
[-3,5,]
[5,]
[-3,]

Но я не хочу вот так [5,] [-3,] [7,]

Я говорил о проблеме. кто-нибудь помогает?

1 Ответ

0 голосов
/ 21 октября 2019

Я сделал удобное расширение, которое будет возвращать искомый вывод:

public static class Extensions
{
    public static IEnumerable<List<T>> GetNonAdjacentSubsets<T>
    (
        this IEnumerable<T> source, // the collection we are evaluating
        int min_distance,           // minimum gap between numbers
        List<T> subset = null       // stores the progress of the subset we are evaluating
    )
    {
        for (int i = 0; i < source.Count(); i++)
        {
            var new_subset = new List<T>(subset ?? Enumerable.Empty<T>())
            {
                source.ElementAt(i)
            };

            if (new_subset.Count > 1) //return subsets of more than one element
                yield return new_subset;

            if (source.Count() < 2) //end of list reached
                yield break;

            foreach (var ss in source.Skip(i + min_distance).GetNonAdjacentSubsets(min_distance, new_subset))
                yield return ss;
        }
    }
}

Использование:

var arr = new int[] { -2, 1, 3, -4, 5 };
var subsets = new List<List<int>>(arr.GetNonAdjacentSubsets(2));

Вывод:

-2, 3

-2, 3, 5

-2, -4

-2, 5

1, -4

1, 5

3, 5

...