none
Need Help Understanding This Code RRS feed

  • Question

  • Hello, and thanks.  Can someone help me out understanding the bold code?  I know it is comparing sequential numbers, but I do not see how this correlates to descending counts.


    namespace CSharp1Exercises.Text
    {
        public class Strings
        {
            /// <summary>
            /// Write a program and ask the user to enter a few numbers separated by a hyphen. Work out 
            /// if the numbers are consecutive. For example, if the input is "5-6-7-8-9" or "20-19-18-17-16", 
            /// display a message: "Consecutive"; otherwise, display "Not Consecutive".
            /// </summary>
            public void Exercise1()
            {
                Console.Write("Enter a few numbers (eg 1-2-3-4): ");
                var input = Console.ReadLine();
    
                var numbers = new List<int>();
                foreach (var number in input.Split('-'))
                    numbers.Add(Convert.ToInt32(number));
    
                numbers.Sort();
    
                var isConsecutive = true;
                for (var i = 1; i < numbers.Count; i++)
                {
                    if (numbers[i] != numbers[i - 1] + 1)
                    {
                        isConsecutive = false;
                        break;
                    }
                }
    
                var message = isConsecutive ? "Consecutive" : "Not Consecutive";
                Console.WriteLine(message);
            }
        }
    }



    Sunday, May 13, 2018 3:38 AM

Answers

  • E.g.input= "5-6-7-9"

    then numbers will be a list with numbers[0]=5,numbers[1]=6,numbers[2]=7,numbers[3]=9

    list first needs to sorted

    Now we have to check whether the list contains consecutive numbers

    So logic is that numbers[i] should be equal to numbers[i-1]+1; we should check this for all elements in the list.

    initially  isConsecutive = true i.e. assume it to be Consecutive

    i                  Condition to check-->numbers[i] != numbers[i - 1] + 1       Description

    1                 numbers[1]!=numbers[0]+1                                               6=5+1-->false-->continue

    2                 numbers[2]!=numbers[1]+1                                               7=6+1-->false-->continue

    3                 numbers[3]!=numbers[2]+1                                               9!=7+1--> true-->break

    Here as soon as condition is matched we break the loop  & set  isConsecutive = false   & hence numbers are not consecutive

    You can test it step by step as

     public void Exercise1()
            {
                Console.Write("Enter a few numbers (eg 1-2-3-4): ");
                var input = Console.ReadLine();
    
                var numbers = new List<int>();
                foreach (var number in input.Split('-'))
                    numbers.Add(Convert.ToInt32(number));
    
                numbers.Sort();
    
                var isConsecutive = true;
                for (var i = 1; i < numbers.Count; i++)
                {
                    Console.Write("{0} {1} {2}+1",numbers[i], numbers[i] == numbers[i - 1] + 1 ? "Equals" : "Not Equals",numbers[i - 1]);
                    Console.ReadKey();
                    if (numbers[i] != numbers[i - 1] + 1)
                    {
                        isConsecutive = false;
                        break;
                    }
                }
    
                var message = isConsecutive ? "Consecutive" : "Not Consecutive";
                Console.WriteLine(message);
                Console.ReadKey();
            }

               

     




    Sunday, May 13, 2018 3:57 AM
  • The Line

    Console.Write("{0} {1} {2}+1",numbers[i], numbers[i] == numbers[i - 1] + 1 ? "Equals" : "Not Equals",numbers[i - 1]);

    is used for getting step by step information

    Here, string is formatted with arguments as

    {0}=numbers[i]

    {1}=(numbers[i] == numbers[i - 1] + 1 ? "Equals" : "Not Equals")

    {2}=numbers[i - 1]

    So we are displaying the info. in format such as 6 Equals 5+1 or like 9 Not Equals 7+1

    Here 6, Equals & 5 are 3 arguments

    Number of parameters must match with provided arguments i.e. each of {0}, {1}, {2} should be provided with an argument. (argument=actual value passed)


    Sunday, May 13, 2018 5:22 AM
  • If numbers were descending just change the condition like number[i]!=number[i-1]-1 as next number should be one less than previous

    Check by following code:

      public void Exercise1()
            {
                Console.Write("Enter a few numbers (eg 1-2-3-4): ");
                var input = Console.ReadLine();
    
                var numbers = new List<int>();
                foreach (var number in input.Split('-'))
                    numbers.Add(Convert.ToInt32(number));
    
                //Sort Ascending
                numbers.Sort();
                //Reverse to get Descending
                numbers.Reverse();
                Console.Write("Sorted List:");
                foreach (int item in numbers)
                    Console.Write(item + " ");
                Console.WriteLine();
    
                var isConsecutive = true;
                for (var i = 1; i < numbers.Count; i++)
                {
                    Console.Write("{0} {1} {2}-1\n", numbers[i], numbers[i] == numbers[i - 1] - 1 ? "Equals" : "Not Equals", numbers[i - 1]);
                    if (numbers[i] != numbers[i - 1] - 1)
                    {
                        isConsecutive = false;
                        break;
                    }
                }
    
                var message = isConsecutive ? "Consecutive" : "Not Consecutive";
                Console.WriteLine(message);
                Console.ReadKey();
            }


    Sunday, May 13, 2018 8:08 AM
  • Actually, I'm wondering if the intent of the exercise is to actually sort the input the user has entered it, or is it to determine if they have entered the numbers sequentially (so, without sorting)?

    Your example shows sorting. Without sorting, you could check it like this:

    var isConsecutive = true;
    var isAscending = true;
    if (numbers.Length > 1 && numbers[0] > numbers[1])
        isAscending = false;
    
    for (var i = 1; i < numbers.Count; i++)
    {
        if (isAscending && numbers[i] != numbers[i - 1] + 1)
        {
            isConsecutive = false;
            break;
        }
        else if (!isAscending && numbers[i] != numbers[i - 1] - 1)
        {
            isConsecutive = false;
            break;
        }
    }
    


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Sunday, May 13, 2018 4:40 PM
    Moderator
  • So, it seems the answer is that it doesn't matter the order of number entry. Only whether the series of numbers are consecutive. At least according to the answer provided.

    Oh!! ... wait a minute ... does that mean that the code you initially posted was part of the exercise, and that it showed the answer to the exercise? If so, then forget everything I said. I misunderstood. I thought that the code you posted was your attempt at solving the exercise.

    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Sunday, May 13, 2018 11:25 PM
    Moderator

