Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all consecutive numbers in an int[]

Tags:

c#

.net

c#-4.0

I want to find all the consecutive numbers in a an ordered int[8] of casual numbers from 0 to 31. The consecutive numbers must be from minimum length of 3 and a max of 5 numbers.

In the example the last give me very real problem.

ex:

int[] = new int[] { 3,7,14,16,23, 28, 29 ,30 } // no  result (28,29 is length of 2 numbers)

int[] = new int[] { 4,5,6,7,18, 19, 20 ,21 }  // 4,5,6,7 (yes! length of 4!!)

int[] = new int[] { 2.3.4.5.6.7.8.9 } // two results : 2,3,4 and 5,6,7,8,9  

I don't want the solution but just an example of how approach the question because I'm trying using generals and I'm really stuck!

Really thanks for help!

Christian

-this is the code from where I started (not soup from my kitchen)

public partial class Test2 : Form
{
    public Test2()
    {
        InitializeComponent();
    }

    private void Test2_Load(object sender, EventArgs e)
    {          

         int[] numbers = new[] { 21, 4, 5, 22, 17, 6, 20, 23 };

      //  int[] numbers = new[] { 1, 2, 3, 4, 5, 6, 7, 8 };

        foreach (Campo r in FindRanges(numbers, 3))
        {
            listBox1.Items.Add(string.Join(", ", r.Select(x => x.ToString()).ToArray()));
        }



    }


    struct Campo : IEnumerable<int>
    {
        readonly int _start;
        readonly int _count;

        public Campo(int start, int count)
        {
            _start = start;
            _count = count;
        }

        public int Start
        {
            get { return _start; }
        }

        public int Count
        {
            get { return _count; }
        }

        public int End
        {
            get { return _start + _count - 1; }

        }

        public IEnumerator<int> GetEnumerator()
        {
            for (int i = 0; i < _count; ++i)
            {
                yield return _start + i;
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {

            return this.GetEnumerator();

        }


        public static Campo operator +(Campo x, int y)
        {
            return new Campo(x.Start, x.Count + y);
        }

        public Campo removefirst()
        {
            return new Campo(this.Start + 3, this.Count);
        }

        public Campo removelast()
        {
            return new Campo(this.Start, this.Count - 1);
        }
    }

    static IEnumerable<Campo> FindRanges(IEnumerable<int> source, int minCount)
    {


        var ordered = source.OrderBy(x => x);

        Campo r = default(Campo);

        foreach (int value in ordered)
        {

            if (r.Count == 0)
            {
                r = new Campo(value, 1);
                continue;
            }


            if (r.Count == 5)
            {
                r = r.removefirst();

                continue;
            }

            if (value == r.End)
            {
               continue;
            }


            if ((value == 0 || value == 8 || value == 16 || value == 24) && (r.Count > minCount))
            {
                continue;
            }

            if ((value == 7 || value == 15 || value == 23 || value == 31) && (r.Count == 1))
            {
                continue;
            }

            else if (value == r.End + 1)
            {
               r += 1;
            }
            else
            {

                if (r.Count >= minCount)
                {
                    yield return r;
                }


                r = new Campo(value, 1);
            }
        }


        if (r.Count >= minCount)
        {
            yield return r;
        }
    }

}

like image 464
CB. Avatar asked Nov 25 '10 20:11

CB.


People also ask

How do you find consecutive numbers in an array?

Method 1 (Use Sorting) 1) Sort all the elements. 2) Do a linear scan of the sorted array. If the difference between the current element and the next element is anything other than 1, then return false. If all differences are 1, then return true.

How do you find consecutive integers of a number?

If n is an integer, (n + 1) and (n + 2) will be the next two consecutive integers. For example, let n be 1. We find its consecutive integers as (1 + 1) and (1 + 2), or 2 and 3.

What is the formula to find consecutive numbers?

Consecutive Numbers Formula{a + (n-1)}]. So, the sum of 'n' consecutive numbers or sum of 'n' terms of AP (Arithmetic Progression) = (n/2) × (first number + last number). Even Consecutive Numbers Formula = 2n, 2n+2, 2n+4, 2n+6,… Odd Consecutive Numbers Formula = 2n+1, 2n+3, 2n+5, 2n+7,…


2 Answers

I suggest you take some examples and write them out on paper. Carefully work out what you're intuitively doing when you try to solve them by hand - and convert that into code.

You'll probably want to keep a count of how many values you've already found in the sequence, and what the previous value was...

like image 73
Jon Skeet Avatar answered Oct 12 '22 04:10

Jon Skeet


sorry for the late update but time is very oppressor....

This my final solution with all necessary limits (for my needs) for serier. Thank you all

static IEnumerable<IEnumerable<int>> Sequences(IEnumerable<int> input, bool ascen = false, int min = 3)
    {
        int ord = ascen == false ? -1 : 1;

        input = ord == -1 ? input.OrderByDescending(x => x) : input.OrderBy(x => x);

        var seq = new List<List<int>>();
        foreach (var i in input)
        {
            var existing = seq.FirstOrDefault(lst => lst.Last() + ord == i);
            if ((existing == null) || (seq.Last().Count == 5) || i == 7 || i == 15 || i == 23)

                seq.Add(new List<int> { i });
            else
                existing.Add(i);
        }
        return min <= 1 ? seq : seq.Where(lst => lst.Count >= min);
    }
like image 41
CB. Avatar answered Oct 12 '22 04:10

CB.