Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6653557
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T01:17:05+00:00 2026-05-26T01:17:05+00:00

This question is pretty much the opposite of this question: Does C# have built-in

  • 0

This question is pretty much the opposite of this question:
Does C# have built-in support for parsing page-number strings?

So given

1,3,5,6,7,8,9,10,12:

I will ouput:

1,3,5-10,12

Here is my first attempt. It seems kind of hacky and is probably the worst code I ever wrote. Can you suggest an imporovement\better way to do it?

static string numListToRangeStr(List<int> numList)
{
    StringBuilder retString = new StringBuilder();
    numList.Sort();

    bool inRangeFind = false;
    int firstInRange = numList[0];
    int lastNumber = firstInRange;
    bool first = true;

    for (int i = 1; i < numList.Count; i++)
    {
        if (numList[i] == (lastNumber + 1))
        {
            inRangeFind = true;
        }
        else
        {             
            if (inRangeFind)
            {
                if (!first)
                {
                    retString.Append(",");
                }
                retString.Append(firstInRange);
                retString.Append("-");
            }
            else
            {
               if (!first)
                {
                    retString.Append(",");
                }
            }

            retString.Append(lastNumber);

            firstInRange = numList[i];
            inRangeFind = false;
            first = false;
        }

        lastNumber = numList[i];
    }


    if (inRangeFind)
    {
        if (!first)
        {
            retString.Append(",");
        }
        retString.Append(firstInRange);
        retString.Append("-");
    }
    else
    {
        if (!first)
        {
            retString.Append(",");
        }
    }
    retString.Append(lastNumber);

    return retString.ToString();
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T01:17:06+00:00Added an answer on May 26, 2026 at 1:17 am

    When something has several moving parts like this, I think it helps to decompose it into little logical units and then combine them together. The little logical units might even be usable separately. The code below breaks the problem down into:

    • turning the heterogeneous set of sequential and nonsequential numbers into a homogenous set of ranges (possibly including “degenerate” ranges which start and end at the same number)
    • a way to “pretty-print” such ranges: (x,y) prints as “x-y”; (x,x) prints as “x”
    • a way to interperse a separator between elements of an enumerable, and convert the result into a string.

    The program is:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication37 {
      public static class Program {
        static void Main(string[] args) {
          var numList=new[] {1, 3, 5, 6, 7, 8, 9, 10, 12};
          Console.WriteLine(numListToPossiblyDegenerateRanges(numList).Select(r => PrettyRange(r)).Intersperse(","));
        }
    
        /// <summary>
        /// e.g. 1,3,5,6,7,8,9,10,12
        /// becomes
        /// (1,1),(3,3),(5,10),(12,12)
        /// </summary>
        public static IEnumerable<Tuple<int,int>> numListToPossiblyDegenerateRanges(IEnumerable<int> numList) {
          Tuple<int, int> currentRange=null;
          foreach(var num in numList) {
            if(currentRange==null) {
              currentRange=Tuple.Create(num, num);
            } else if(currentRange.Item2==num-1) {
              currentRange=Tuple.Create(currentRange.Item1, num);
            } else {
              yield return currentRange;
              currentRange=Tuple.Create(num, num);
            }
          }
          if(currentRange!=null) {
            yield return currentRange;
          }
        }
    
        /// <summary>
        /// e.g. (1,1) becomes "1"
        /// (1,3) becomes "1-3"
        /// </summary>
        /// <param name="range"></param>
        /// <returns></returns>
        public static string PrettyRange(Tuple<int,int> range) {
          if(range.Item1==range.Item2) {
            return range.Item1.ToString();
          }
          return string.Format("{0}-{1}", range.Item1, range.Item2);
        }
    
        public static string Intersperse(this IEnumerable<string> items, string interspersand) {
          var currentInterspersand="";
          var result=new StringBuilder();
          foreach(var item in items) {
            result.Append(currentInterspersand);
            result.Append(item);
            currentInterspersand=interspersand;
          }
          return result.ToString();
        }
      }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This question does pretty much what I want to accomplish, but my table is
I am pretty much sure that this question have been asked and answered several
I have seen posts which explains pretty much this question but they all used
Apologies for making this my second Z80 DAA question - I have pretty much
Ok, so I think the title of this question pretty much sums it up.
This question is pretty much the same as this .Net question exept for java.
Pretty much the same as this question. But I can't seem to get this
This is pretty much a duplicate question but instead of using Castle Dynamic Proxy
This is a pretty-much theoretical question, but.. How much of an operating system could
I realize this question is pretty basic, but I'm really stuck. I have a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.