All replies

  • E.g.input= "5-6-7-9"

    then numbers will be a list with numbers[0]=5,numbers[1]=6,numbers[2]=7,numbers[3]=9

    list first needs to sorted

    Now we have to check whether the list contains consecutive numbers

    So logic is that numbers[i] should be equal to numbers[i-1]+1; we should check this for all elements in the list.

    initially  isConsecutive = true i.e. assume it to be Consecutive

    i                  Condition to check-->numbers[i] != numbers[i - 1] + 1       Description

    1                 numbers[1]!=numbers[0]+1                                               6=5+1-->false-->continue

    2                 numbers[2]!=numbers[1]+1                                               7=6+1-->false-->continue

    3                 numbers[3]!=numbers[2]+1                                               9!=7+1--> true-->break

    Here as soon as condition is matched we break the loop  & set  isConsecutive = false   & hence numbers are not consecutive

    You can test it step by step as

     public void Exercise1()
            {
                Console.Write("Enter a few numbers (eg 1-2-3-4): ");
                var input = Console.ReadLine();
    
                var numbers = new List<int>();
                foreach (var number in input.Split('-'))
                    numbers.Add(Convert.ToInt32(number));
    
                numbers.Sort();
    
                var isConsecutive = true;
                for (var i = 1; i < numbers.Count; i++)
                {
                    Console.Write("{0} {1} {2}+1",numbers[i], numbers[i] == numbers[i - 1] + 1 ? "Equals" : "Not Equals",numbers[i - 1]);
                    Console.ReadKey();
                    if (numbers[i] != numbers[i - 1] + 1)
                    {
                        isConsecutive = false;
                        break;
                    }
                }
    
                var message = isConsecutive ? "Consecutive" : "Not Consecutive";
                Console.WriteLine(message);
                Console.ReadKey();
            }

               

     




    Sunday, May 13, 2018 3:57 AM
  • Thank you Vikram!
    Sunday, May 13, 2018 4:04 AM
  • Vikram, why is the last part necessary?

                    Console.Write("{0} {1} {2}+1", numbers[i], numbers[i] == numbers[i - 1] + 1 ? "Equals" : "Not Equals", numbers[i - 1]);


    Sunday, May 13, 2018 4:25 AM
  • The Line

    Console.Write("{0} {1} {2}+1",numbers[i], numbers[i] == numbers[i - 1] + 1 ? "Equals" : "Not Equals",numbers[i - 1]);

    is used for getting step by step information

    Here, string is formatted with arguments as

    {0}=numbers[i]

    {1}=(numbers[i] == numbers[i - 1] + 1 ? "Equals" : "Not Equals")

    {2}=numbers[i - 1]

    So we are displaying the info. in format such as 6 Equals 5+1 or like 9 Not Equals 7+1

    Here 6, Equals & 5 are 3 arguments

    Number of parameters must match with provided arguments i.e. each of {0}, {1}, {2} should be provided with an argument. (argument=actual value passed)


    Sunday, May 13, 2018 5:22 AM
  • According to the logic description, if the numbers were descending, rather than ascending, the argument wont work, from what I see?  if number[0] = 8, number[1]=7, number[2]=6, number[3] =5


    then:

    i                  Condition to check-->numbers[i] != numbers[i - 1] + 1       Description

    1                 numbers[1]!=numbers[0]+1                                               7=8+1 would be true right?

    What am I missing?



    Sunday, May 13, 2018 7:31 AM
  • If numbers were descending just change the condition like number[i]!=number[i-1]-1 as next number should be one less than previous

    Check by following code:

      public void Exercise1()
            {
                Console.Write("Enter a few numbers (eg 1-2-3-4): ");
                var input = Console.ReadLine();
    
                var numbers = new List<int>();
                foreach (var number in input.Split('-'))
                    numbers.Add(Convert.ToInt32(number));
    
                //Sort Ascending
                numbers.Sort();
                //Reverse to get Descending
                numbers.Reverse();
                Console.Write("Sorted List:");
                foreach (int item in numbers)
                    Console.Write(item + " ");
                Console.WriteLine();
    
                var isConsecutive = true;
                for (var i = 1; i < numbers.Count; i++)
                {
                    Console.Write("{0} {1} {2}-1\n", numbers[i], numbers[i] == numbers[i - 1] - 1 ? "Equals" : "Not Equals", numbers[i - 1]);
                    if (numbers[i] != numbers[i - 1] - 1)
                    {
                        isConsecutive = false;
                        break;
                    }
                }
    
                var message = isConsecutive ? "Consecutive" : "Not Consecutive";
                Console.WriteLine(message);
                Console.ReadKey();
            }


    Sunday, May 13, 2018 8:08 AM
  • That's really kind of you to take the time Vikram.  I will go over the iterations part of my beginner course again tonight and review what you provided!!
    Sunday, May 13, 2018 10:22 AM
  • Actually, I'm wondering if the intent of the exercise is to actually sort the input the user has entered it, or is it to determine if they have entered the numbers sequentially (so, without sorting)?

    Your example shows sorting. Without sorting, you could check it like this:

    var isConsecutive = true;
    var isAscending = true;
    if (numbers.Length > 1 && numbers[0] > numbers[1])
        isAscending = false;
    
    for (var i = 1; i < numbers.Count; i++)
    {
        if (isAscending && numbers[i] != numbers[i - 1] + 1)
        {
            isConsecutive = false;
            break;
        }
        else if (!isAscending && numbers[i] != numbers[i - 1] - 1)
        {
            isConsecutive = false;
            break;
        }
    }
    


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Sunday, May 13, 2018 4:40 PM
    Moderator
  • Thanks Bonnie, that's very interesting!  I appreciate the alternative explanation.  It shows me there are different ways to do the same thing.  At first I got thrown by Sort.  I missed its function.  I couldn't understand why numbers entered in descending order were not causing isConsecutive to be false.  In the inclusion of sort it makes only one mathematical parameter numbers[i] = numbers[i-1]+1 necessary right?  I guess it is a simplification of "sorts".  
    Sunday, May 13, 2018 8:43 PM
  • Thanks Bonnie, that's very interesting!  I appreciate the alternative explanation.  It shows me there are different ways to do the same thing. 

    Well, it's really not the same thing. It all depends on what the intent of the exercise is. 

    Are you supposed to determine "consecutiveness", based on the numbers *alone*?

    -- Or --

    Are you supposed to determine "consecutiveness", based on the numbers *as they were entered*?

    The code I proposed will actually work for either scenario (although, as you said, with the sort you only need to check in one direction, ascending). But, keep in mind that these *are* two different interpretations of the exercise. I have no idea which is expected ... sorting or not.

    At first I got thrown by Sort.  I missed its function.  I couldn't understand why numbers entered in descending order were not causing isConsecutive to be false.  In the inclusion of sort it makes only one mathematical parameter numbers[i] = numbers[i-1]+1 necessary right?  I guess it is a simplification of "sorts".  
    It sounds to me, from the summary comment, that numbers entered in descending order should also be considered for "consecutiveness".


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Sunday, May 13, 2018 9:16 PM
    Moderator
  • The only instruction provided was as follows:  

            /// <summary>
            /// Write a program and ask the user to enter a few numbers separated by a hyphen. Work out 
            /// if the numbers are consecutive. For example, if the input is "5-6-7-8-9" or "20-19-18-17-16", 
            /// display a message: "Consecutive"; otherwise, display "Not Consecutive".
            /// </summary>

    So, it seems the answer is that it doesn't matter the order of number entry. Only whether the series of numbers are consecutive. At least according to the answer provided.
    Sunday, May 13, 2018 9:21 PM
  • The only instruction provided was as follows:  

            /// <summary>
            /// Write a program and ask the user to enter a few numbers separated by a hyphen. Work out 
            /// if the numbers are consecutive. For example, if the input is "5-6-7-8-9" or "20-19-18-17-16", 
            /// display a message: "Consecutive"; otherwise, display "Not Consecutive".
            /// </summary>

    So, it seems the answer is that it doesn't matter the order of number entry. Only whether the series of numbers are consecutive. At least according to the answer provided.

    Right, and I was thinking that the comment *could* mean that "5-7-6-8-9" or "20-18-19-17-16"  is *not* consecutive!!


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Sunday, May 13, 2018 11:20 PM
    Moderator
  • So, it seems the answer is that it doesn't matter the order of number entry. Only whether the series of numbers are consecutive. At least according to the answer provided.

    Oh!! ... wait a minute ... does that mean that the code you initially posted was part of the exercise, and that it showed the answer to the exercise? If so, then forget everything I said. I misunderstood. I thought that the code you posted was your attempt at solving the exercise.

    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Sunday, May 13, 2018 11:25 PM
    Moderator
  • You did point out something very important to understand!  I should have stated that more clearly, but thanks a lot for your input.  It really helps!!
    Monday, May 14, 2018 2:56 AM