0

E.g. If we have an array [1,2,3,4,6,7,8] then 1 then 2 then 3 then 4 are all consecutive but 6 is not, so that's the first non-consecutive number. If the whole array is consecutive then return null . The array will always have at least 2 elements 1 and all elements will be numbers. The numbers will also all be unique and in ascending order. The numbers could be positive or negative and the first non-consecutive could be either too. please help me finish this code i am new in programming. My code:

using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _2katas
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            var input = this.txtInput.Text;
            var numarray = input.Split(',');
            int firstValue = Convert.ToInt32(numarray[0]);

            
            for (var i = 0; i < numarray.Length; i++)
            {
                if (Convert.ToInt32(numarray[i]) - i != firstValue)
                {
                    lblPrint.Text = "";
                }
               
                else
                {
                    lblPrint.Text = "";
                }



                if (this.rdbConsecutive.Checked == true)
                {
                    lblKataRunning.Text = "Consecutive";
                }
                else if (this.rdbStripCleaning.Checked == true)
                {
                    lblKataRunning.Text = "Strip Cleaning";
                }
            }
        }
    }
}
5
  • please ignore the radio buttons at the end. Commented Aug 5, 2020 at 9:26
  • 1
    Does this answer your question? Finding consecutive numbers in c# Commented Aug 5, 2020 at 9:29
  • "web forms"? do you mean winforms? Commented Aug 5, 2020 at 9:33
  • learn.microsoft.com/en-us/dotnet/api/… Commented Aug 5, 2020 at 9:33
  • @TheGeneral yes Commented Aug 5, 2020 at 9:36

5 Answers 5

1

A linq solution just for the fun of it:

static int? FindFirstNonConsecutive(IEnumerable<int> arr)
{
    var nonConsecutiveInfo = 
          arr.Select((i, index) => new {Index = index, Delta = i - index})
             .FirstOrDefault(t => t.Delta != arr.First());
    
    return nonConsecutiveInfo?.Delta + nonConsecutiveInfo?.Index; 
}

Note that this will only work finding non consecutive numbers in ascending order as per requirements.

Sign up to request clarification or add additional context in comments.

Comments

1

Let's extract a method:

Find the first element of an array that is not consecutive ...

If the whole array is consecutive then return null

We can implement it like this:

private static string FirstInconsecutive(string data) {
  var array = data.Split(',');

  if (array.Length <= 0)
    return null; //TODO: what shall we return on empty array?

  if (!int.TryParse(array[0], out int delta))
    return array[0];

  for (int i = 1; i < array.Length; ++i)
    if (!int.TryParse(array[i], out int value) || value - i != delta)
      return array[i];

  return null;
}

Usage:

string result = FirstInconsecutive(txtInput.Text);

Please note int.TryParse which helps to return the right answer "ABC" on an input like "1, 2, 3, ABC, 4, 6, 7, 8" (user input txtInput.Text can contain any string)

Comments

0

Two numbers are not consecutive if the left ones + 1 <> the right one.

Check with something like this, note that you have to change your boundary checks:

        for (var i = 0; i < numarray.Length - 1; i++)
        {
            if (Convert.ToInt32(numarray[i]) + 1 != Convert.ToInt32(numarray[i+1]))

Comments

0

Update your condition as below for loop and it will work. I would suggest you to have separate function so that it could be reusable if needed elsewhere in code.

Here start your loop from i = 1 and compare numarray[i-1] + 1 != numarray[i] values.

You can convert your sting[] to int[] with var numarray = input.Split(',').Select(x => Convert.ToInt32(x)).ToArray(); and use it with IsConsecutive(numarray) as per button1_Click code.

You can get first non-consecutive value with minor modification in return type and return statement as shown in GetFirstNonConsecutiveValue().

public bool IsConsecutive(int[] numarray)
{
    for (int i = 1; i < numarray.Length; i++)
    {
        if (numarray[i-1] + 1 != numarray[i])
        {
            return false;
        }                
    }
    return true;
}

public int? GetFirstNonConsecutiveValue(int[] numarray)
{
    for (int i = 1; i < numarray.Length; i++)
    {
        if (numarray[i-1] + 1 != numarray[i])
        {
            return numarray[i];
        }                
    }
    return null;
}

private void button1_Click(object sender, EventArgs e)
{
    var input = this.txtInput.Text;
    var numarray = input.Split(',').Select(x => Convert.ToInt32(x)).ToArray();

    var nonConsecutiveValue = GetFirstNonConsecutiveValue(numarray);
    if (nonConsecutiveValue != null)
    {
        // nonConsecutiveValue is first non consecutive value.
    }
    else
    {
        // sequence is consecutive.
    }       
}

1 Comment

The requirement was to find the first non-consecutive element (or null) - so you need to modify your return values.
0

One way to go.

string rawData = "1,2,3,4,6,7,8,9";
IEnumerable<int> data = rawData.Split(',').Select(v => Convert.ToInt32(v));
IEnumerable<int> all = Enumerable.Range(data.Min(), data.Max() - data.Min() + 1);
IEnumerable<int> diff = all.Except(data);
if (diff.Count() == 0)
{
  return null;
}
return data.ElementAt(all.ToList().IndexOf(diff.First()))

NB Not thoroughly tested.

Just test diff for being empty to get the numbers are consecutive

3 Comments

Please, be careful with Enumerable.Range: string rawData = "1,2,3,4,6,7,8,1234567890"; will cause troubles
Another potential problem is integer overflow with data.Max() - data.Min(), e.g. for string rawData = "-1234567890,2,3,4,6,7,8,1234567890"; input
I was going on the OPs very constrained input data and operating on the assumption that some care had already been taken. Could fix that issue, just by moving to long.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.